Fix *printf result for NaN, Inf, -0.0 on mingw.
[gnulib.git] / lib / vasnprintf.c
1 /* vsprintf with automatic memory allocation.
2    Copyright (C) 1999, 2002-2007 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 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
19    This must come before <config.h> because <config.h> may include
20    <features.h>, and once <features.h> has been included, it's too late.  */
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE    1
23 #endif
24
25 #include <config.h>
26 #ifndef IN_LIBINTL
27 # include <alloca.h>
28 #endif
29
30 /* Specification.  */
31 #if WIDE_CHAR_VERSION
32 # include "vasnwprintf.h"
33 #else
34 # include "vasnprintf.h"
35 #endif
36
37 #include <locale.h>     /* localeconv() */
38 #include <stdio.h>      /* snprintf(), sprintf() */
39 #include <stdlib.h>     /* abort(), malloc(), realloc(), free() */
40 #include <string.h>     /* memcpy(), strlen() */
41 #include <errno.h>      /* errno */
42 #include <limits.h>     /* CHAR_BIT */
43 #include <float.h>      /* DBL_MAX_EXP, LDBL_MAX_EXP */
44 #if HAVE_NL_LANGINFO
45 # include <langinfo.h>
46 #endif
47 #if WIDE_CHAR_VERSION
48 # include "wprintf-parse.h"
49 #else
50 # include "printf-parse.h"
51 #endif
52
53 /* Checked size_t computations.  */
54 #include "xsize.h"
55
56 #if NEED_PRINTF_INFINITE && !defined IN_LIBINTL
57 # include <math.h>
58 # include "isnan.h"
59 #endif
60
61 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
62 # include <math.h>
63 # include "float+.h"
64 #endif
65
66 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
67 # include <math.h>
68 # include "isnan.h"
69 # include "printf-frexp.h"
70 # include "isnanl-nolibm.h"
71 # include "printf-frexpl.h"
72 # include "fpucw.h"
73 #endif
74
75 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW.  */
76 #ifndef EOVERFLOW
77 # define EOVERFLOW E2BIG
78 #endif
79
80 #if HAVE_WCHAR_T
81 # if HAVE_WCSLEN
82 #  define local_wcslen wcslen
83 # else
84    /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
85       a dependency towards this library, here is a local substitute.
86       Define this substitute only once, even if this file is included
87       twice in the same compilation unit.  */
88 #  ifndef local_wcslen_defined
89 #   define local_wcslen_defined 1
90 static size_t
91 local_wcslen (const wchar_t *s)
92 {
93   const wchar_t *ptr;
94
95   for (ptr = s; *ptr != (wchar_t) 0; ptr++)
96     ;
97   return ptr - s;
98 }
99 #  endif
100 # endif
101 #endif
102
103 #if WIDE_CHAR_VERSION
104 # define VASNPRINTF vasnwprintf
105 # define CHAR_T wchar_t
106 # define DIRECTIVE wchar_t_directive
107 # define DIRECTIVES wchar_t_directives
108 # define PRINTF_PARSE wprintf_parse
109 # define USE_SNPRINTF 1
110 # if HAVE_DECL__SNWPRINTF
111    /* On Windows, the function swprintf() has a different signature than
112       on Unix; we use the _snwprintf() function instead.  */
113 #  define SNPRINTF _snwprintf
114 # else
115    /* Unix.  */
116 #  define SNPRINTF swprintf
117 # endif
118 #else
119 # define VASNPRINTF vasnprintf
120 # define CHAR_T char
121 # define DIRECTIVE char_directive
122 # define DIRECTIVES char_directives
123 # define PRINTF_PARSE printf_parse
124 # /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
125      But don't use it on BeOS, since BeOS snprintf produces no output if the
126      size argument is >= 0x3000000.  */
127 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__
128 #  define USE_SNPRINTF 1
129 # else
130 #  define USE_SNPRINTF 0
131 # endif
132 # if HAVE_DECL__SNPRINTF
133    /* Windows.  */
134 #  define SNPRINTF _snprintf
135 # else
136    /* Unix.  */
137 #  define SNPRINTF snprintf
138    /* Here we need to call the native snprintf, not rpl_snprintf.  */
139 #  undef snprintf
140 # endif
141 #endif
142 /* Here we need to call the native sprintf, not rpl_sprintf.  */
143 #undef sprintf
144
145 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
146 /* Determine the decimal-point character according to the current locale.  */
147 # ifndef decimal_point_char_defined
148 #  define decimal_point_char_defined 1
149 static char
150 decimal_point_char ()
151 {
152   const char *point;
153   /* Determine it in a multithread-safe way.  We know nl_langinfo is
154      multithread-safe on glibc systems, but is not required to be multithread-
155      safe by POSIX.  sprintf(), however, is multithread-safe.  localeconv()
156      is rarely multithread-safe.  */
157 #  if HAVE_NL_LANGINFO && __GLIBC__
158   point = nl_langinfo (RADIXCHAR);
159 #  elif 1
160   char pointbuf[5];
161   sprintf (pointbuf, "%#.0f", 1.0);
162   point = &pointbuf[1];
163 #  else
164   point = localeconv () -> decimal_point;
165 #  endif
166   /* The decimal point is always a single byte: either '.' or ','.  */
167   return (point[0] != '\0' ? point[0] : '.');
168 }
169 # endif
170 #endif
171
172 #if NEED_PRINTF_INFINITE && !defined IN_LIBINTL
173
174 /* Equivalent to !isfinite(x) || x == 0, but does not require libm.  */
175 static int
176 is_infinite_or_zero (double x)
177 {
178   return isnan (x) || x + x == x;
179 }
180
181 #endif
182
183 #if NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
184
185 /* Converting 'long double' to decimal without rare rounding bugs requires
186    real bignums.  We use the naming conventions of GNU gmp, but vastly simpler
187    (and slower) algorithms.  */
188
189 typedef unsigned int mp_limb_t;
190 # define GMP_LIMB_BITS 32
191 typedef int mp_limb_verify[2 * (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS) - 1];
192
193 typedef unsigned long long mp_twolimb_t;
194 # define GMP_TWOLIMB_BITS 64
195 typedef int mp_twolimb_verify[2 * (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS) - 1];
196
197 /* Representation of a bignum >= 0.  */
198 typedef struct
199 {
200   size_t nlimbs;
201   mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc().  */
202 } mpn_t;
203
204 /* Compute the product of two bignums >= 0.
205    Return the allocated memory in case of success, NULL in case of memory
206    allocation failure.  */
207 static void *
208 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
209 {
210   const mp_limb_t *p1;
211   const mp_limb_t *p2;
212   size_t len1;
213   size_t len2;
214
215   if (src1.nlimbs <= src2.nlimbs)
216     {
217       len1 = src1.nlimbs;
218       p1 = src1.limbs;
219       len2 = src2.nlimbs;
220       p2 = src2.limbs;
221     }
222   else
223     {
224       len1 = src2.nlimbs;
225       p1 = src2.limbs;
226       len2 = src1.nlimbs;
227       p2 = src1.limbs;
228     }
229   /* Now 0 <= len1 <= len2.  */
230   if (len1 == 0)
231     {
232       /* src1 or src2 is zero.  */
233       dest->nlimbs = 0;
234       dest->limbs = (mp_limb_t *) malloc (1);
235     }
236   else
237     {
238       /* Here 1 <= len1 <= len2.  */
239       size_t dlen;
240       mp_limb_t *dp;
241       size_t k, i, j;
242
243       dlen = len1 + len2;
244       dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
245       if (dp == NULL)
246         return NULL;
247       for (k = len2; k > 0; )
248         dp[--k] = 0;
249       for (i = 0; i < len1; i++)
250         {
251           mp_limb_t digit1 = p1[i];
252           mp_twolimb_t carry = 0;
253           for (j = 0; j < len2; j++)
254             {
255               mp_limb_t digit2 = p2[j];
256               carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
257               carry += dp[i + j];
258               dp[i + j] = (mp_limb_t) carry;
259               carry = carry >> GMP_LIMB_BITS;
260             }
261           dp[i + len2] = (mp_limb_t) carry;
262         }
263       /* Normalise.  */
264       while (dlen > 0 && dp[dlen - 1] == 0)
265         dlen--;
266       dest->nlimbs = dlen;
267       dest->limbs = dp;
268     }
269   return dest->limbs;
270 }
271
272 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
273    a is written as  a = q * b + r  with 0 <= r < b.  q is the quotient, r
274    the remainder.
275    Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
276    q is incremented.
277    Return the allocated memory in case of success, NULL in case of memory
278    allocation failure.  */
279 static void *
280 divide (mpn_t a, mpn_t b, mpn_t *q)
281 {
282   /* Algorithm:
283      First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
284      with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
285      If m<n, then q:=0 and r:=a.
286      If m>=n=1, perform a single-precision division:
287        r:=0, j:=m,
288        while j>0 do
289          {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
290                = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
291          j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
292        Normalise [q[m-1],...,q[0]], yields q.
293      If m>=n>1, perform a multiple-precision division:
294        We have a/b < beta^(m-n+1).
295        s:=intDsize-1-(hightest bit in b[n-1]), 0<=s<intDsize.
296        Shift a and b left by s bits, copying them. r:=a.
297        r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
298        For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
299          Compute q* :
300            q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
301            In case of overflow (q* >= beta) set q* := beta-1.
302            Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
303            and c3 := b[n-2] * q*.
304            {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
305             occurred.  Furthermore 0 <= c3 < beta^2.
306             If there was overflow and
307             r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
308             the next test can be skipped.}
309            While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
310              Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
311            If q* > 0:
312              Put r := r - b * q* * beta^j. In detail:
313                [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
314                hence: u:=0, for i:=0 to n-1 do
315                               u := u + q* * b[i],
316                               r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
317                               u:=u div beta (+ 1, if carry in subtraction)
318                       r[n+j]:=r[n+j]-u.
319                {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
320                                < q* + 1 <= beta,
321                 the carry u does not overflow.}
322              If a negative carry occurs, put q* := q* - 1
323                and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
324          Set q[j] := q*.
325        Normalise [q[m-n],..,q[0]]; this yields the quotient q.
326        Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
327        rest r.
328        The room for q[j] can be allocated at the memory location of r[n+j].
329      Finally, round-to-even:
330        Shift r left by 1 bit.
331        If r > b or if r = b and q[0] is odd, q := q+1.
332    */
333   const mp_limb_t *a_ptr = a.limbs;
334   size_t a_len = a.nlimbs;
335   const mp_limb_t *b_ptr = b.limbs;
336   size_t b_len = b.nlimbs;
337   mp_limb_t *roomptr;
338   mp_limb_t *tmp_roomptr = NULL;
339   mp_limb_t *q_ptr;
340   size_t q_len;
341   mp_limb_t *r_ptr;
342   size_t r_len;
343
344   /* Allocate room for a_len+2 digits.
345      (Need a_len+1 digits for the real division and 1 more digit for the
346      final rounding of q.)  */
347   roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
348   if (roomptr == NULL)
349     return NULL;
350
351   /* Normalise a.  */
352   while (a_len > 0 && a_ptr[a_len - 1] == 0)
353     a_len--;
354
355   /* Normalise b.  */
356   for (;;)
357     {
358       if (b_len == 0)
359         /* Division by zero.  */
360         abort ();
361       if (b_ptr[b_len - 1] == 0)
362         b_len--;
363       else
364         break;
365     }
366
367   /* Here m = a_len >= 0 and n = b_len > 0.  */
368
369   if (a_len < b_len)
370     {
371       /* m<n: trivial case.  q=0, r := copy of a.  */
372       r_ptr = roomptr;
373       r_len = a_len;
374       memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
375       q_ptr = roomptr + a_len;
376       q_len = 0;
377     }
378   else if (b_len == 1)
379     {
380       /* n=1: single precision division.
381          beta^(m-1) <= a < beta^m  ==>  beta^(m-2) <= a/b < beta^m  */
382       r_ptr = roomptr;
383       q_ptr = roomptr + 1;
384       {
385         mp_limb_t den = b_ptr[0];
386         mp_limb_t remainder = 0;
387         const mp_limb_t *sourceptr = a_ptr + a_len;
388         mp_limb_t *destptr = q_ptr + a_len;
389         size_t count;
390         for (count = a_len; count > 0; count--)
391           {
392             mp_twolimb_t num =
393               ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
394             *--destptr = num / den;
395             remainder = num % den;
396           }
397         /* Normalise and store r.  */
398         if (remainder > 0)
399           {
400             r_ptr[0] = remainder;
401             r_len = 1;
402           }
403         else
404           r_len = 0;
405         /* Normalise q.  */
406         q_len = a_len;
407         if (q_ptr[q_len - 1] == 0)
408           q_len--;
409       }
410     }
411   else
412     {
413       /* n>1: multiple precision division.
414          beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n  ==>
415          beta^(m-n-1) <= a/b < beta^(m-n+1).  */
416       /* Determine s.  */
417       size_t s;
418       {
419         mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
420         s = 31;
421         if (msd >= 0x10000)
422           {
423             msd = msd >> 16;
424             s -= 16;
425           }
426         if (msd >= 0x100)
427           {
428             msd = msd >> 8;
429             s -= 8;
430           }
431         if (msd >= 0x10)
432           {
433             msd = msd >> 4;
434             s -= 4;
435           }
436         if (msd >= 0x4)
437           {
438             msd = msd >> 2;
439             s -= 2;
440           }
441         if (msd >= 0x2)
442           {
443             msd = msd >> 1;
444             s -= 1;
445           }
446       }
447       /* 0 <= s < GMP_LIMB_BITS.
448          Copy b, shifting it left by s bits.  */
449       if (s > 0)
450         {
451           tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
452           if (tmp_roomptr == NULL)
453             {
454               free (roomptr);
455               return NULL;
456             }
457           {
458             const mp_limb_t *sourceptr = b_ptr;
459             mp_limb_t *destptr = tmp_roomptr;
460             mp_twolimb_t accu = 0;
461             size_t count;
462             for (count = b_len; count > 0; count--)
463               {
464                 accu += (mp_twolimb_t) *sourceptr++ << s;
465                 *destptr++ = (mp_limb_t) accu;
466                 accu = accu >> GMP_LIMB_BITS;
467               }
468             /* accu must be zero, since that was how s was determined.  */
469             if (accu != 0)
470               abort ();
471           }
472           b_ptr = tmp_roomptr;
473         }
474       /* Copy a, shifting it left by s bits, yields r.
475          Memory layout:
476          At the beginning: r = roomptr[0..a_len],
477          at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len]  */
478       r_ptr = roomptr;
479       if (s == 0)
480         {
481           memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
482           r_ptr[a_len] = 0;
483         }
484       else
485         {
486           const mp_limb_t *sourceptr = a_ptr;
487           mp_limb_t *destptr = r_ptr;
488           mp_twolimb_t accu = 0;
489           size_t count;
490           for (count = a_len; count > 0; count--)
491             {
492               accu += (mp_twolimb_t) *sourceptr++ << s;
493               *destptr++ = (mp_limb_t) accu;
494               accu = accu >> GMP_LIMB_BITS;
495             }
496           *destptr++ = (mp_limb_t) accu;
497         }
498       q_ptr = roomptr + b_len;
499       q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
500       {
501         size_t j = a_len - b_len; /* m-n */
502         mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
503         mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
504         mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
505           ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
506         /* Division loop, traversed m-n+1 times.
507            j counts down, b is unchanged, beta/2 <= b[n-1] < beta.  */
508         for (;;)
509           {
510             mp_limb_t q_star;
511             mp_limb_t c1;
512             if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
513               {
514                 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow.  */
515                 mp_twolimb_t num =
516                   ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
517                   | r_ptr[j + b_len - 1];
518                 q_star = num / b_msd;
519                 c1 = num % b_msd;
520               }
521             else
522               {
523                 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1].  */
524                 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
525                 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
526                    <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
527                    <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
528                         {<= beta !}.
529                    If yes, jump directly to the subtraction loop.
530                    (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
531                     <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
532                 if (r_ptr[j + b_len] > b_msd
533                     || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
534                   /* r[j+n] >= b[n-1]+1 or
535                      r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
536                      carry.  */
537                   goto subtract;
538               }
539             /* q_star = q*,
540                c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta).  */
541             {
542               mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
543                 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
544               mp_twolimb_t c3 = /* b[n-2] * q* */
545                 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
546               /* While c2 < c3, increase c2 and decrease c3.
547                  Consider c3-c2.  While it is > 0, decrease it by
548                  b[n-1]*beta+b[n-2].  Because of b[n-1]*beta+b[n-2] >= beta^2/2
549                  this can happen only twice.  */
550               if (c3 > c2)
551                 {
552                   q_star = q_star - 1; /* q* := q* - 1 */
553                   if (c3 - c2 > b_msdd)
554                     q_star = q_star - 1; /* q* := q* - 1 */
555                 }
556             }
557             if (q_star > 0)
558               subtract:
559               {
560                 /* Subtract r := r - b * q* * beta^j.  */
561                 mp_limb_t cr;
562                 {
563                   const mp_limb_t *sourceptr = b_ptr;
564                   mp_limb_t *destptr = r_ptr + j;
565                   mp_twolimb_t carry = 0;
566                   size_t count;
567                   for (count = b_len; count > 0; count--)
568                     {
569                       /* Here 0 <= carry <= q*.  */
570                       carry =
571                         carry
572                         + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
573                         + (mp_limb_t) ~(*destptr);
574                       /* Here 0 <= carry <= beta*q* + beta-1.  */
575                       *destptr++ = ~(mp_limb_t) carry;
576                       carry = carry >> GMP_LIMB_BITS; /* <= q* */
577                     }
578                   cr = (mp_limb_t) carry;
579                 }
580                 /* Subtract cr from r_ptr[j + b_len], then forget about
581                    r_ptr[j + b_len].  */
582                 if (cr > r_ptr[j + b_len])
583                   {
584                     /* Subtraction gave a carry.  */
585                     q_star = q_star - 1; /* q* := q* - 1 */
586                     /* Add b back.  */
587                     {
588                       const mp_limb_t *sourceptr = b_ptr;
589                       mp_limb_t *destptr = r_ptr + j;
590                       mp_limb_t carry = 0;
591                       size_t count;
592                       for (count = b_len; count > 0; count--)
593                         {
594                           mp_limb_t source1 = *sourceptr++;
595                           mp_limb_t source2 = *destptr;
596                           *destptr++ = source1 + source2 + carry;
597                           carry =
598                             (carry
599                              ? source1 >= (mp_limb_t) ~source2
600                              : source1 > (mp_limb_t) ~source2);
601                         }
602                     }
603                     /* Forget about the carry and about r[j+n].  */
604                   }
605               }
606             /* q* is determined.  Store it as q[j].  */
607             q_ptr[j] = q_star;
608             if (j == 0)
609               break;
610             j--;
611           }
612       }
613       r_len = b_len;
614       /* Normalise q.  */
615       if (q_ptr[q_len - 1] == 0)
616         q_len--;
617 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
618           b is shifted left by s bits.  */
619       /* Shift r right by s bits.  */
620       if (s > 0)
621         {
622           mp_limb_t ptr = r_ptr + r_len;
623           mp_twolimb_t accu = 0;
624           size_t count;
625           for (count = r_len; count > 0; count--)
626             {
627               accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
628               accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
629               *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
630             }
631         }
632 # endif
633       /* Normalise r.  */
634       while (r_len > 0 && r_ptr[r_len - 1] == 0)
635         r_len--;
636     }
637   /* Compare r << 1 with b.  */
638   if (r_len > b_len)
639     goto increment_q;
640   {
641     size_t i;
642     for (i = b_len;;)
643       {
644         mp_limb_t r_i =
645           (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
646           | (i < r_len ? r_ptr[i] << 1 : 0);
647         mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
648         if (r_i > b_i)
649           goto increment_q;
650         if (r_i < b_i)
651           goto keep_q;
652         if (i == 0)
653           break;
654         i--;
655       }
656   }
657   if (q_len > 0 && ((q_ptr[0] & 1) != 0))
658     /* q is odd.  */
659     increment_q:
660     {
661       size_t i;
662       for (i = 0; i < q_len; i++)
663         if (++(q_ptr[i]) != 0)
664           goto keep_q;
665       q_ptr[q_len++] = 1;
666     }
667   keep_q:
668   if (tmp_roomptr != NULL)
669     free (tmp_roomptr);
670   q->limbs = q_ptr;
671   q->nlimbs = q_len;
672   return roomptr;
673 }
674
675 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
676    representation.
677    Destroys the contents of a.
678    Return the allocated memory - containing the decimal digits in low-to-high
679    order, terminated with a NUL character - in case of success, NULL in case
680    of memory allocation failure.  */
681 static char *
682 convert_to_decimal (mpn_t a, size_t extra_zeroes)
683 {
684   mp_limb_t *a_ptr = a.limbs;
685   size_t a_len = a.nlimbs;
686   /* 0.03345 is slightly larger than log(2)/(9*log(10)).  */
687   size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
688   char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
689   if (c_ptr != NULL)
690     {
691       char *d_ptr = c_ptr;
692       for (; extra_zeroes > 0; extra_zeroes--)
693         *d_ptr++ = '0';
694       while (a_len > 0)
695         {
696           /* Divide a by 10^9, in-place.  */
697           mp_limb_t remainder = 0;
698           mp_limb_t *ptr = a_ptr + a_len;
699           size_t count;
700           for (count = a_len; count > 0; count--)
701             {
702               mp_twolimb_t num =
703                 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
704               *ptr = num / 1000000000;
705               remainder = num % 1000000000;
706             }
707           /* Store the remainder as 9 decimal digits.  */
708           for (count = 9; count > 0; count--)
709             {
710               *d_ptr++ = '0' + (remainder % 10);
711               remainder = remainder / 10;
712             }
713           /* Normalize a.  */
714           if (a_ptr[a_len - 1] == 0)
715             a_len--;
716         }
717       /* Remove leading zeroes.  */
718       while (d_ptr > c_ptr && d_ptr[-1] == '0')
719         d_ptr--;
720       /* But keep at least one zero.  */
721       if (d_ptr == c_ptr)
722         *d_ptr++ = '0';
723       /* Terminate the string.  */
724       *d_ptr = '\0';
725     }
726   return c_ptr;
727 }
728
729 /* Assuming x is finite and >= 0:
730    write x as x = 2^e * m, where m is a bignum.
731    Return the allocated memory in case of success, NULL in case of memory
732    allocation failure.  */
733 static void *
734 decode_long_double (long double x, int *ep, mpn_t *mp)
735 {
736   mpn_t m;
737   int exp;
738   long double y;
739   size_t i;
740
741   /* Allocate memory for result.  */
742   m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
743   m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
744   if (m.limbs == NULL)
745     return NULL;
746   /* Split into exponential part and mantissa.  */
747   y = frexpl (x, &exp);
748   if (!(y >= 0.0L && y < 1.0L))
749     abort ();
750   /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
751      latter is an integer.  */
752   /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
753      I'm not sure whether it's safe to cast a 'long double' value between
754      2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
755      'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
756      doesn't matter).  */
757 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
758 #  if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
759     {
760       mp_limb_t hi, lo;
761       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
762       hi = (int) y;
763       y -= hi;
764       if (!(y >= 0.0L && y < 1.0L))
765         abort ();
766       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
767       lo = (int) y;
768       y -= lo;
769       if (!(y >= 0.0L && y < 1.0L))
770         abort ();
771       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
772     }
773 #  else
774     {
775       mp_limb_t d;
776       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
777       d = (int) y;
778       y -= d;
779       if (!(y >= 0.0L && y < 1.0L))
780         abort ();
781       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
782     }
783 #  endif
784 # endif
785   for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
786     {
787       mp_limb_t hi, lo;
788       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
789       hi = (int) y;
790       y -= hi;
791       if (!(y >= 0.0L && y < 1.0L))
792         abort ();
793       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
794       lo = (int) y;
795       y -= lo;
796       if (!(y >= 0.0L && y < 1.0L))
797         abort ();
798       m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
799     }
800   if (!(y == 0.0L))
801     abort ();
802   /* Normalise.  */
803   while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
804     m.nlimbs--;
805   *mp = m;
806   *ep = exp - LDBL_MANT_BIT;
807   return m.limbs;
808 }
809
810 /* Assuming x is finite and >= 0, and n is an integer:
811    Returns the decimal representation of round (x * 10^n).
812    Return the allocated memory - containing the decimal digits in low-to-high
813    order, terminated with a NUL character - in case of success, NULL in case
814    of memory allocation failure.  */
815 static char *
816 scale10_round_decimal_long_double (long double x, int n)
817 {
818   int e;
819   mpn_t m;
820   void *memory = decode_long_double (x, &e, &m);
821   int s;
822   size_t extra_zeroes;
823   unsigned int abs_n;
824   unsigned int abs_s;
825   mp_limb_t *pow5_ptr;
826   size_t pow5_len;
827   unsigned int s_limbs;
828   unsigned int s_bits;
829   mpn_t pow5;
830   mpn_t z;
831   void *z_memory;
832   char *digits;
833
834   if (memory == NULL)
835     return NULL;
836   /* x = 2^e * m, hence
837      y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
838        = round (2^s * 5^n * m).  */
839   s = e + n;
840   extra_zeroes = 0;
841   /* Factor out a common power of 10 if possible.  */
842   if (s > 0 && n > 0)
843     {
844       extra_zeroes = (s < n ? s : n);
845       s -= extra_zeroes;
846       n -= extra_zeroes;
847     }
848   /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
849      Before converting to decimal, we need to compute
850      z = round (2^s * 5^n * m).  */
851   /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
852      sign.  2.322 is slightly larger than log(5)/log(2).  */
853   abs_n = (n >= 0 ? n : -n);
854   abs_s = (s >= 0 ? s : -s);
855   pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
856                                     + abs_s / GMP_LIMB_BITS + 1)
857                                    * sizeof (mp_limb_t));
858   if (pow5_ptr == NULL)
859     {
860       free (memory);
861       return NULL;
862     }
863   /* Initialize with 1.  */
864   pow5_ptr[0] = 1;
865   pow5_len = 1;
866   /* Multiply with 5^|n|.  */
867   if (abs_n > 0)
868     {
869       static mp_limb_t const small_pow5[13 + 1] =
870         {
871           1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
872           48828125, 244140625, 1220703125
873         };
874       unsigned int n13;
875       for (n13 = 0; n13 <= abs_n; n13 += 13)
876         {
877           mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
878           size_t j;
879           mp_twolimb_t carry = 0;
880           for (j = 0; j < pow5_len; j++)
881             {
882               mp_limb_t digit2 = pow5_ptr[j];
883               carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
884               pow5_ptr[j] = (mp_limb_t) carry;
885               carry = carry >> GMP_LIMB_BITS;
886             }
887           if (carry > 0)
888             pow5_ptr[pow5_len++] = (mp_limb_t) carry;
889         }
890     }
891   s_limbs = abs_s / GMP_LIMB_BITS;
892   s_bits = abs_s % GMP_LIMB_BITS;
893   if (n >= 0 ? s >= 0 : s <= 0)
894     {
895       /* Multiply with 2^|s|.  */
896       if (s_bits > 0)
897         {
898           mp_limb_t *ptr = pow5_ptr;
899           mp_twolimb_t accu = 0;
900           size_t count;
901           for (count = pow5_len; count > 0; count--)
902             {
903               accu += (mp_twolimb_t) *ptr << s_bits;
904               *ptr++ = (mp_limb_t) accu;
905               accu = accu >> GMP_LIMB_BITS;
906             }
907           if (accu > 0)
908             {
909               *ptr = (mp_limb_t) accu;
910               pow5_len++;
911             }
912         }
913       if (s_limbs > 0)
914         {
915           size_t count;
916           for (count = pow5_len; count > 0;)
917             {
918               count--;
919               pow5_ptr[s_limbs + count] = pow5_ptr[count];
920             }
921           for (count = s_limbs; count > 0;)
922             {
923               count--;
924               pow5_ptr[count] = 0;
925             }
926           pow5_len += s_limbs;
927         }
928       pow5.limbs = pow5_ptr;
929       pow5.nlimbs = pow5_len;
930       if (n >= 0)
931         {
932           /* Multiply m with pow5.  No division needed.  */
933           z_memory = multiply (m, pow5, &z);
934         }
935       else
936         {
937           /* Divide m by pow5 and round.  */
938           z_memory = divide (m, pow5, &z);
939         }
940     }
941   else
942     {
943       pow5.limbs = pow5_ptr;
944       pow5.nlimbs = pow5_len;
945       if (n >= 0)
946         {
947           /* n >= 0, s < 0.
948              Multiply m with pow5, then divide by 2^|s|.  */
949           mpn_t numerator;
950           mpn_t denominator;
951           void *tmp_memory;
952           tmp_memory = multiply (m, pow5, &numerator);
953           if (tmp_memory == NULL)
954             {
955               free (pow5_ptr);
956               free (memory);
957               return NULL;
958             }
959           /* Construct 2^|s|.  */
960           {
961             mp_limb_t *ptr = pow5_ptr + pow5_len;
962             size_t i;
963             for (i = 0; i < s_limbs; i++)
964               ptr[i] = 0;
965             ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
966             denominator.limbs = ptr;
967             denominator.nlimbs = s_limbs + 1;
968           }
969           z_memory = divide (numerator, denominator, &z);
970           free (tmp_memory);
971         }
972       else
973         {
974           /* n < 0, s > 0.
975              Multiply m with 2^s, then divide by pow5.  */
976           mpn_t numerator;
977           mp_limb_t *num_ptr;
978           num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
979                                           * sizeof (mp_limb_t));
980           if (num_ptr == NULL)
981             {
982               free (pow5_ptr);
983               free (memory);
984               return NULL;
985             }
986           {
987             mp_limb_t *destptr = num_ptr;
988             {
989               size_t i;
990               for (i = 0; i < s_limbs; i++)
991                 *destptr++ = 0;
992             }
993             if (s_bits > 0)
994               {
995                 const mp_limb_t *sourceptr = m.limbs;
996                 mp_twolimb_t accu = 0;
997                 size_t count;
998                 for (count = m.nlimbs; count > 0; count--)
999                   {
1000                     accu += (mp_twolimb_t) *sourceptr++ << s;
1001                     *destptr++ = (mp_limb_t) accu;
1002                     accu = accu >> GMP_LIMB_BITS;
1003                   }
1004                 if (accu > 0)
1005                   *destptr++ = (mp_limb_t) accu;
1006               }
1007             else
1008               {
1009                 const mp_limb_t *sourceptr = m.limbs;
1010                 size_t count;
1011                 for (count = m.nlimbs; count > 0; count--)
1012                   *destptr++ = *sourceptr++;
1013               }
1014             numerator.limbs = num_ptr;
1015             numerator.nlimbs = destptr - num_ptr;
1016           }
1017           z_memory = divide (numerator, pow5, &z);
1018           free (num_ptr);
1019         }
1020     }
1021   free (pow5_ptr);
1022   free (memory);
1023
1024   /* Here y = round (x * 10^n) = z * 10^extra_zeroes.  */
1025
1026   if (z_memory == NULL)
1027     return NULL;
1028   digits = convert_to_decimal (z, extra_zeroes);
1029   free (z_memory);
1030   return digits;
1031 }
1032
1033 /* Assuming x is finite and > 0:
1034    Return an approximation for n with 10^n <= x < 10^(n+1).
1035    The approximation is usually the right n, but may be off by 1 sometimes.  */
1036 static int
1037 floorlog10l (long double x)
1038 {
1039   int exp;
1040   long double y;
1041   double z;
1042   double l;
1043
1044   /* Split into exponential part and mantissa.  */
1045   y = frexpl (x, &exp);
1046   if (!(y >= 0.0L && y < 1.0L))
1047     abort ();
1048   if (y == 0.0L)
1049     return INT_MIN;
1050   if (y < 0.5L)
1051     {
1052       while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1053         {
1054           y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1055           exp -= GMP_LIMB_BITS;
1056         }
1057       if (y < (1.0L / (1 << 16)))
1058         {
1059           y *= 1.0L * (1 << 16);
1060           exp -= 16;
1061         }
1062       if (y < (1.0L / (1 << 8)))
1063         {
1064           y *= 1.0L * (1 << 8);
1065           exp -= 8;
1066         }
1067       if (y < (1.0L / (1 << 4)))
1068         {
1069           y *= 1.0L * (1 << 4);
1070           exp -= 4;
1071         }
1072       if (y < (1.0L / (1 << 2)))
1073         {
1074           y *= 1.0L * (1 << 2);
1075           exp -= 2;
1076         }
1077       if (y < (1.0L / (1 << 1)))
1078         {
1079           y *= 1.0L * (1 << 1);
1080           exp -= 1;
1081         }
1082     }
1083   if (!(y >= 0.5L && y < 1.0L))
1084     abort ();
1085   /* Compute an approximation for l = log2(x) = exp + log2(y).  */
1086   l = exp;
1087   z = y;
1088   if (z < 0.70710678118654752444)
1089     {
1090       z *= 1.4142135623730950488;
1091       l -= 0.5;
1092     }
1093   if (z < 0.8408964152537145431)
1094     {
1095       z *= 1.1892071150027210667;
1096       l -= 0.25;
1097     }
1098   if (z < 0.91700404320467123175)
1099     {
1100       z *= 1.0905077326652576592;
1101       l -= 0.125;
1102     }
1103   if (z < 0.9576032806985736469)
1104     {
1105       z *= 1.0442737824274138403;
1106       l -= 0.0625;
1107     }
1108   /* Now 0.95 <= z <= 1.01.  */
1109   z = 1 - z;
1110   /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1111      Four terms are enough to get an approximation with error < 10^-7.  */
1112   l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1113   /* Finally multiply with log(2)/log(10), yields an approximation for
1114      log10(x).  */
1115   l *= 0.30102999566398119523;
1116   /* Round down to the next integer.  */
1117   return (int) l + (l < 0 ? -1 : 0);
1118 }
1119
1120 #endif
1121
1122 CHAR_T *
1123 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
1124 {
1125   DIRECTIVES d;
1126   arguments a;
1127
1128   if (PRINTF_PARSE (format, &d, &a) < 0)
1129     {
1130       errno = EINVAL;
1131       return NULL;
1132     }
1133
1134 #define CLEANUP() \
1135   free (d.dir);                                                         \
1136   if (a.arg)                                                            \
1137     free (a.arg);
1138
1139   if (printf_fetchargs (args, &a) < 0)
1140     {
1141       CLEANUP ();
1142       errno = EINVAL;
1143       return NULL;
1144     }
1145
1146   {
1147     size_t buf_neededlength;
1148     CHAR_T *buf;
1149     CHAR_T *buf_malloced;
1150     const CHAR_T *cp;
1151     size_t i;
1152     DIRECTIVE *dp;
1153     /* Output string accumulator.  */
1154     CHAR_T *result;
1155     size_t allocated;
1156     size_t length;
1157
1158     /* Allocate a small buffer that will hold a directive passed to
1159        sprintf or snprintf.  */
1160     buf_neededlength =
1161       xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1162 #if HAVE_ALLOCA
1163     if (buf_neededlength < 4000 / sizeof (CHAR_T))
1164       {
1165         buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
1166         buf_malloced = NULL;
1167       }
1168     else
1169 #endif
1170       {
1171         size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
1172         if (size_overflow_p (buf_memsize))
1173           goto out_of_memory_1;
1174         buf = (CHAR_T *) malloc (buf_memsize);
1175         if (buf == NULL)
1176           goto out_of_memory_1;
1177         buf_malloced = buf;
1178       }
1179
1180     if (resultbuf != NULL)
1181       {
1182         result = resultbuf;
1183         allocated = *lengthp;
1184       }
1185     else
1186       {
1187         result = NULL;
1188         allocated = 0;
1189       }
1190     length = 0;
1191     /* Invariants:
1192        result is either == resultbuf or == NULL or malloc-allocated.
1193        If length > 0, then result != NULL.  */
1194
1195     /* Ensures that allocated >= needed.  Aborts through a jump to
1196        out_of_memory if needed is SIZE_MAX or otherwise too big.  */
1197 #define ENSURE_ALLOCATION(needed) \
1198     if ((needed) > allocated)                                                \
1199       {                                                                      \
1200         size_t memory_size;                                                  \
1201         CHAR_T *memory;                                                      \
1202                                                                              \
1203         allocated = (allocated > 0 ? xtimes (allocated, 2) : 12);            \
1204         if ((needed) > allocated)                                            \
1205           allocated = (needed);                                              \
1206         memory_size = xtimes (allocated, sizeof (CHAR_T));                   \
1207         if (size_overflow_p (memory_size))                                   \
1208           goto out_of_memory;                                                \
1209         if (result == resultbuf || result == NULL)                           \
1210           memory = (CHAR_T *) malloc (memory_size);                          \
1211         else                                                                 \
1212           memory = (CHAR_T *) realloc (result, memory_size);                 \
1213         if (memory == NULL)                                                  \
1214           goto out_of_memory;                                                \
1215         if (result == resultbuf && length > 0)                               \
1216           memcpy (memory, result, length * sizeof (CHAR_T));                 \
1217         result = memory;                                                     \
1218       }
1219
1220     for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1221       {
1222         if (cp != dp->dir_start)
1223           {
1224             size_t n = dp->dir_start - cp;
1225             size_t augmented_length = xsum (length, n);
1226
1227             ENSURE_ALLOCATION (augmented_length);
1228             memcpy (result + length, cp, n * sizeof (CHAR_T));
1229             length = augmented_length;
1230           }
1231         if (i == d.count)
1232           break;
1233
1234         /* Execute a single directive.  */
1235         if (dp->conversion == '%')
1236           {
1237             size_t augmented_length;
1238
1239             if (!(dp->arg_index == ARG_NONE))
1240               abort ();
1241             augmented_length = xsum (length, 1);
1242             ENSURE_ALLOCATION (augmented_length);
1243             result[length] = '%';
1244             length = augmented_length;
1245           }
1246         else
1247           {
1248             if (!(dp->arg_index != ARG_NONE))
1249               abort ();
1250
1251             if (dp->conversion == 'n')
1252               {
1253                 switch (a.arg[dp->arg_index].type)
1254                   {
1255                   case TYPE_COUNT_SCHAR_POINTER:
1256                     *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1257                     break;
1258                   case TYPE_COUNT_SHORT_POINTER:
1259                     *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1260                     break;
1261                   case TYPE_COUNT_INT_POINTER:
1262                     *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1263                     break;
1264                   case TYPE_COUNT_LONGINT_POINTER:
1265                     *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1266                     break;
1267 #if HAVE_LONG_LONG_INT
1268                   case TYPE_COUNT_LONGLONGINT_POINTER:
1269                     *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1270                     break;
1271 #endif
1272                   default:
1273                     abort ();
1274                   }
1275               }
1276 #if (NEED_PRINTF_INFINITE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
1277             else if ((dp->conversion == 'f' || dp->conversion == 'F'
1278                       || dp->conversion == 'e' || dp->conversion == 'E'
1279                       || dp->conversion == 'g' || dp->conversion == 'G')
1280                      && (0
1281 # if NEED_PRINTF_INFINITE
1282                          || (a.arg[dp->arg_index].type == TYPE_DOUBLE
1283                              /* The systems (mingw) which produce wrong output
1284                                 for Inf and -Inf also do so for NaN and -0.0.
1285                                 Therefore we treat these cases here as well.  */
1286                              && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
1287 # endif
1288 # if NEED_PRINTF_LONG_DOUBLE
1289                          || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
1290 # endif
1291                         ))
1292               {
1293                 arg_type type = a.arg[dp->arg_index].type;
1294                 int flags = dp->flags;
1295                 int has_width;
1296                 size_t width;
1297                 int has_precision;
1298                 size_t precision;
1299                 size_t tmp_length;
1300                 CHAR_T tmpbuf[700];
1301                 CHAR_T *tmp;
1302                 CHAR_T *pad_ptr;
1303                 CHAR_T *p;
1304
1305                 has_width = 0;
1306                 width = 0;
1307                 if (dp->width_start != dp->width_end)
1308                   {
1309                     if (dp->width_arg_index != ARG_NONE)
1310                       {
1311                         int arg;
1312
1313                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1314                           abort ();
1315                         arg = a.arg[dp->width_arg_index].a.a_int;
1316                         if (arg < 0)
1317                           {
1318                             /* "A negative field width is taken as a '-' flag
1319                                 followed by a positive field width."  */
1320                             flags |= FLAG_LEFT;
1321                             width = (unsigned int) (-arg);
1322                           }
1323                         else
1324                           width = arg;
1325                       }
1326                     else
1327                       {
1328                         const CHAR_T *digitp = dp->width_start;
1329
1330                         do
1331                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1332                         while (digitp != dp->width_end);
1333                       }
1334                     has_width = 1;
1335                   }
1336
1337                 has_precision = 0;
1338                 precision = 0;
1339                 if (dp->precision_start != dp->precision_end)
1340                   {
1341                     if (dp->precision_arg_index != ARG_NONE)
1342                       {
1343                         int arg;
1344
1345                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1346                           abort ();
1347                         arg = a.arg[dp->precision_arg_index].a.a_int;
1348                         /* "A negative precision is taken as if the precision
1349                             were omitted."  */
1350                         if (arg >= 0)
1351                           {
1352                             precision = arg;
1353                             has_precision = 1;
1354                           }
1355                       }
1356                     else
1357                       {
1358                         const CHAR_T *digitp = dp->precision_start + 1;
1359
1360                         precision = 0;
1361                         while (digitp != dp->precision_end)
1362                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1363                         has_precision = 1;
1364                       }
1365                   }
1366
1367                 /* POSIX specifies the default precision to be 6 for %f, %F,
1368                    %e, %E, but not for %g, %G.  Implementations appear to use
1369                    the same default precision also for %g, %G.  */
1370                 if (!has_precision)
1371                   precision = 6;
1372
1373                 /* Allocate a temporary buffer of sufficient size.  */
1374 # if NEED_PRINTF_INFINITE && NEED_PRINTF_LONG_DOUBLE
1375                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1376 # elif NEED_PRINTF_LONG_DOUBLE
1377                 tmp_length = LDBL_DIG + 1;
1378 # elif NEED_PRINTF_INFINITE
1379                 tmp_length = 0;
1380 # endif
1381                 if (tmp_length < precision)
1382                   tmp_length = precision;
1383 # if NEED_PRINTF_LONG_DOUBLE
1384 #  if NEED_PRINTF_INFINITE
1385                 if (type == TYPE_LONGDOUBLE)
1386 #  endif
1387                   if (dp->conversion == 'f' || dp->conversion == 'F')
1388                     {
1389                       long double arg = a.arg[dp->arg_index].a.a_longdouble;
1390                       if (!(isnanl (arg) || arg + arg == arg))
1391                         {
1392                           /* arg is finite and nonzero.  */
1393                           int exponent = floorlog10l (arg < 0 ? -arg : arg);
1394                           if (exponent >= 0 && tmp_length < exponent + precision)
1395                             tmp_length = exponent + precision;
1396                         }
1397                     }
1398 # endif
1399                 /* Account for sign, decimal point etc. */
1400                 tmp_length = xsum (tmp_length, 12);
1401
1402                 if (tmp_length < width)
1403                   tmp_length = width;
1404
1405                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1406
1407                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1408                   tmp = tmpbuf;
1409                 else
1410                   {
1411                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1412
1413                     if (size_overflow_p (tmp_memsize))
1414                       /* Overflow, would lead to out of memory.  */
1415                       goto out_of_memory;
1416                     tmp = (CHAR_T *) malloc (tmp_memsize);
1417                     if (tmp == NULL)
1418                       /* Out of memory.  */
1419                       goto out_of_memory;
1420                   }
1421
1422                 pad_ptr = NULL;
1423                 p = tmp;
1424
1425 # if NEED_PRINTF_LONG_DOUBLE
1426 #  if NEED_PRINTF_INFINITE
1427                 if (type == TYPE_LONGDOUBLE)
1428 #  endif
1429                   {
1430                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
1431
1432                     if (isnanl (arg))
1433                       {
1434                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1435                           {
1436                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1437                           }
1438                         else
1439                           {
1440                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1441                           }
1442                       }
1443                     else
1444                       {
1445                         int sign = 0;
1446                         DECL_LONG_DOUBLE_ROUNDING
1447
1448                         BEGIN_LONG_DOUBLE_ROUNDING ();
1449
1450                         if (signbit (arg)) /* arg < 0.0L or negative zero */
1451                           {
1452                             sign = -1;
1453                             arg = -arg;
1454                           }
1455
1456                         if (sign < 0)
1457                           *p++ = '-';
1458                         else if (flags & FLAG_SHOWSIGN)
1459                           *p++ = '+';
1460                         else if (flags & FLAG_SPACE)
1461                           *p++ = ' ';
1462
1463                         if (arg > 0.0L && arg + arg == arg)
1464                           {
1465                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1466                               {
1467                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1468                               }
1469                             else
1470                               {
1471                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1472                               }
1473                           }
1474                         else
1475                           {
1476                             pad_ptr = p;
1477
1478                             if (dp->conversion == 'f' || dp->conversion == 'F')
1479                               {
1480                                 char *digits;
1481                                 size_t ndigits;
1482
1483                                 digits =
1484                                   scale10_round_decimal_long_double (arg, precision);
1485                                 if (digits == NULL)
1486                                   {
1487                                     END_LONG_DOUBLE_ROUNDING ();
1488                                     goto out_of_memory;
1489                                   }
1490                                 ndigits = strlen (digits);
1491
1492                                 if (ndigits > precision)
1493                                   do
1494                                     {
1495                                       --ndigits;
1496                                       *p++ = digits[ndigits];
1497                                     }
1498                                   while (ndigits > precision);
1499                                 else
1500                                   *p++ = '0';
1501                                 /* Here ndigits <= precision.  */
1502                                 if ((flags & FLAG_ALT) || precision > 0)
1503                                   {
1504                                     *p++ = decimal_point_char ();
1505                                     for (; precision > ndigits; precision--)
1506                                       *p++ = '0';
1507                                     while (ndigits > 0)
1508                                       {
1509                                         --ndigits;
1510                                         *p++ = digits[ndigits];
1511                                       }
1512                                   }
1513
1514                                 free (digits);
1515                               }
1516                             else if (dp->conversion == 'e' || dp->conversion == 'E')
1517                               {
1518                                 int exponent;
1519
1520                                 if (arg == 0.0L)
1521                                   {
1522                                     exponent = 0;
1523                                     *p++ = '0';
1524                                     if ((flags & FLAG_ALT) || precision > 0)
1525                                       {
1526                                         *p++ = decimal_point_char ();
1527                                         for (; precision > 0; precision--)
1528                                           *p++ = '0';
1529                                       }
1530                                   }
1531                                 else
1532                                   {
1533                                     /* arg > 0.0L.  */
1534                                     int adjusted;
1535                                     char *digits;
1536                                     size_t ndigits;
1537
1538                                     exponent = floorlog10l (arg);
1539                                     adjusted = 0;
1540                                     for (;;)
1541                                       {
1542                                         digits =
1543                                           scale10_round_decimal_long_double (arg,
1544                                                                              (int)precision - exponent);
1545                                         if (digits == NULL)
1546                                           {
1547                                             END_LONG_DOUBLE_ROUNDING ();
1548                                             goto out_of_memory;
1549                                           }
1550                                         ndigits = strlen (digits);
1551
1552                                         if (ndigits == precision + 1)
1553                                           break;
1554                                         if (ndigits < precision
1555                                             || ndigits > precision + 2)
1556                                           /* The exponent was not guessed
1557                                              precisely enough.  */
1558                                           abort ();
1559                                         if (adjusted)
1560                                           /* None of two values of exponent is
1561                                              the right one.  Prevent an endless
1562                                              loop.  */
1563                                           abort ();
1564                                         free (digits);
1565                                         if (ndigits == precision)
1566                                           exponent -= 1;
1567                                         else
1568                                           exponent += 1;
1569                                         adjusted = 1;
1570                                       }
1571
1572                                     /* Here ndigits = precision+1.  */
1573                                     *p++ = digits[--ndigits];
1574                                     if ((flags & FLAG_ALT) || precision > 0)
1575                                       {
1576                                         *p++ = decimal_point_char ();
1577                                         while (ndigits > 0)
1578                                           {
1579                                             --ndigits;
1580                                             *p++ = digits[ndigits];
1581                                           }
1582                                       }
1583
1584                                     free (digits);
1585                                   }
1586
1587                                 *p++ = dp->conversion; /* 'e' or 'E' */
1588 #  if WIDE_CHAR_VERSION
1589                                 {
1590                                   static const wchar_t decimal_format[] =
1591                                     { '%', '+', '.', '2', 'd', '\0' };
1592                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
1593                                 }
1594 #  else
1595                                 sprintf (p, "%+.2d", exponent);
1596 #  endif
1597                                 while (*p != '\0')
1598                                   p++;
1599                               }
1600                             else if (dp->conversion == 'g' || dp->conversion == 'G')
1601                               {
1602                                 if (precision == 0)
1603                                   precision = 1;
1604                                 /* precision >= 1.  */
1605
1606                                 if (arg == 0.0L)
1607                                   /* The exponent is 0, >= -4, < precision.
1608                                      Use fixed-point notation.  */
1609                                   {
1610                                     size_t ndigits = precision;
1611                                     /* Number of trailing zeroes that have to be
1612                                        dropped.  */
1613                                     size_t nzeroes =
1614                                       (flags & FLAG_ALT ? 0 : precision - 1);
1615
1616                                     --ndigits;
1617                                     *p++ = '0';
1618                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
1619                                       {
1620                                         *p++ = decimal_point_char ();
1621                                         while (ndigits > nzeroes)
1622                                           {
1623                                             --ndigits;
1624                                             *p++ = '0';
1625                                           }
1626                                       }
1627                                   }
1628                                 else
1629                                   {
1630                                     /* arg > 0.0L.  */
1631                                     int exponent;
1632                                     int adjusted;
1633                                     char *digits;
1634                                     size_t ndigits;
1635                                     size_t nzeroes;
1636
1637                                     exponent = floorlog10l (arg);
1638                                     adjusted = 0;
1639                                     for (;;)
1640                                       {
1641                                         digits =
1642                                           scale10_round_decimal_long_double (arg,
1643                                                                              (int)(precision - 1) - exponent);
1644                                         if (digits == NULL)
1645                                           {
1646                                             END_LONG_DOUBLE_ROUNDING ();
1647                                             goto out_of_memory;
1648                                           }
1649                                         ndigits = strlen (digits);
1650
1651                                         if (ndigits == precision)
1652                                           break;
1653                                         if (ndigits < precision - 1
1654                                             || ndigits > precision + 1)
1655                                           /* The exponent was not guessed
1656                                              precisely enough.  */
1657                                           abort ();
1658                                         if (adjusted)
1659                                           /* None of two values of exponent is
1660                                              the right one.  Prevent an endless
1661                                              loop.  */
1662                                           abort ();
1663                                         free (digits);
1664                                         if (ndigits < precision)
1665                                           exponent -= 1;
1666                                         else
1667                                           exponent += 1;
1668                                         adjusted = 1;
1669                                       }
1670                                     /* Here ndigits = precision.  */
1671
1672                                     /* Determine the number of trailing zeroes
1673                                        that have to be dropped.  */
1674                                     nzeroes = 0;
1675                                     if ((flags & FLAG_ALT) == 0)
1676                                       while (nzeroes < ndigits
1677                                              && digits[nzeroes] == '0')
1678                                         nzeroes++;
1679
1680                                     /* The exponent is now determined.  */
1681                                     if (exponent >= -4
1682                                         && exponent < (long)precision)
1683                                       {
1684                                         /* Fixed-point notation:
1685                                            max(exponent,0)+1 digits, then the
1686                                            decimal point, then the remaining
1687                                            digits without trailing zeroes.  */
1688                                         if (exponent >= 0)
1689                                           {
1690                                             size_t count = exponent + 1;
1691                                             /* Note: count <= precision = ndigits.  */
1692                                             for (; count > 0; count--)
1693                                               *p++ = digits[--ndigits];
1694                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
1695                                               {
1696                                                 *p++ = decimal_point_char ();
1697                                                 while (ndigits > nzeroes)
1698                                                   {
1699                                                     --ndigits;
1700                                                     *p++ = digits[ndigits];
1701                                                   }
1702                                               }
1703                                           }
1704                                         else
1705                                           {
1706                                             size_t count = -exponent - 1;
1707                                             *p++ = '0';
1708                                             *p++ = decimal_point_char ();
1709                                             for (; count > 0; count--)
1710                                               *p++ = '0';
1711                                             while (ndigits > nzeroes)
1712                                               {
1713                                                 --ndigits;
1714                                                 *p++ = digits[ndigits];
1715                                               }
1716                                           }
1717                                       }
1718                                     else
1719                                       {
1720                                         /* Exponential notation.  */
1721                                         *p++ = digits[--ndigits];
1722                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
1723                                           {
1724                                             *p++ = decimal_point_char ();
1725                                             while (ndigits > nzeroes)
1726                                               {
1727                                                 --ndigits;
1728                                                 *p++ = digits[ndigits];
1729                                               }
1730                                           }
1731                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1732 #  if WIDE_CHAR_VERSION
1733                                         {
1734                                           static const wchar_t decimal_format[] =
1735                                             { '%', '+', '.', '2', 'd', '\0' };
1736                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
1737                                         }
1738 #  else
1739                                         sprintf (p, "%+.2d", exponent);
1740 #  endif
1741                                         while (*p != '\0')
1742                                           p++;
1743                                       }
1744
1745                                     free (digits);
1746                                   }
1747                               }
1748                             else
1749                               abort ();
1750                           }
1751
1752                         END_LONG_DOUBLE_ROUNDING ();
1753                       }
1754                   }
1755 #  if NEED_PRINTF_INFINITE
1756                 else
1757 #  endif
1758 # endif
1759 # if NEED_PRINTF_INFINITE
1760                   {
1761                     /* Simpler than above: handle only NaN, Infinity, zero.  */
1762                     double arg = a.arg[dp->arg_index].a.a_double;
1763
1764                     if (isnan (arg))
1765                       {
1766                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1767                           {
1768                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1769                           }
1770                         else
1771                           {
1772                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1773                           }
1774                       }
1775                     else
1776                       {
1777                         int sign = 0;
1778
1779                         if (signbit (arg)) /* arg < 0.0L or negative zero */
1780                           {
1781                             sign = -1;
1782                             arg = -arg;
1783                           }
1784
1785                         if (sign < 0)
1786                           *p++ = '-';
1787                         else if (flags & FLAG_SHOWSIGN)
1788                           *p++ = '+';
1789                         else if (flags & FLAG_SPACE)
1790                           *p++ = ' ';
1791
1792                         if (arg > 0.0 && arg + arg == arg)
1793                           {
1794                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1795                               {
1796                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1797                               }
1798                             else
1799                               {
1800                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1801                               }
1802                           }
1803                         else
1804                           {
1805                             if (!(arg == 0.0))
1806                               abort ();
1807
1808                             pad_ptr = p;
1809
1810                             if (dp->conversion == 'f' || dp->conversion == 'F')
1811                               {
1812                                 *p++ = '0';
1813                                 if ((flags & FLAG_ALT) || precision > 0)
1814                                   {
1815                                     *p++ = decimal_point_char ();
1816                                     for (; precision > 0; precision--)
1817                                       *p++ = '0';
1818                                   }
1819                               }
1820                             else if (dp->conversion == 'e' || dp->conversion == 'E')
1821                               {
1822                                 *p++ = '0';
1823                                 if ((flags & FLAG_ALT) || precision > 0)
1824                                   {
1825                                     *p++ = decimal_point_char ();
1826                                     for (; precision > 0; precision--)
1827                                       *p++ = '0';
1828                                   }
1829                                 *p++ = dp->conversion; /* 'e' or 'E' */
1830                                 *p++ = '+';
1831                                 /* Produce the same number of exponent digits as
1832                                    the native printf implementation.  */
1833 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1834                                 *p++ = '0';
1835 # endif
1836                                 *p++ = '0';
1837                                 *p++ = '0';
1838                               }
1839                             else if (dp->conversion == 'g' || dp->conversion == 'G')
1840                               {
1841                                 *p++ = '0';
1842                                 if (flags & FLAG_ALT)
1843                                   {
1844                                     size_t ndigits =
1845                                       (precision > 0 ? precision - 1 : 0);
1846                                     *p++ = decimal_point_char ();
1847                                     for (; ndigits > 0; --ndigits)
1848                                       *p++ = '0';
1849                                   }
1850                               }
1851                             else
1852                               abort ();
1853                           }
1854                       }
1855                   }
1856 # endif
1857
1858                 /* The generated string now extends from tmp to p, with the
1859                    zero padding insertion point being at pad_ptr.  */
1860                 if (has_width && p - tmp < width)
1861                   {
1862                     size_t pad = width - (p - tmp);
1863                     CHAR_T *end = p + pad;
1864
1865                     if (flags & FLAG_LEFT)
1866                       {
1867                         /* Pad with spaces on the right.  */
1868                         for (; pad > 0; pad--)
1869                           *p++ = ' ';
1870                       }
1871                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1872                       {
1873                         /* Pad with zeroes.  */
1874                         CHAR_T *q = end;
1875
1876                         while (p > pad_ptr)
1877                           *--q = *--p;
1878                         for (; pad > 0; pad--)
1879                           *p++ = '0';
1880                       }
1881                     else
1882                       {
1883                         /* Pad with spaces on the left.  */
1884                         CHAR_T *q = end;
1885
1886                         while (p > tmp)
1887                           *--q = *--p;
1888                         for (; pad > 0; pad--)
1889                           *p++ = ' ';
1890                       }
1891
1892                     p = end;
1893                   }
1894
1895                 {
1896                   size_t count = p - tmp;
1897
1898                   if (count >= tmp_length)
1899                     /* tmp_length was incorrectly calculated - fix the
1900                        code above!  */
1901                     abort ();
1902
1903                   /* Make room for the result.  */
1904                   if (count >= allocated - length)
1905                     {
1906                       size_t n = xsum (length, count);
1907
1908                       ENSURE_ALLOCATION (n);
1909                     }
1910
1911                   /* Append the result.  */
1912                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
1913                   if (tmp != tmpbuf)
1914                     free (tmp);
1915                   length += count;
1916                 }
1917               }
1918 #endif
1919 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1920             else if (dp->conversion == 'a' || dp->conversion == 'A')
1921               {
1922                 arg_type type = a.arg[dp->arg_index].type;
1923                 int flags = dp->flags;
1924                 int has_width;
1925                 size_t width;
1926                 int has_precision;
1927                 size_t precision;
1928                 size_t tmp_length;
1929                 CHAR_T tmpbuf[700];
1930                 CHAR_T *tmp;
1931                 CHAR_T *pad_ptr;
1932                 CHAR_T *p;
1933
1934                 has_width = 0;
1935                 width = 0;
1936                 if (dp->width_start != dp->width_end)
1937                   {
1938                     if (dp->width_arg_index != ARG_NONE)
1939                       {
1940                         int arg;
1941
1942                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1943                           abort ();
1944                         arg = a.arg[dp->width_arg_index].a.a_int;
1945                         if (arg < 0)
1946                           {
1947                             /* "A negative field width is taken as a '-' flag
1948                                 followed by a positive field width."  */
1949                             flags |= FLAG_LEFT;
1950                             width = (unsigned int) (-arg);
1951                           }
1952                         else
1953                           width = arg;
1954                       }
1955                     else
1956                       {
1957                         const CHAR_T *digitp = dp->width_start;
1958
1959                         do
1960                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1961                         while (digitp != dp->width_end);
1962                       }
1963                     has_width = 1;
1964                   }
1965
1966                 has_precision = 0;
1967                 precision = 0;
1968                 if (dp->precision_start != dp->precision_end)
1969                   {
1970                     if (dp->precision_arg_index != ARG_NONE)
1971                       {
1972                         int arg;
1973
1974                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1975                           abort ();
1976                         arg = a.arg[dp->precision_arg_index].a.a_int;
1977                         /* "A negative precision is taken as if the precision
1978                             were omitted."  */
1979                         if (arg >= 0)
1980                           {
1981                             precision = arg;
1982                             has_precision = 1;
1983                           }
1984                       }
1985                     else
1986                       {
1987                         const CHAR_T *digitp = dp->precision_start + 1;
1988
1989                         precision = 0;
1990                         while (digitp != dp->precision_end)
1991                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1992                         has_precision = 1;
1993                       }
1994                   }
1995
1996                 /* Allocate a temporary buffer of sufficient size.  */
1997                 if (type == TYPE_LONGDOUBLE)
1998                   tmp_length =
1999                     (unsigned int) ((LDBL_DIG + 1)
2000                                     * 0.831 /* decimal -> hexadecimal */
2001                                    )
2002                     + 1; /* turn floor into ceil */
2003                 else
2004                   tmp_length =
2005                     (unsigned int) ((DBL_DIG + 1)
2006                                     * 0.831 /* decimal -> hexadecimal */
2007                                    )
2008                     + 1; /* turn floor into ceil */
2009                 if (tmp_length < precision)
2010                   tmp_length = precision;
2011                 /* Account for sign, decimal point etc. */
2012                 tmp_length = xsum (tmp_length, 12);
2013
2014                 if (tmp_length < width)
2015                   tmp_length = width;
2016
2017                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2018
2019                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2020                   tmp = tmpbuf;
2021                 else
2022                   {
2023                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2024
2025                     if (size_overflow_p (tmp_memsize))
2026                       /* Overflow, would lead to out of memory.  */
2027                       goto out_of_memory;
2028                     tmp = (CHAR_T *) malloc (tmp_memsize);
2029                     if (tmp == NULL)
2030                       /* Out of memory.  */
2031                       goto out_of_memory;
2032                   }
2033
2034                 pad_ptr = NULL;
2035                 p = tmp;
2036                 if (type == TYPE_LONGDOUBLE)
2037                   {
2038                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2039
2040                     if (isnanl (arg))
2041                       {
2042                         if (dp->conversion == 'A')
2043                           {
2044                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2045                           }
2046                         else
2047                           {
2048                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2049                           }
2050                       }
2051                     else
2052                       {
2053                         int sign = 0;
2054                         DECL_LONG_DOUBLE_ROUNDING
2055
2056                         BEGIN_LONG_DOUBLE_ROUNDING ();
2057
2058                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2059                           {
2060                             sign = -1;
2061                             arg = -arg;
2062                           }
2063
2064                         if (sign < 0)
2065                           *p++ = '-';
2066                         else if (flags & FLAG_SHOWSIGN)
2067                           *p++ = '+';
2068                         else if (flags & FLAG_SPACE)
2069                           *p++ = ' ';
2070
2071                         if (arg > 0.0L && arg + arg == arg)
2072                           {
2073                             if (dp->conversion == 'A')
2074                               {
2075                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2076                               }
2077                             else
2078                               {
2079                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2080                               }
2081                           }
2082                         else
2083                           {
2084                             int exponent;
2085                             long double mantissa;
2086
2087                             if (arg > 0.0L)
2088                               mantissa = printf_frexpl (arg, &exponent);
2089                             else
2090                               {
2091                                 exponent = 0;
2092                                 mantissa = 0.0L;
2093                               }
2094
2095                             if (has_precision
2096                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2097                               {
2098                                 /* Round the mantissa.  */
2099                                 long double tail = mantissa;
2100                                 size_t q;
2101
2102                                 for (q = precision; ; q--)
2103                                   {
2104                                     int digit = (int) tail;
2105                                     tail -= digit;
2106                                     if (q == 0)
2107                                       {
2108                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2109                                           tail = 1 - tail;
2110                                         else
2111                                           tail = - tail;
2112                                         break;
2113                                       }
2114                                     tail *= 16.0L;
2115                                   }
2116                                 if (tail != 0.0L)
2117                                   for (q = precision; q > 0; q--)
2118                                     tail *= 0.0625L;
2119                                 mantissa += tail;
2120                               }
2121
2122                             *p++ = '0';
2123                             *p++ = dp->conversion - 'A' + 'X';
2124                             pad_ptr = p;
2125                             {
2126                               int digit;
2127
2128                               digit = (int) mantissa;
2129                               mantissa -= digit;
2130                               *p++ = '0' + digit;
2131                               if ((flags & FLAG_ALT)
2132                                   || mantissa > 0.0L || precision > 0)
2133                                 {
2134                                   *p++ = decimal_point_char ();
2135                                   /* This loop terminates because we assume
2136                                      that FLT_RADIX is a power of 2.  */
2137                                   while (mantissa > 0.0L)
2138                                     {
2139                                       mantissa *= 16.0L;
2140                                       digit = (int) mantissa;
2141                                       mantissa -= digit;
2142                                       *p++ = digit
2143                                              + (digit < 10
2144                                                 ? '0'
2145                                                 : dp->conversion - 10);
2146                                       if (precision > 0)
2147                                         precision--;
2148                                     }
2149                                   while (precision > 0)
2150                                     {
2151                                       *p++ = '0';
2152                                       precision--;
2153                                     }
2154                                 }
2155                               }
2156                               *p++ = dp->conversion - 'A' + 'P';
2157 # if WIDE_CHAR_VERSION
2158                               {
2159                                 static const wchar_t decimal_format[] =
2160                                   { '%', '+', 'd', '\0' };
2161                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2162                               }
2163 # else
2164                               sprintf (p, "%+d", exponent);
2165 # endif
2166                               while (*p != '\0')
2167                                 p++;
2168                           }
2169
2170                         END_LONG_DOUBLE_ROUNDING ();
2171                       }
2172                   }
2173                 else
2174                   {
2175                     double arg = a.arg[dp->arg_index].a.a_double;
2176
2177                     if (isnan (arg))
2178                       {
2179                         if (dp->conversion == 'A')
2180                           {
2181                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2182                           }
2183                         else
2184                           {
2185                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2186                           }
2187                       }
2188                     else
2189                       {
2190                         int sign = 0;
2191
2192                         if (signbit (arg)) /* arg < 0.0 or negative zero */
2193                           {
2194                             sign = -1;
2195                             arg = -arg;
2196                           }
2197
2198                         if (sign < 0)
2199                           *p++ = '-';
2200                         else if (flags & FLAG_SHOWSIGN)
2201                           *p++ = '+';
2202                         else if (flags & FLAG_SPACE)
2203                           *p++ = ' ';
2204
2205                         if (arg > 0.0 && arg + arg == arg)
2206                           {
2207                             if (dp->conversion == 'A')
2208                               {
2209                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2210                               }
2211                             else
2212                               {
2213                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2214                               }
2215                           }
2216                         else
2217                           {
2218                             int exponent;
2219                             double mantissa;
2220
2221                             if (arg > 0.0)
2222                               mantissa = printf_frexp (arg, &exponent);
2223                             else
2224                               {
2225                                 exponent = 0;
2226                                 mantissa = 0.0;
2227                               }
2228
2229                             if (has_precision
2230                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2231                               {
2232                                 /* Round the mantissa.  */
2233                                 double tail = mantissa;
2234                                 size_t q;
2235
2236                                 for (q = precision; ; q--)
2237                                   {
2238                                     int digit = (int) tail;
2239                                     tail -= digit;
2240                                     if (q == 0)
2241                                       {
2242                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2243                                           tail = 1 - tail;
2244                                         else
2245                                           tail = - tail;
2246                                         break;
2247                                       }
2248                                     tail *= 16.0;
2249                                   }
2250                                 if (tail != 0.0)
2251                                   for (q = precision; q > 0; q--)
2252                                     tail *= 0.0625;
2253                                 mantissa += tail;
2254                               }
2255
2256                             *p++ = '0';
2257                             *p++ = dp->conversion - 'A' + 'X';
2258                             pad_ptr = p;
2259                             {
2260                               int digit;
2261
2262                               digit = (int) mantissa;
2263                               mantissa -= digit;
2264                               *p++ = '0' + digit;
2265                               if ((flags & FLAG_ALT)
2266                                   || mantissa > 0.0 || precision > 0)
2267                                 {
2268                                   *p++ = decimal_point_char ();
2269                                   /* This loop terminates because we assume
2270                                      that FLT_RADIX is a power of 2.  */
2271                                   while (mantissa > 0.0)
2272                                     {
2273                                       mantissa *= 16.0;
2274                                       digit = (int) mantissa;
2275                                       mantissa -= digit;
2276                                       *p++ = digit
2277                                              + (digit < 10
2278                                                 ? '0'
2279                                                 : dp->conversion - 10);
2280                                       if (precision > 0)
2281                                         precision--;
2282                                     }
2283                                   while (precision > 0)
2284                                     {
2285                                       *p++ = '0';
2286                                       precision--;
2287                                     }
2288                                 }
2289                               }
2290                               *p++ = dp->conversion - 'A' + 'P';
2291 # if WIDE_CHAR_VERSION
2292                               {
2293                                 static const wchar_t decimal_format[] =
2294                                   { '%', '+', 'd', '\0' };
2295                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2296                               }
2297 # else
2298                               sprintf (p, "%+d", exponent);
2299 # endif
2300                               while (*p != '\0')
2301                                 p++;
2302                           }
2303                       }
2304                   }
2305                 /* The generated string now extends from tmp to p, with the
2306                    zero padding insertion point being at pad_ptr.  */
2307                 if (has_width && p - tmp < width)
2308                   {
2309                     size_t pad = width - (p - tmp);
2310                     CHAR_T *end = p + pad;
2311
2312                     if (flags & FLAG_LEFT)
2313                       {
2314                         /* Pad with spaces on the right.  */
2315                         for (; pad > 0; pad--)
2316                           *p++ = ' ';
2317                       }
2318                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2319                       {
2320                         /* Pad with zeroes.  */
2321                         CHAR_T *q = end;
2322
2323                         while (p > pad_ptr)
2324                           *--q = *--p;
2325                         for (; pad > 0; pad--)
2326                           *p++ = '0';
2327                       }
2328                     else
2329                       {
2330                         /* Pad with spaces on the left.  */
2331                         CHAR_T *q = end;
2332
2333                         while (p > tmp)
2334                           *--q = *--p;
2335                         for (; pad > 0; pad--)
2336                           *p++ = ' ';
2337                       }
2338
2339                     p = end;
2340                   }
2341
2342                 {
2343                   size_t count = p - tmp;
2344
2345                   if (count >= tmp_length)
2346                     /* tmp_length was incorrectly calculated - fix the
2347                        code above!  */
2348                     abort ();
2349
2350                   /* Make room for the result.  */
2351                   if (count >= allocated - length)
2352                     {
2353                       size_t n = xsum (length, count);
2354
2355                       ENSURE_ALLOCATION (n);
2356                     }
2357
2358                   /* Append the result.  */
2359                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
2360                   if (tmp != tmpbuf)
2361                     free (tmp);
2362                   length += count;
2363                 }
2364               }
2365 #endif
2366             else
2367               {
2368                 arg_type type = a.arg[dp->arg_index].type;
2369                 int flags = dp->flags;
2370 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2371                 int has_width;
2372                 size_t width;
2373 #endif
2374 #if NEED_PRINTF_FLAG_ZERO
2375                 int pad_ourselves;
2376 #else
2377 #               define pad_ourselves 0
2378 #endif
2379                 CHAR_T *fbp;
2380                 unsigned int prefix_count;
2381                 int prefixes[2];
2382 #if !USE_SNPRINTF
2383                 size_t tmp_length;
2384                 CHAR_T tmpbuf[700];
2385                 CHAR_T *tmp;
2386 #endif
2387
2388 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2389                 has_width = 0;
2390                 width = 0;
2391                 if (dp->width_start != dp->width_end)
2392                   {
2393                     if (dp->width_arg_index != ARG_NONE)
2394                       {
2395                         int arg;
2396
2397                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2398                           abort ();
2399                         arg = a.arg[dp->width_arg_index].a.a_int;
2400                         if (arg < 0)
2401                           {
2402                             /* "A negative field width is taken as a '-' flag
2403                                 followed by a positive field width."  */
2404                             flags |= FLAG_LEFT;
2405                             width = (unsigned int) (-arg);
2406                           }
2407                         else
2408                           width = arg;
2409                       }
2410                     else
2411                       {
2412                         const CHAR_T *digitp = dp->width_start;
2413
2414                         do
2415                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2416                         while (digitp != dp->width_end);
2417                       }
2418                     has_width = 1;
2419                   }
2420 #endif
2421
2422 #if !USE_SNPRINTF
2423                 /* Allocate a temporary buffer of sufficient size for calling
2424                    sprintf.  */
2425                 {
2426                   size_t precision;
2427
2428                   precision = 6;
2429                   if (dp->precision_start != dp->precision_end)
2430                     {
2431                       if (dp->precision_arg_index != ARG_NONE)
2432                         {
2433                           int arg;
2434
2435                           if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2436                             abort ();
2437                           arg = a.arg[dp->precision_arg_index].a.a_int;
2438                           precision = (arg < 0 ? 0 : arg);
2439                         }
2440                       else
2441                         {
2442                           const CHAR_T *digitp = dp->precision_start + 1;
2443
2444                           precision = 0;
2445                           while (digitp != dp->precision_end)
2446                             precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2447                         }
2448                     }
2449
2450                   switch (dp->conversion)
2451                     {
2452
2453                     case 'd': case 'i': case 'u':
2454 # if HAVE_LONG_LONG_INT
2455                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2456                         tmp_length =
2457                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2458                                           * 0.30103 /* binary -> decimal */
2459                                          )
2460                           + 1; /* turn floor into ceil */
2461                       else
2462 # endif
2463                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2464                         tmp_length =
2465                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2466                                           * 0.30103 /* binary -> decimal */
2467                                          )
2468                           + 1; /* turn floor into ceil */
2469                       else
2470                         tmp_length =
2471                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2472                                           * 0.30103 /* binary -> decimal */
2473                                          )
2474                           + 1; /* turn floor into ceil */
2475                       if (tmp_length < precision)
2476                         tmp_length = precision;
2477                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
2478                       tmp_length = xsum (tmp_length, tmp_length);
2479                       /* Add 1, to account for a leading sign.  */
2480                       tmp_length = xsum (tmp_length, 1);
2481                       break;
2482
2483                     case 'o':
2484 # if HAVE_LONG_LONG_INT
2485                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2486                         tmp_length =
2487                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2488                                           * 0.333334 /* binary -> octal */
2489                                          )
2490                           + 1; /* turn floor into ceil */
2491                       else
2492 # endif
2493                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2494                         tmp_length =
2495                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2496                                           * 0.333334 /* binary -> octal */
2497                                          )
2498                           + 1; /* turn floor into ceil */
2499                       else
2500                         tmp_length =
2501                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2502                                           * 0.333334 /* binary -> octal */
2503                                          )
2504                           + 1; /* turn floor into ceil */
2505                       if (tmp_length < precision)
2506                         tmp_length = precision;
2507                       /* Add 1, to account for a leading sign.  */
2508                       tmp_length = xsum (tmp_length, 1);
2509                       break;
2510
2511                     case 'x': case 'X':
2512 # if HAVE_LONG_LONG_INT
2513                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2514                         tmp_length =
2515                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2516                                           * 0.25 /* binary -> hexadecimal */
2517                                          )
2518                           + 1; /* turn floor into ceil */
2519                       else
2520 # endif
2521                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2522                         tmp_length =
2523                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2524                                           * 0.25 /* binary -> hexadecimal */
2525                                          )
2526                           + 1; /* turn floor into ceil */
2527                       else
2528                         tmp_length =
2529                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2530                                           * 0.25 /* binary -> hexadecimal */
2531                                          )
2532                           + 1; /* turn floor into ceil */
2533                       if (tmp_length < precision)
2534                         tmp_length = precision;
2535                       /* Add 2, to account for a leading sign or alternate form.  */
2536                       tmp_length = xsum (tmp_length, 2);
2537                       break;
2538
2539                     case 'f': case 'F':
2540                       if (type == TYPE_LONGDOUBLE)
2541                         tmp_length =
2542                           (unsigned int) (LDBL_MAX_EXP
2543                                           * 0.30103 /* binary -> decimal */
2544                                           * 2 /* estimate for FLAG_GROUP */
2545                                          )
2546                           + 1 /* turn floor into ceil */
2547                           + 10; /* sign, decimal point etc. */
2548                       else
2549                         tmp_length =
2550                           (unsigned int) (DBL_MAX_EXP
2551                                           * 0.30103 /* binary -> decimal */
2552                                           * 2 /* estimate for FLAG_GROUP */
2553                                          )
2554                           + 1 /* turn floor into ceil */
2555                           + 10; /* sign, decimal point etc. */
2556                       tmp_length = xsum (tmp_length, precision);
2557                       break;
2558
2559                     case 'e': case 'E': case 'g': case 'G':
2560                       tmp_length =
2561                         12; /* sign, decimal point, exponent etc. */
2562                       tmp_length = xsum (tmp_length, precision);
2563                       break;
2564
2565                     case 'a': case 'A':
2566                       if (type == TYPE_LONGDOUBLE)
2567                         tmp_length =
2568                           (unsigned int) (LDBL_DIG
2569                                           * 0.831 /* decimal -> hexadecimal */
2570                                          )
2571                           + 1; /* turn floor into ceil */
2572                       else
2573                         tmp_length =
2574                           (unsigned int) (DBL_DIG
2575                                           * 0.831 /* decimal -> hexadecimal */
2576                                          )
2577                           + 1; /* turn floor into ceil */
2578                       if (tmp_length < precision)
2579                         tmp_length = precision;
2580                       /* Account for sign, decimal point etc. */
2581                       tmp_length = xsum (tmp_length, 12);
2582                       break;
2583
2584                     case 'c':
2585 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2586                       if (type == TYPE_WIDE_CHAR)
2587                         tmp_length = MB_CUR_MAX;
2588                       else
2589 # endif
2590                         tmp_length = 1;
2591                       break;
2592
2593                     case 's':
2594 # if HAVE_WCHAR_T
2595                       if (type == TYPE_WIDE_STRING)
2596                         {
2597                           tmp_length =
2598                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2599
2600 #  if !WIDE_CHAR_VERSION
2601                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2602 #  endif
2603                         }
2604                       else
2605 # endif
2606                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2607                       break;
2608
2609                     case 'p':
2610                       tmp_length =
2611                         (unsigned int) (sizeof (void *) * CHAR_BIT
2612                                         * 0.25 /* binary -> hexadecimal */
2613                                        )
2614                           + 1 /* turn floor into ceil */
2615                           + 2; /* account for leading 0x */
2616                       break;
2617
2618                     default:
2619                       abort ();
2620                     }
2621
2622                   if (tmp_length < width)
2623                     tmp_length = width;
2624
2625                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2626                 }
2627
2628                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2629                   tmp = tmpbuf;
2630                 else
2631                   {
2632                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2633
2634                     if (size_overflow_p (tmp_memsize))
2635                       /* Overflow, would lead to out of memory.  */
2636                       goto out_of_memory;
2637                     tmp = (CHAR_T *) malloc (tmp_memsize);
2638                     if (tmp == NULL)
2639                       /* Out of memory.  */
2640                       goto out_of_memory;
2641                   }
2642 #endif
2643
2644                 /* Decide whether to perform the padding ourselves.  */
2645 #if NEED_PRINTF_FLAG_ZERO
2646                 switch (dp->conversion)
2647                   {
2648                   case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2649                   case 'a': case 'A':
2650                     pad_ourselves = 1;
2651                     break;
2652                   default:
2653                     pad_ourselves = 0;
2654                     break;
2655                   }
2656 #endif
2657
2658                 /* Construct the format string for calling snprintf or
2659                    sprintf.  */
2660                 fbp = buf;
2661                 *fbp++ = '%';
2662 #if NEED_PRINTF_FLAG_GROUPING
2663                 /* The underlying implementation doesn't support the ' flag.
2664                    Produce no grouping characters in this case; this is
2665                    acceptable because the grouping is locale dependent.  */
2666 #else
2667                 if (flags & FLAG_GROUP)
2668                   *fbp++ = '\'';
2669 #endif
2670                 if (flags & FLAG_LEFT)
2671                   *fbp++ = '-';
2672                 if (flags & FLAG_SHOWSIGN)
2673                   *fbp++ = '+';
2674                 if (flags & FLAG_SPACE)
2675                   *fbp++ = ' ';
2676                 if (flags & FLAG_ALT)
2677                   *fbp++ = '#';
2678                 if (!pad_ourselves)
2679                   {
2680                     if (flags & FLAG_ZERO)
2681                       *fbp++ = '0';
2682                     if (dp->width_start != dp->width_end)
2683                       {
2684                         size_t n = dp->width_end - dp->width_start;
2685                         memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2686                         fbp += n;
2687                       }
2688                   }
2689                 if (dp->precision_start != dp->precision_end)
2690                   {
2691                     size_t n = dp->precision_end - dp->precision_start;
2692                     memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2693                     fbp += n;
2694                   }
2695
2696                 switch (type)
2697                   {
2698 #if HAVE_LONG_LONG_INT
2699                   case TYPE_LONGLONGINT:
2700                   case TYPE_ULONGLONGINT:
2701 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2702                     *fbp++ = 'I';
2703                     *fbp++ = '6';
2704                     *fbp++ = '4';
2705                     break;
2706 # else
2707                     *fbp++ = 'l';
2708                     /*FALLTHROUGH*/
2709 # endif
2710 #endif
2711                   case TYPE_LONGINT:
2712                   case TYPE_ULONGINT:
2713 #if HAVE_WINT_T
2714                   case TYPE_WIDE_CHAR:
2715 #endif
2716 #if HAVE_WCHAR_T
2717                   case TYPE_WIDE_STRING:
2718 #endif
2719                     *fbp++ = 'l';
2720                     break;
2721                   case TYPE_LONGDOUBLE:
2722                     *fbp++ = 'L';
2723                     break;
2724                   default:
2725                     break;
2726                   }
2727 #if NEED_PRINTF_DIRECTIVE_F
2728                 if (dp->conversion == 'F')
2729                   *fbp = 'f';
2730                 else
2731 #endif
2732                   *fbp = dp->conversion;
2733 #if USE_SNPRINTF
2734                 fbp[1] = '%';
2735                 fbp[2] = 'n';
2736                 fbp[3] = '\0';
2737 #else
2738                 fbp[1] = '\0';
2739 #endif
2740
2741                 /* Construct the arguments for calling snprintf or sprintf.  */
2742                 prefix_count = 0;
2743                 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2744                   {
2745                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2746                       abort ();
2747                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2748                   }
2749                 if (dp->precision_arg_index != ARG_NONE)
2750                   {
2751                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2752                       abort ();
2753                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2754                   }
2755
2756 #if USE_SNPRINTF
2757                 /* Prepare checking whether snprintf returns the count
2758                    via %n.  */
2759                 ENSURE_ALLOCATION (xsum (length, 1));
2760                 result[length] = '\0';
2761 #endif
2762
2763                 for (;;)
2764                   {
2765                     size_t maxlen;
2766                     int count;
2767                     int retcount;
2768
2769                     maxlen = allocated - length;
2770                     count = -1;
2771                     retcount = 0;
2772
2773 #if USE_SNPRINTF
2774                     /* SNPRINTF can fail if maxlen > INT_MAX.  */
2775                     if (maxlen > INT_MAX)
2776                       goto overflow;
2777 # define SNPRINTF_BUF(arg) \
2778                     switch (prefix_count)                                   \
2779                       {                                                     \
2780                       case 0:                                               \
2781                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2782                                              arg, &count);                  \
2783                         break;                                              \
2784                       case 1:                                               \
2785                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2786                                              prefixes[0], arg, &count);     \
2787                         break;                                              \
2788                       case 2:                                               \
2789                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2790                                              prefixes[0], prefixes[1], arg, \
2791                                              &count);                       \
2792                         break;                                              \
2793                       default:                                              \
2794                         abort ();                                           \
2795                       }
2796 #else
2797 # define SNPRINTF_BUF(arg) \
2798                     switch (prefix_count)                                   \
2799                       {                                                     \
2800                       case 0:                                               \
2801                         count = sprintf (tmp, buf, arg);                    \
2802                         break;                                              \
2803                       case 1:                                               \
2804                         count = sprintf (tmp, buf, prefixes[0], arg);       \
2805                         break;                                              \
2806                       case 2:                                               \
2807                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2808                                          arg);                              \
2809                         break;                                              \
2810                       default:                                              \
2811                         abort ();                                           \
2812                       }
2813 #endif
2814
2815                     switch (type)
2816                       {
2817                       case TYPE_SCHAR:
2818                         {
2819                           int arg = a.arg[dp->arg_index].a.a_schar;
2820                           SNPRINTF_BUF (arg);
2821                         }
2822                         break;
2823                       case TYPE_UCHAR:
2824                         {
2825                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2826                           SNPRINTF_BUF (arg);
2827                         }
2828                         break;
2829                       case TYPE_SHORT:
2830                         {
2831                           int arg = a.arg[dp->arg_index].a.a_short;
2832                           SNPRINTF_BUF (arg);
2833                         }
2834                         break;
2835                       case TYPE_USHORT:
2836                         {
2837                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2838                           SNPRINTF_BUF (arg);
2839                         }
2840                         break;
2841                       case TYPE_INT:
2842                         {
2843                           int arg = a.arg[dp->arg_index].a.a_int;
2844                           SNPRINTF_BUF (arg);
2845                         }
2846                         break;
2847                       case TYPE_UINT:
2848                         {
2849                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2850                           SNPRINTF_BUF (arg);
2851                         }
2852                         break;
2853                       case TYPE_LONGINT:
2854                         {
2855                           long int arg = a.arg[dp->arg_index].a.a_longint;
2856                           SNPRINTF_BUF (arg);
2857                         }
2858                         break;
2859                       case TYPE_ULONGINT:
2860                         {
2861                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2862                           SNPRINTF_BUF (arg);
2863                         }
2864                         break;
2865 #if HAVE_LONG_LONG_INT
2866                       case TYPE_LONGLONGINT:
2867                         {
2868                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2869                           SNPRINTF_BUF (arg);
2870                         }
2871                         break;
2872                       case TYPE_ULONGLONGINT:
2873                         {
2874                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2875                           SNPRINTF_BUF (arg);
2876                         }
2877                         break;
2878 #endif
2879                       case TYPE_DOUBLE:
2880                         {
2881                           double arg = a.arg[dp->arg_index].a.a_double;
2882                           SNPRINTF_BUF (arg);
2883                         }
2884                         break;
2885                       case TYPE_LONGDOUBLE:
2886                         {
2887                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
2888                           SNPRINTF_BUF (arg);
2889                         }
2890                         break;
2891                       case TYPE_CHAR:
2892                         {
2893                           int arg = a.arg[dp->arg_index].a.a_char;
2894                           SNPRINTF_BUF (arg);
2895                         }
2896                         break;
2897 #if HAVE_WINT_T
2898                       case TYPE_WIDE_CHAR:
2899                         {
2900                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2901                           SNPRINTF_BUF (arg);
2902                         }
2903                         break;
2904 #endif
2905                       case TYPE_STRING:
2906                         {
2907                           const char *arg = a.arg[dp->arg_index].a.a_string;
2908                           SNPRINTF_BUF (arg);
2909                         }
2910                         break;
2911 #if HAVE_WCHAR_T
2912                       case TYPE_WIDE_STRING:
2913                         {
2914                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2915                           SNPRINTF_BUF (arg);
2916                         }
2917                         break;
2918 #endif
2919                       case TYPE_POINTER:
2920                         {
2921                           void *arg = a.arg[dp->arg_index].a.a_pointer;
2922                           SNPRINTF_BUF (arg);
2923                         }
2924                         break;
2925                       default:
2926                         abort ();
2927                       }
2928
2929 #if USE_SNPRINTF
2930                     /* Portability: Not all implementations of snprintf()
2931                        are ISO C 99 compliant.  Determine the number of
2932                        bytes that snprintf() has produced or would have
2933                        produced.  */
2934                     if (count >= 0)
2935                       {
2936                         /* Verify that snprintf() has NUL-terminated its
2937                            result.  */
2938                         if (count < maxlen && result[length + count] != '\0')
2939                           abort ();
2940                         /* Portability hack.  */
2941                         if (retcount > count)
2942                           count = retcount;
2943                       }
2944                     else
2945                       {
2946                         /* snprintf() doesn't understand the '%n'
2947                            directive.  */
2948                         if (fbp[1] != '\0')
2949                           {
2950                             /* Don't use the '%n' directive; instead, look
2951                                at the snprintf() return value.  */
2952                             fbp[1] = '\0';
2953                             continue;
2954                           }
2955                         else
2956                           {
2957                             /* Look at the snprintf() return value.  */
2958                             if (retcount < 0)
2959                               {
2960                                 /* HP-UX 10.20 snprintf() is doubly deficient:
2961                                    It doesn't understand the '%n' directive,
2962                                    *and* it returns -1 (rather than the length
2963                                    that would have been required) when the
2964                                    buffer is too small.  */
2965                                 size_t bigger_need =
2966                                   xsum (xtimes (allocated, 2), 12);
2967                                 ENSURE_ALLOCATION (bigger_need);
2968                                 continue;
2969                               }
2970                             else
2971                               count = retcount;
2972                           }
2973                       }
2974 #endif
2975
2976                     /* Attempt to handle failure.  */
2977                     if (count < 0)
2978                       {
2979                         if (!(result == resultbuf || result == NULL))
2980                           free (result);
2981                         if (buf_malloced != NULL)
2982                           free (buf_malloced);
2983                         CLEANUP ();
2984                         errno = EINVAL;
2985                         return NULL;
2986                       }
2987
2988                     /* Make room for the result.  */
2989                     if (count >= maxlen)
2990                       {
2991                         /* Need at least count bytes.  But allocate
2992                            proportionally, to avoid looping eternally if
2993                            snprintf() reports a too small count.  */
2994                         size_t n =
2995                           xmax (xsum (length, count), xtimes (allocated, 2));
2996
2997                         ENSURE_ALLOCATION (n);
2998 #if USE_SNPRINTF
2999                         continue;
3000 #else
3001                         maxlen = allocated - length;
3002 #endif
3003                       }
3004
3005                     /* Perform padding.  */
3006 #if NEED_PRINTF_FLAG_ZERO
3007                     if (pad_ourselves && has_width && count < width)
3008                       {
3009 # if USE_SNPRINTF
3010                         /* Make room for the result.  */
3011                         if (width >= maxlen)
3012                           {
3013                             /* Need at least width bytes.  But allocate
3014                                proportionally, to avoid looping eternally if
3015                                snprintf() reports a too small count.  */
3016                             size_t n =
3017                               xmax (xsum (length + 1, width),
3018                                     xtimes (allocated, 2));
3019
3020                             length += count;
3021                             ENSURE_ALLOCATION (n);
3022                             length -= count;
3023                             maxlen = allocated - length; /* > width */
3024                           }
3025                         /* Here width < maxlen.  */
3026 # endif
3027                         {
3028 # if USE_SNPRINTF
3029                           CHAR_T * const rp = result + length;
3030 # else
3031                           CHAR_T * const rp = tmp;
3032 # endif
3033                           CHAR_T *p = rp + count;
3034                           size_t pad = width - count;
3035                           CHAR_T *end = p + pad;
3036                           CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3037                           /* No zero-padding of "inf" and "nan".  */
3038                           if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3039                               || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3040                             pad_ptr = NULL;
3041                           /* The generated string now extends from rp to p,
3042                              with the zero padding insertion point being at
3043                              pad_ptr.  */
3044
3045                           if (flags & FLAG_LEFT)
3046                             {
3047                               /* Pad with spaces on the right.  */
3048                               for (; pad > 0; pad--)
3049                                 *p++ = ' ';
3050                             }
3051                           else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3052                             {
3053                               /* Pad with zeroes.  */
3054                               CHAR_T *q = end;
3055
3056                               while (p > pad_ptr)
3057                                 *--q = *--p;
3058                               for (; pad > 0; pad--)
3059                                 *p++ = '0';
3060                             }
3061                           else
3062                             {
3063                               /* Pad with spaces on the left.  */
3064                               CHAR_T *q = end;
3065
3066                               while (p > rp)
3067                                 *--q = *--p;
3068                               for (; pad > 0; pad--)
3069                                 *p++ = ' ';
3070                             }
3071
3072                           count = width; /* = count + pad = end - rp */
3073                         }
3074                       }
3075 #endif
3076
3077 #if !USE_SNPRINTF
3078                     if (count >= tmp_length)
3079                       /* tmp_length was incorrectly calculated - fix the
3080                          code above!  */
3081                       abort ();
3082 #endif
3083
3084                     /* Here still count < maxlen.  */
3085
3086 #if USE_SNPRINTF
3087                     /* The snprintf() result did fit.  */
3088 #else
3089                     /* Append the sprintf() result.  */
3090                     memcpy (result + length, tmp, count * sizeof (CHAR_T));
3091                     if (tmp != tmpbuf)
3092                       free (tmp);
3093 #endif
3094
3095 #if NEED_PRINTF_DIRECTIVE_F
3096                     if (dp->conversion == 'F')
3097                       {
3098                         /* Convert the %f result to upper case for %F.  */
3099                         CHAR_T *rp = result + length;
3100                         size_t rc;
3101                         for (rc = count; rc > 0; rc--, rp++)
3102                           if (*rp >= 'a' && *rp <= 'z')
3103                             *rp = *rp - 'a' + 'A';
3104                       }
3105 #endif
3106
3107                     length += count;
3108                     break;
3109                   }
3110               }
3111           }
3112       }
3113
3114     /* Add the final NUL.  */
3115     ENSURE_ALLOCATION (xsum (length, 1));
3116     result[length] = '\0';
3117
3118     if (result != resultbuf && length + 1 < allocated)
3119       {
3120         /* Shrink the allocated memory if possible.  */
3121         CHAR_T *memory;
3122
3123         memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3124         if (memory != NULL)
3125           result = memory;
3126       }
3127
3128     if (buf_malloced != NULL)
3129       free (buf_malloced);
3130     CLEANUP ();
3131     *lengthp = length;
3132     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
3133        says that snprintf() fails with errno = EOVERFLOW in this case, but
3134        that's only because snprintf() returns an 'int'.  This function does
3135        not have this limitation.  */
3136     return result;
3137
3138   overflow:
3139     if (!(result == resultbuf || result == NULL))
3140       free (result);
3141     if (buf_malloced != NULL)
3142       free (buf_malloced);
3143     CLEANUP ();
3144     errno = EOVERFLOW;
3145     return NULL;
3146
3147   out_of_memory:
3148     if (!(result == resultbuf || result == NULL))
3149       free (result);
3150     if (buf_malloced != NULL)
3151       free (buf_malloced);
3152   out_of_memory_1:
3153     CLEANUP ();
3154     errno = ENOMEM;
3155     return NULL;
3156   }
3157 }
3158
3159 #undef SNPRINTF
3160 #undef USE_SNPRINTF
3161 #undef PRINTF_PARSE
3162 #undef DIRECTIVES
3163 #undef DIRECTIVE
3164 #undef CHAR_T
3165 #undef VASNPRINTF