Fix a warning in last patch.
[pspp] / 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 # if NEED_PRINTF_INFINITE && NEED_PRINTF_LONG_DOUBLE
1294                 arg_type type = a.arg[dp->arg_index].type;
1295 # endif
1296                 int flags = dp->flags;
1297                 int has_width;
1298                 size_t width;
1299                 int has_precision;
1300                 size_t precision;
1301                 size_t tmp_length;
1302                 CHAR_T tmpbuf[700];
1303                 CHAR_T *tmp;
1304                 CHAR_T *pad_ptr;
1305                 CHAR_T *p;
1306
1307                 has_width = 0;
1308                 width = 0;
1309                 if (dp->width_start != dp->width_end)
1310                   {
1311                     if (dp->width_arg_index != ARG_NONE)
1312                       {
1313                         int arg;
1314
1315                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1316                           abort ();
1317                         arg = a.arg[dp->width_arg_index].a.a_int;
1318                         if (arg < 0)
1319                           {
1320                             /* "A negative field width is taken as a '-' flag
1321                                 followed by a positive field width."  */
1322                             flags |= FLAG_LEFT;
1323                             width = (unsigned int) (-arg);
1324                           }
1325                         else
1326                           width = arg;
1327                       }
1328                     else
1329                       {
1330                         const CHAR_T *digitp = dp->width_start;
1331
1332                         do
1333                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1334                         while (digitp != dp->width_end);
1335                       }
1336                     has_width = 1;
1337                   }
1338
1339                 has_precision = 0;
1340                 precision = 0;
1341                 if (dp->precision_start != dp->precision_end)
1342                   {
1343                     if (dp->precision_arg_index != ARG_NONE)
1344                       {
1345                         int arg;
1346
1347                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1348                           abort ();
1349                         arg = a.arg[dp->precision_arg_index].a.a_int;
1350                         /* "A negative precision is taken as if the precision
1351                             were omitted."  */
1352                         if (arg >= 0)
1353                           {
1354                             precision = arg;
1355                             has_precision = 1;
1356                           }
1357                       }
1358                     else
1359                       {
1360                         const CHAR_T *digitp = dp->precision_start + 1;
1361
1362                         precision = 0;
1363                         while (digitp != dp->precision_end)
1364                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1365                         has_precision = 1;
1366                       }
1367                   }
1368
1369                 /* POSIX specifies the default precision to be 6 for %f, %F,
1370                    %e, %E, but not for %g, %G.  Implementations appear to use
1371                    the same default precision also for %g, %G.  */
1372                 if (!has_precision)
1373                   precision = 6;
1374
1375                 /* Allocate a temporary buffer of sufficient size.  */
1376 # if NEED_PRINTF_INFINITE && NEED_PRINTF_LONG_DOUBLE
1377                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
1378 # elif NEED_PRINTF_LONG_DOUBLE
1379                 tmp_length = LDBL_DIG + 1;
1380 # elif NEED_PRINTF_INFINITE
1381                 tmp_length = 0;
1382 # endif
1383                 if (tmp_length < precision)
1384                   tmp_length = precision;
1385 # if NEED_PRINTF_LONG_DOUBLE
1386 #  if NEED_PRINTF_INFINITE
1387                 if (type == TYPE_LONGDOUBLE)
1388 #  endif
1389                   if (dp->conversion == 'f' || dp->conversion == 'F')
1390                     {
1391                       long double arg = a.arg[dp->arg_index].a.a_longdouble;
1392                       if (!(isnanl (arg) || arg + arg == arg))
1393                         {
1394                           /* arg is finite and nonzero.  */
1395                           int exponent = floorlog10l (arg < 0 ? -arg : arg);
1396                           if (exponent >= 0 && tmp_length < exponent + precision)
1397                             tmp_length = exponent + precision;
1398                         }
1399                     }
1400 # endif
1401                 /* Account for sign, decimal point etc. */
1402                 tmp_length = xsum (tmp_length, 12);
1403
1404                 if (tmp_length < width)
1405                   tmp_length = width;
1406
1407                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1408
1409                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1410                   tmp = tmpbuf;
1411                 else
1412                   {
1413                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1414
1415                     if (size_overflow_p (tmp_memsize))
1416                       /* Overflow, would lead to out of memory.  */
1417                       goto out_of_memory;
1418                     tmp = (CHAR_T *) malloc (tmp_memsize);
1419                     if (tmp == NULL)
1420                       /* Out of memory.  */
1421                       goto out_of_memory;
1422                   }
1423
1424                 pad_ptr = NULL;
1425                 p = tmp;
1426
1427 # if NEED_PRINTF_LONG_DOUBLE
1428 #  if NEED_PRINTF_INFINITE
1429                 if (type == TYPE_LONGDOUBLE)
1430 #  endif
1431                   {
1432                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
1433
1434                     if (isnanl (arg))
1435                       {
1436                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1437                           {
1438                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1439                           }
1440                         else
1441                           {
1442                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1443                           }
1444                       }
1445                     else
1446                       {
1447                         int sign = 0;
1448                         DECL_LONG_DOUBLE_ROUNDING
1449
1450                         BEGIN_LONG_DOUBLE_ROUNDING ();
1451
1452                         if (signbit (arg)) /* arg < 0.0L or negative zero */
1453                           {
1454                             sign = -1;
1455                             arg = -arg;
1456                           }
1457
1458                         if (sign < 0)
1459                           *p++ = '-';
1460                         else if (flags & FLAG_SHOWSIGN)
1461                           *p++ = '+';
1462                         else if (flags & FLAG_SPACE)
1463                           *p++ = ' ';
1464
1465                         if (arg > 0.0L && arg + arg == arg)
1466                           {
1467                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1468                               {
1469                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1470                               }
1471                             else
1472                               {
1473                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1474                               }
1475                           }
1476                         else
1477                           {
1478                             pad_ptr = p;
1479
1480                             if (dp->conversion == 'f' || dp->conversion == 'F')
1481                               {
1482                                 char *digits;
1483                                 size_t ndigits;
1484
1485                                 digits =
1486                                   scale10_round_decimal_long_double (arg, precision);
1487                                 if (digits == NULL)
1488                                   {
1489                                     END_LONG_DOUBLE_ROUNDING ();
1490                                     goto out_of_memory;
1491                                   }
1492                                 ndigits = strlen (digits);
1493
1494                                 if (ndigits > precision)
1495                                   do
1496                                     {
1497                                       --ndigits;
1498                                       *p++ = digits[ndigits];
1499                                     }
1500                                   while (ndigits > precision);
1501                                 else
1502                                   *p++ = '0';
1503                                 /* Here ndigits <= precision.  */
1504                                 if ((flags & FLAG_ALT) || precision > 0)
1505                                   {
1506                                     *p++ = decimal_point_char ();
1507                                     for (; precision > ndigits; precision--)
1508                                       *p++ = '0';
1509                                     while (ndigits > 0)
1510                                       {
1511                                         --ndigits;
1512                                         *p++ = digits[ndigits];
1513                                       }
1514                                   }
1515
1516                                 free (digits);
1517                               }
1518                             else if (dp->conversion == 'e' || dp->conversion == 'E')
1519                               {
1520                                 int exponent;
1521
1522                                 if (arg == 0.0L)
1523                                   {
1524                                     exponent = 0;
1525                                     *p++ = '0';
1526                                     if ((flags & FLAG_ALT) || precision > 0)
1527                                       {
1528                                         *p++ = decimal_point_char ();
1529                                         for (; precision > 0; precision--)
1530                                           *p++ = '0';
1531                                       }
1532                                   }
1533                                 else
1534                                   {
1535                                     /* arg > 0.0L.  */
1536                                     int adjusted;
1537                                     char *digits;
1538                                     size_t ndigits;
1539
1540                                     exponent = floorlog10l (arg);
1541                                     adjusted = 0;
1542                                     for (;;)
1543                                       {
1544                                         digits =
1545                                           scale10_round_decimal_long_double (arg,
1546                                                                              (int)precision - exponent);
1547                                         if (digits == NULL)
1548                                           {
1549                                             END_LONG_DOUBLE_ROUNDING ();
1550                                             goto out_of_memory;
1551                                           }
1552                                         ndigits = strlen (digits);
1553
1554                                         if (ndigits == precision + 1)
1555                                           break;
1556                                         if (ndigits < precision
1557                                             || ndigits > precision + 2)
1558                                           /* The exponent was not guessed
1559                                              precisely enough.  */
1560                                           abort ();
1561                                         if (adjusted)
1562                                           /* None of two values of exponent is
1563                                              the right one.  Prevent an endless
1564                                              loop.  */
1565                                           abort ();
1566                                         free (digits);
1567                                         if (ndigits == precision)
1568                                           exponent -= 1;
1569                                         else
1570                                           exponent += 1;
1571                                         adjusted = 1;
1572                                       }
1573
1574                                     /* Here ndigits = precision+1.  */
1575                                     *p++ = digits[--ndigits];
1576                                     if ((flags & FLAG_ALT) || precision > 0)
1577                                       {
1578                                         *p++ = decimal_point_char ();
1579                                         while (ndigits > 0)
1580                                           {
1581                                             --ndigits;
1582                                             *p++ = digits[ndigits];
1583                                           }
1584                                       }
1585
1586                                     free (digits);
1587                                   }
1588
1589                                 *p++ = dp->conversion; /* 'e' or 'E' */
1590 #  if WIDE_CHAR_VERSION
1591                                 {
1592                                   static const wchar_t decimal_format[] =
1593                                     { '%', '+', '.', '2', 'd', '\0' };
1594                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
1595                                 }
1596 #  else
1597                                 sprintf (p, "%+.2d", exponent);
1598 #  endif
1599                                 while (*p != '\0')
1600                                   p++;
1601                               }
1602                             else if (dp->conversion == 'g' || dp->conversion == 'G')
1603                               {
1604                                 if (precision == 0)
1605                                   precision = 1;
1606                                 /* precision >= 1.  */
1607
1608                                 if (arg == 0.0L)
1609                                   /* The exponent is 0, >= -4, < precision.
1610                                      Use fixed-point notation.  */
1611                                   {
1612                                     size_t ndigits = precision;
1613                                     /* Number of trailing zeroes that have to be
1614                                        dropped.  */
1615                                     size_t nzeroes =
1616                                       (flags & FLAG_ALT ? 0 : precision - 1);
1617
1618                                     --ndigits;
1619                                     *p++ = '0';
1620                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
1621                                       {
1622                                         *p++ = decimal_point_char ();
1623                                         while (ndigits > nzeroes)
1624                                           {
1625                                             --ndigits;
1626                                             *p++ = '0';
1627                                           }
1628                                       }
1629                                   }
1630                                 else
1631                                   {
1632                                     /* arg > 0.0L.  */
1633                                     int exponent;
1634                                     int adjusted;
1635                                     char *digits;
1636                                     size_t ndigits;
1637                                     size_t nzeroes;
1638
1639                                     exponent = floorlog10l (arg);
1640                                     adjusted = 0;
1641                                     for (;;)
1642                                       {
1643                                         digits =
1644                                           scale10_round_decimal_long_double (arg,
1645                                                                              (int)(precision - 1) - exponent);
1646                                         if (digits == NULL)
1647                                           {
1648                                             END_LONG_DOUBLE_ROUNDING ();
1649                                             goto out_of_memory;
1650                                           }
1651                                         ndigits = strlen (digits);
1652
1653                                         if (ndigits == precision)
1654                                           break;
1655                                         if (ndigits < precision - 1
1656                                             || ndigits > precision + 1)
1657                                           /* The exponent was not guessed
1658                                              precisely enough.  */
1659                                           abort ();
1660                                         if (adjusted)
1661                                           /* None of two values of exponent is
1662                                              the right one.  Prevent an endless
1663                                              loop.  */
1664                                           abort ();
1665                                         free (digits);
1666                                         if (ndigits < precision)
1667                                           exponent -= 1;
1668                                         else
1669                                           exponent += 1;
1670                                         adjusted = 1;
1671                                       }
1672                                     /* Here ndigits = precision.  */
1673
1674                                     /* Determine the number of trailing zeroes
1675                                        that have to be dropped.  */
1676                                     nzeroes = 0;
1677                                     if ((flags & FLAG_ALT) == 0)
1678                                       while (nzeroes < ndigits
1679                                              && digits[nzeroes] == '0')
1680                                         nzeroes++;
1681
1682                                     /* The exponent is now determined.  */
1683                                     if (exponent >= -4
1684                                         && exponent < (long)precision)
1685                                       {
1686                                         /* Fixed-point notation:
1687                                            max(exponent,0)+1 digits, then the
1688                                            decimal point, then the remaining
1689                                            digits without trailing zeroes.  */
1690                                         if (exponent >= 0)
1691                                           {
1692                                             size_t count = exponent + 1;
1693                                             /* Note: count <= precision = ndigits.  */
1694                                             for (; count > 0; count--)
1695                                               *p++ = digits[--ndigits];
1696                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
1697                                               {
1698                                                 *p++ = decimal_point_char ();
1699                                                 while (ndigits > nzeroes)
1700                                                   {
1701                                                     --ndigits;
1702                                                     *p++ = digits[ndigits];
1703                                                   }
1704                                               }
1705                                           }
1706                                         else
1707                                           {
1708                                             size_t count = -exponent - 1;
1709                                             *p++ = '0';
1710                                             *p++ = decimal_point_char ();
1711                                             for (; count > 0; count--)
1712                                               *p++ = '0';
1713                                             while (ndigits > nzeroes)
1714                                               {
1715                                                 --ndigits;
1716                                                 *p++ = digits[ndigits];
1717                                               }
1718                                           }
1719                                       }
1720                                     else
1721                                       {
1722                                         /* Exponential notation.  */
1723                                         *p++ = digits[--ndigits];
1724                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
1725                                           {
1726                                             *p++ = decimal_point_char ();
1727                                             while (ndigits > nzeroes)
1728                                               {
1729                                                 --ndigits;
1730                                                 *p++ = digits[ndigits];
1731                                               }
1732                                           }
1733                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
1734 #  if WIDE_CHAR_VERSION
1735                                         {
1736                                           static const wchar_t decimal_format[] =
1737                                             { '%', '+', '.', '2', 'd', '\0' };
1738                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
1739                                         }
1740 #  else
1741                                         sprintf (p, "%+.2d", exponent);
1742 #  endif
1743                                         while (*p != '\0')
1744                                           p++;
1745                                       }
1746
1747                                     free (digits);
1748                                   }
1749                               }
1750                             else
1751                               abort ();
1752                           }
1753
1754                         END_LONG_DOUBLE_ROUNDING ();
1755                       }
1756                   }
1757 #  if NEED_PRINTF_INFINITE
1758                 else
1759 #  endif
1760 # endif
1761 # if NEED_PRINTF_INFINITE
1762                   {
1763                     /* Simpler than above: handle only NaN, Infinity, zero.  */
1764                     double arg = a.arg[dp->arg_index].a.a_double;
1765
1766                     if (isnan (arg))
1767                       {
1768                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1769                           {
1770                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
1771                           }
1772                         else
1773                           {
1774                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
1775                           }
1776                       }
1777                     else
1778                       {
1779                         int sign = 0;
1780
1781                         if (signbit (arg)) /* arg < 0.0L or negative zero */
1782                           {
1783                             sign = -1;
1784                             arg = -arg;
1785                           }
1786
1787                         if (sign < 0)
1788                           *p++ = '-';
1789                         else if (flags & FLAG_SHOWSIGN)
1790                           *p++ = '+';
1791                         else if (flags & FLAG_SPACE)
1792                           *p++ = ' ';
1793
1794                         if (arg > 0.0 && arg + arg == arg)
1795                           {
1796                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
1797                               {
1798                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
1799                               }
1800                             else
1801                               {
1802                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
1803                               }
1804                           }
1805                         else
1806                           {
1807                             if (!(arg == 0.0))
1808                               abort ();
1809
1810                             pad_ptr = p;
1811
1812                             if (dp->conversion == 'f' || dp->conversion == 'F')
1813                               {
1814                                 *p++ = '0';
1815                                 if ((flags & FLAG_ALT) || precision > 0)
1816                                   {
1817                                     *p++ = decimal_point_char ();
1818                                     for (; precision > 0; precision--)
1819                                       *p++ = '0';
1820                                   }
1821                               }
1822                             else if (dp->conversion == 'e' || dp->conversion == 'E')
1823                               {
1824                                 *p++ = '0';
1825                                 if ((flags & FLAG_ALT) || precision > 0)
1826                                   {
1827                                     *p++ = decimal_point_char ();
1828                                     for (; precision > 0; precision--)
1829                                       *p++ = '0';
1830                                   }
1831                                 *p++ = dp->conversion; /* 'e' or 'E' */
1832                                 *p++ = '+';
1833                                 /* Produce the same number of exponent digits as
1834                                    the native printf implementation.  */
1835 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
1836                                 *p++ = '0';
1837 # endif
1838                                 *p++ = '0';
1839                                 *p++ = '0';
1840                               }
1841                             else if (dp->conversion == 'g' || dp->conversion == 'G')
1842                               {
1843                                 *p++ = '0';
1844                                 if (flags & FLAG_ALT)
1845                                   {
1846                                     size_t ndigits =
1847                                       (precision > 0 ? precision - 1 : 0);
1848                                     *p++ = decimal_point_char ();
1849                                     for (; ndigits > 0; --ndigits)
1850                                       *p++ = '0';
1851                                   }
1852                               }
1853                             else
1854                               abort ();
1855                           }
1856                       }
1857                   }
1858 # endif
1859
1860                 /* The generated string now extends from tmp to p, with the
1861                    zero padding insertion point being at pad_ptr.  */
1862                 if (has_width && p - tmp < width)
1863                   {
1864                     size_t pad = width - (p - tmp);
1865                     CHAR_T *end = p + pad;
1866
1867                     if (flags & FLAG_LEFT)
1868                       {
1869                         /* Pad with spaces on the right.  */
1870                         for (; pad > 0; pad--)
1871                           *p++ = ' ';
1872                       }
1873                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
1874                       {
1875                         /* Pad with zeroes.  */
1876                         CHAR_T *q = end;
1877
1878                         while (p > pad_ptr)
1879                           *--q = *--p;
1880                         for (; pad > 0; pad--)
1881                           *p++ = '0';
1882                       }
1883                     else
1884                       {
1885                         /* Pad with spaces on the left.  */
1886                         CHAR_T *q = end;
1887
1888                         while (p > tmp)
1889                           *--q = *--p;
1890                         for (; pad > 0; pad--)
1891                           *p++ = ' ';
1892                       }
1893
1894                     p = end;
1895                   }
1896
1897                 {
1898                   size_t count = p - tmp;
1899
1900                   if (count >= tmp_length)
1901                     /* tmp_length was incorrectly calculated - fix the
1902                        code above!  */
1903                     abort ();
1904
1905                   /* Make room for the result.  */
1906                   if (count >= allocated - length)
1907                     {
1908                       size_t n = xsum (length, count);
1909
1910                       ENSURE_ALLOCATION (n);
1911                     }
1912
1913                   /* Append the result.  */
1914                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
1915                   if (tmp != tmpbuf)
1916                     free (tmp);
1917                   length += count;
1918                 }
1919               }
1920 #endif
1921 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
1922             else if (dp->conversion == 'a' || dp->conversion == 'A')
1923               {
1924                 arg_type type = a.arg[dp->arg_index].type;
1925                 int flags = dp->flags;
1926                 int has_width;
1927                 size_t width;
1928                 int has_precision;
1929                 size_t precision;
1930                 size_t tmp_length;
1931                 CHAR_T tmpbuf[700];
1932                 CHAR_T *tmp;
1933                 CHAR_T *pad_ptr;
1934                 CHAR_T *p;
1935
1936                 has_width = 0;
1937                 width = 0;
1938                 if (dp->width_start != dp->width_end)
1939                   {
1940                     if (dp->width_arg_index != ARG_NONE)
1941                       {
1942                         int arg;
1943
1944                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1945                           abort ();
1946                         arg = a.arg[dp->width_arg_index].a.a_int;
1947                         if (arg < 0)
1948                           {
1949                             /* "A negative field width is taken as a '-' flag
1950                                 followed by a positive field width."  */
1951                             flags |= FLAG_LEFT;
1952                             width = (unsigned int) (-arg);
1953                           }
1954                         else
1955                           width = arg;
1956                       }
1957                     else
1958                       {
1959                         const CHAR_T *digitp = dp->width_start;
1960
1961                         do
1962                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1963                         while (digitp != dp->width_end);
1964                       }
1965                     has_width = 1;
1966                   }
1967
1968                 has_precision = 0;
1969                 precision = 0;
1970                 if (dp->precision_start != dp->precision_end)
1971                   {
1972                     if (dp->precision_arg_index != ARG_NONE)
1973                       {
1974                         int arg;
1975
1976                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1977                           abort ();
1978                         arg = a.arg[dp->precision_arg_index].a.a_int;
1979                         /* "A negative precision is taken as if the precision
1980                             were omitted."  */
1981                         if (arg >= 0)
1982                           {
1983                             precision = arg;
1984                             has_precision = 1;
1985                           }
1986                       }
1987                     else
1988                       {
1989                         const CHAR_T *digitp = dp->precision_start + 1;
1990
1991                         precision = 0;
1992                         while (digitp != dp->precision_end)
1993                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1994                         has_precision = 1;
1995                       }
1996                   }
1997
1998                 /* Allocate a temporary buffer of sufficient size.  */
1999                 if (type == TYPE_LONGDOUBLE)
2000                   tmp_length =
2001                     (unsigned int) ((LDBL_DIG + 1)
2002                                     * 0.831 /* decimal -> hexadecimal */
2003                                    )
2004                     + 1; /* turn floor into ceil */
2005                 else
2006                   tmp_length =
2007                     (unsigned int) ((DBL_DIG + 1)
2008                                     * 0.831 /* decimal -> hexadecimal */
2009                                    )
2010                     + 1; /* turn floor into ceil */
2011                 if (tmp_length < precision)
2012                   tmp_length = precision;
2013                 /* Account for sign, decimal point etc. */
2014                 tmp_length = xsum (tmp_length, 12);
2015
2016                 if (tmp_length < width)
2017                   tmp_length = width;
2018
2019                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2020
2021                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2022                   tmp = tmpbuf;
2023                 else
2024                   {
2025                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2026
2027                     if (size_overflow_p (tmp_memsize))
2028                       /* Overflow, would lead to out of memory.  */
2029                       goto out_of_memory;
2030                     tmp = (CHAR_T *) malloc (tmp_memsize);
2031                     if (tmp == NULL)
2032                       /* Out of memory.  */
2033                       goto out_of_memory;
2034                   }
2035
2036                 pad_ptr = NULL;
2037                 p = tmp;
2038                 if (type == TYPE_LONGDOUBLE)
2039                   {
2040                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2041
2042                     if (isnanl (arg))
2043                       {
2044                         if (dp->conversion == 'A')
2045                           {
2046                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2047                           }
2048                         else
2049                           {
2050                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2051                           }
2052                       }
2053                     else
2054                       {
2055                         int sign = 0;
2056                         DECL_LONG_DOUBLE_ROUNDING
2057
2058                         BEGIN_LONG_DOUBLE_ROUNDING ();
2059
2060                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2061                           {
2062                             sign = -1;
2063                             arg = -arg;
2064                           }
2065
2066                         if (sign < 0)
2067                           *p++ = '-';
2068                         else if (flags & FLAG_SHOWSIGN)
2069                           *p++ = '+';
2070                         else if (flags & FLAG_SPACE)
2071                           *p++ = ' ';
2072
2073                         if (arg > 0.0L && arg + arg == arg)
2074                           {
2075                             if (dp->conversion == 'A')
2076                               {
2077                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2078                               }
2079                             else
2080                               {
2081                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2082                               }
2083                           }
2084                         else
2085                           {
2086                             int exponent;
2087                             long double mantissa;
2088
2089                             if (arg > 0.0L)
2090                               mantissa = printf_frexpl (arg, &exponent);
2091                             else
2092                               {
2093                                 exponent = 0;
2094                                 mantissa = 0.0L;
2095                               }
2096
2097                             if (has_precision
2098                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2099                               {
2100                                 /* Round the mantissa.  */
2101                                 long double tail = mantissa;
2102                                 size_t q;
2103
2104                                 for (q = precision; ; q--)
2105                                   {
2106                                     int digit = (int) tail;
2107                                     tail -= digit;
2108                                     if (q == 0)
2109                                       {
2110                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2111                                           tail = 1 - tail;
2112                                         else
2113                                           tail = - tail;
2114                                         break;
2115                                       }
2116                                     tail *= 16.0L;
2117                                   }
2118                                 if (tail != 0.0L)
2119                                   for (q = precision; q > 0; q--)
2120                                     tail *= 0.0625L;
2121                                 mantissa += tail;
2122                               }
2123
2124                             *p++ = '0';
2125                             *p++ = dp->conversion - 'A' + 'X';
2126                             pad_ptr = p;
2127                             {
2128                               int digit;
2129
2130                               digit = (int) mantissa;
2131                               mantissa -= digit;
2132                               *p++ = '0' + digit;
2133                               if ((flags & FLAG_ALT)
2134                                   || mantissa > 0.0L || precision > 0)
2135                                 {
2136                                   *p++ = decimal_point_char ();
2137                                   /* This loop terminates because we assume
2138                                      that FLT_RADIX is a power of 2.  */
2139                                   while (mantissa > 0.0L)
2140                                     {
2141                                       mantissa *= 16.0L;
2142                                       digit = (int) mantissa;
2143                                       mantissa -= digit;
2144                                       *p++ = digit
2145                                              + (digit < 10
2146                                                 ? '0'
2147                                                 : dp->conversion - 10);
2148                                       if (precision > 0)
2149                                         precision--;
2150                                     }
2151                                   while (precision > 0)
2152                                     {
2153                                       *p++ = '0';
2154                                       precision--;
2155                                     }
2156                                 }
2157                               }
2158                               *p++ = dp->conversion - 'A' + 'P';
2159 # if WIDE_CHAR_VERSION
2160                               {
2161                                 static const wchar_t decimal_format[] =
2162                                   { '%', '+', 'd', '\0' };
2163                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2164                               }
2165 # else
2166                               sprintf (p, "%+d", exponent);
2167 # endif
2168                               while (*p != '\0')
2169                                 p++;
2170                           }
2171
2172                         END_LONG_DOUBLE_ROUNDING ();
2173                       }
2174                   }
2175                 else
2176                   {
2177                     double arg = a.arg[dp->arg_index].a.a_double;
2178
2179                     if (isnan (arg))
2180                       {
2181                         if (dp->conversion == 'A')
2182                           {
2183                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2184                           }
2185                         else
2186                           {
2187                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2188                           }
2189                       }
2190                     else
2191                       {
2192                         int sign = 0;
2193
2194                         if (signbit (arg)) /* arg < 0.0 or negative zero */
2195                           {
2196                             sign = -1;
2197                             arg = -arg;
2198                           }
2199
2200                         if (sign < 0)
2201                           *p++ = '-';
2202                         else if (flags & FLAG_SHOWSIGN)
2203                           *p++ = '+';
2204                         else if (flags & FLAG_SPACE)
2205                           *p++ = ' ';
2206
2207                         if (arg > 0.0 && arg + arg == arg)
2208                           {
2209                             if (dp->conversion == 'A')
2210                               {
2211                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2212                               }
2213                             else
2214                               {
2215                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2216                               }
2217                           }
2218                         else
2219                           {
2220                             int exponent;
2221                             double mantissa;
2222
2223                             if (arg > 0.0)
2224                               mantissa = printf_frexp (arg, &exponent);
2225                             else
2226                               {
2227                                 exponent = 0;
2228                                 mantissa = 0.0;
2229                               }
2230
2231                             if (has_precision
2232                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2233                               {
2234                                 /* Round the mantissa.  */
2235                                 double tail = mantissa;
2236                                 size_t q;
2237
2238                                 for (q = precision; ; q--)
2239                                   {
2240                                     int digit = (int) tail;
2241                                     tail -= digit;
2242                                     if (q == 0)
2243                                       {
2244                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2245                                           tail = 1 - tail;
2246                                         else
2247                                           tail = - tail;
2248                                         break;
2249                                       }
2250                                     tail *= 16.0;
2251                                   }
2252                                 if (tail != 0.0)
2253                                   for (q = precision; q > 0; q--)
2254                                     tail *= 0.0625;
2255                                 mantissa += tail;
2256                               }
2257
2258                             *p++ = '0';
2259                             *p++ = dp->conversion - 'A' + 'X';
2260                             pad_ptr = p;
2261                             {
2262                               int digit;
2263
2264                               digit = (int) mantissa;
2265                               mantissa -= digit;
2266                               *p++ = '0' + digit;
2267                               if ((flags & FLAG_ALT)
2268                                   || mantissa > 0.0 || precision > 0)
2269                                 {
2270                                   *p++ = decimal_point_char ();
2271                                   /* This loop terminates because we assume
2272                                      that FLT_RADIX is a power of 2.  */
2273                                   while (mantissa > 0.0)
2274                                     {
2275                                       mantissa *= 16.0;
2276                                       digit = (int) mantissa;
2277                                       mantissa -= digit;
2278                                       *p++ = digit
2279                                              + (digit < 10
2280                                                 ? '0'
2281                                                 : dp->conversion - 10);
2282                                       if (precision > 0)
2283                                         precision--;
2284                                     }
2285                                   while (precision > 0)
2286                                     {
2287                                       *p++ = '0';
2288                                       precision--;
2289                                     }
2290                                 }
2291                               }
2292                               *p++ = dp->conversion - 'A' + 'P';
2293 # if WIDE_CHAR_VERSION
2294                               {
2295                                 static const wchar_t decimal_format[] =
2296                                   { '%', '+', 'd', '\0' };
2297                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2298                               }
2299 # else
2300                               sprintf (p, "%+d", exponent);
2301 # endif
2302                               while (*p != '\0')
2303                                 p++;
2304                           }
2305                       }
2306                   }
2307                 /* The generated string now extends from tmp to p, with the
2308                    zero padding insertion point being at pad_ptr.  */
2309                 if (has_width && p - tmp < width)
2310                   {
2311                     size_t pad = width - (p - tmp);
2312                     CHAR_T *end = p + pad;
2313
2314                     if (flags & FLAG_LEFT)
2315                       {
2316                         /* Pad with spaces on the right.  */
2317                         for (; pad > 0; pad--)
2318                           *p++ = ' ';
2319                       }
2320                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2321                       {
2322                         /* Pad with zeroes.  */
2323                         CHAR_T *q = end;
2324
2325                         while (p > pad_ptr)
2326                           *--q = *--p;
2327                         for (; pad > 0; pad--)
2328                           *p++ = '0';
2329                       }
2330                     else
2331                       {
2332                         /* Pad with spaces on the left.  */
2333                         CHAR_T *q = end;
2334
2335                         while (p > tmp)
2336                           *--q = *--p;
2337                         for (; pad > 0; pad--)
2338                           *p++ = ' ';
2339                       }
2340
2341                     p = end;
2342                   }
2343
2344                 {
2345                   size_t count = p - tmp;
2346
2347                   if (count >= tmp_length)
2348                     /* tmp_length was incorrectly calculated - fix the
2349                        code above!  */
2350                     abort ();
2351
2352                   /* Make room for the result.  */
2353                   if (count >= allocated - length)
2354                     {
2355                       size_t n = xsum (length, count);
2356
2357                       ENSURE_ALLOCATION (n);
2358                     }
2359
2360                   /* Append the result.  */
2361                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
2362                   if (tmp != tmpbuf)
2363                     free (tmp);
2364                   length += count;
2365                 }
2366               }
2367 #endif
2368             else
2369               {
2370                 arg_type type = a.arg[dp->arg_index].type;
2371                 int flags = dp->flags;
2372 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2373                 int has_width;
2374                 size_t width;
2375 #endif
2376 #if NEED_PRINTF_FLAG_ZERO
2377                 int pad_ourselves;
2378 #else
2379 #               define pad_ourselves 0
2380 #endif
2381                 CHAR_T *fbp;
2382                 unsigned int prefix_count;
2383                 int prefixes[2];
2384 #if !USE_SNPRINTF
2385                 size_t tmp_length;
2386                 CHAR_T tmpbuf[700];
2387                 CHAR_T *tmp;
2388 #endif
2389
2390 #if !USE_SNPRINTF || NEED_PRINTF_FLAG_ZERO
2391                 has_width = 0;
2392                 width = 0;
2393                 if (dp->width_start != dp->width_end)
2394                   {
2395                     if (dp->width_arg_index != ARG_NONE)
2396                       {
2397                         int arg;
2398
2399                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2400                           abort ();
2401                         arg = a.arg[dp->width_arg_index].a.a_int;
2402                         if (arg < 0)
2403                           {
2404                             /* "A negative field width is taken as a '-' flag
2405                                 followed by a positive field width."  */
2406                             flags |= FLAG_LEFT;
2407                             width = (unsigned int) (-arg);
2408                           }
2409                         else
2410                           width = arg;
2411                       }
2412                     else
2413                       {
2414                         const CHAR_T *digitp = dp->width_start;
2415
2416                         do
2417                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2418                         while (digitp != dp->width_end);
2419                       }
2420                     has_width = 1;
2421                   }
2422 #endif
2423
2424 #if !USE_SNPRINTF
2425                 /* Allocate a temporary buffer of sufficient size for calling
2426                    sprintf.  */
2427                 {
2428                   size_t precision;
2429
2430                   precision = 6;
2431                   if (dp->precision_start != dp->precision_end)
2432                     {
2433                       if (dp->precision_arg_index != ARG_NONE)
2434                         {
2435                           int arg;
2436
2437                           if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2438                             abort ();
2439                           arg = a.arg[dp->precision_arg_index].a.a_int;
2440                           precision = (arg < 0 ? 0 : arg);
2441                         }
2442                       else
2443                         {
2444                           const CHAR_T *digitp = dp->precision_start + 1;
2445
2446                           precision = 0;
2447                           while (digitp != dp->precision_end)
2448                             precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2449                         }
2450                     }
2451
2452                   switch (dp->conversion)
2453                     {
2454
2455                     case 'd': case 'i': case 'u':
2456 # if HAVE_LONG_LONG_INT
2457                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2458                         tmp_length =
2459                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2460                                           * 0.30103 /* binary -> decimal */
2461                                          )
2462                           + 1; /* turn floor into ceil */
2463                       else
2464 # endif
2465                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2466                         tmp_length =
2467                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2468                                           * 0.30103 /* binary -> decimal */
2469                                          )
2470                           + 1; /* turn floor into ceil */
2471                       else
2472                         tmp_length =
2473                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2474                                           * 0.30103 /* binary -> decimal */
2475                                          )
2476                           + 1; /* turn floor into ceil */
2477                       if (tmp_length < precision)
2478                         tmp_length = precision;
2479                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
2480                       tmp_length = xsum (tmp_length, tmp_length);
2481                       /* Add 1, to account for a leading sign.  */
2482                       tmp_length = xsum (tmp_length, 1);
2483                       break;
2484
2485                     case 'o':
2486 # if HAVE_LONG_LONG_INT
2487                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2488                         tmp_length =
2489                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2490                                           * 0.333334 /* binary -> octal */
2491                                          )
2492                           + 1; /* turn floor into ceil */
2493                       else
2494 # endif
2495                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2496                         tmp_length =
2497                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2498                                           * 0.333334 /* binary -> octal */
2499                                          )
2500                           + 1; /* turn floor into ceil */
2501                       else
2502                         tmp_length =
2503                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2504                                           * 0.333334 /* binary -> octal */
2505                                          )
2506                           + 1; /* turn floor into ceil */
2507                       if (tmp_length < precision)
2508                         tmp_length = precision;
2509                       /* Add 1, to account for a leading sign.  */
2510                       tmp_length = xsum (tmp_length, 1);
2511                       break;
2512
2513                     case 'x': case 'X':
2514 # if HAVE_LONG_LONG_INT
2515                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
2516                         tmp_length =
2517                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
2518                                           * 0.25 /* binary -> hexadecimal */
2519                                          )
2520                           + 1; /* turn floor into ceil */
2521                       else
2522 # endif
2523                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
2524                         tmp_length =
2525                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
2526                                           * 0.25 /* binary -> hexadecimal */
2527                                          )
2528                           + 1; /* turn floor into ceil */
2529                       else
2530                         tmp_length =
2531                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2532                                           * 0.25 /* binary -> hexadecimal */
2533                                          )
2534                           + 1; /* turn floor into ceil */
2535                       if (tmp_length < precision)
2536                         tmp_length = precision;
2537                       /* Add 2, to account for a leading sign or alternate form.  */
2538                       tmp_length = xsum (tmp_length, 2);
2539                       break;
2540
2541                     case 'f': case 'F':
2542                       if (type == TYPE_LONGDOUBLE)
2543                         tmp_length =
2544                           (unsigned int) (LDBL_MAX_EXP
2545                                           * 0.30103 /* binary -> decimal */
2546                                           * 2 /* estimate for FLAG_GROUP */
2547                                          )
2548                           + 1 /* turn floor into ceil */
2549                           + 10; /* sign, decimal point etc. */
2550                       else
2551                         tmp_length =
2552                           (unsigned int) (DBL_MAX_EXP
2553                                           * 0.30103 /* binary -> decimal */
2554                                           * 2 /* estimate for FLAG_GROUP */
2555                                          )
2556                           + 1 /* turn floor into ceil */
2557                           + 10; /* sign, decimal point etc. */
2558                       tmp_length = xsum (tmp_length, precision);
2559                       break;
2560
2561                     case 'e': case 'E': case 'g': case 'G':
2562                       tmp_length =
2563                         12; /* sign, decimal point, exponent etc. */
2564                       tmp_length = xsum (tmp_length, precision);
2565                       break;
2566
2567                     case 'a': case 'A':
2568                       if (type == TYPE_LONGDOUBLE)
2569                         tmp_length =
2570                           (unsigned int) (LDBL_DIG
2571                                           * 0.831 /* decimal -> hexadecimal */
2572                                          )
2573                           + 1; /* turn floor into ceil */
2574                       else
2575                         tmp_length =
2576                           (unsigned int) (DBL_DIG
2577                                           * 0.831 /* decimal -> hexadecimal */
2578                                          )
2579                           + 1; /* turn floor into ceil */
2580                       if (tmp_length < precision)
2581                         tmp_length = precision;
2582                       /* Account for sign, decimal point etc. */
2583                       tmp_length = xsum (tmp_length, 12);
2584                       break;
2585
2586                     case 'c':
2587 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2588                       if (type == TYPE_WIDE_CHAR)
2589                         tmp_length = MB_CUR_MAX;
2590                       else
2591 # endif
2592                         tmp_length = 1;
2593                       break;
2594
2595                     case 's':
2596 # if HAVE_WCHAR_T
2597                       if (type == TYPE_WIDE_STRING)
2598                         {
2599                           tmp_length =
2600                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
2601
2602 #  if !WIDE_CHAR_VERSION
2603                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
2604 #  endif
2605                         }
2606                       else
2607 # endif
2608                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
2609                       break;
2610
2611                     case 'p':
2612                       tmp_length =
2613                         (unsigned int) (sizeof (void *) * CHAR_BIT
2614                                         * 0.25 /* binary -> hexadecimal */
2615                                        )
2616                           + 1 /* turn floor into ceil */
2617                           + 2; /* account for leading 0x */
2618                       break;
2619
2620                     default:
2621                       abort ();
2622                     }
2623
2624                   if (tmp_length < width)
2625                     tmp_length = width;
2626
2627                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2628                 }
2629
2630                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
2631                   tmp = tmpbuf;
2632                 else
2633                   {
2634                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
2635
2636                     if (size_overflow_p (tmp_memsize))
2637                       /* Overflow, would lead to out of memory.  */
2638                       goto out_of_memory;
2639                     tmp = (CHAR_T *) malloc (tmp_memsize);
2640                     if (tmp == NULL)
2641                       /* Out of memory.  */
2642                       goto out_of_memory;
2643                   }
2644 #endif
2645
2646                 /* Decide whether to perform the padding ourselves.  */
2647 #if NEED_PRINTF_FLAG_ZERO
2648                 switch (dp->conversion)
2649                   {
2650                   case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
2651                   case 'a': case 'A':
2652                     pad_ourselves = 1;
2653                     break;
2654                   default:
2655                     pad_ourselves = 0;
2656                     break;
2657                   }
2658 #endif
2659
2660                 /* Construct the format string for calling snprintf or
2661                    sprintf.  */
2662                 fbp = buf;
2663                 *fbp++ = '%';
2664 #if NEED_PRINTF_FLAG_GROUPING
2665                 /* The underlying implementation doesn't support the ' flag.
2666                    Produce no grouping characters in this case; this is
2667                    acceptable because the grouping is locale dependent.  */
2668 #else
2669                 if (flags & FLAG_GROUP)
2670                   *fbp++ = '\'';
2671 #endif
2672                 if (flags & FLAG_LEFT)
2673                   *fbp++ = '-';
2674                 if (flags & FLAG_SHOWSIGN)
2675                   *fbp++ = '+';
2676                 if (flags & FLAG_SPACE)
2677                   *fbp++ = ' ';
2678                 if (flags & FLAG_ALT)
2679                   *fbp++ = '#';
2680                 if (!pad_ourselves)
2681                   {
2682                     if (flags & FLAG_ZERO)
2683                       *fbp++ = '0';
2684                     if (dp->width_start != dp->width_end)
2685                       {
2686                         size_t n = dp->width_end - dp->width_start;
2687                         memcpy (fbp, dp->width_start, n * sizeof (CHAR_T));
2688                         fbp += n;
2689                       }
2690                   }
2691                 if (dp->precision_start != dp->precision_end)
2692                   {
2693                     size_t n = dp->precision_end - dp->precision_start;
2694                     memcpy (fbp, dp->precision_start, n * sizeof (CHAR_T));
2695                     fbp += n;
2696                   }
2697
2698                 switch (type)
2699                   {
2700 #if HAVE_LONG_LONG_INT
2701                   case TYPE_LONGLONGINT:
2702                   case TYPE_ULONGLONGINT:
2703 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
2704                     *fbp++ = 'I';
2705                     *fbp++ = '6';
2706                     *fbp++ = '4';
2707                     break;
2708 # else
2709                     *fbp++ = 'l';
2710                     /*FALLTHROUGH*/
2711 # endif
2712 #endif
2713                   case TYPE_LONGINT:
2714                   case TYPE_ULONGINT:
2715 #if HAVE_WINT_T
2716                   case TYPE_WIDE_CHAR:
2717 #endif
2718 #if HAVE_WCHAR_T
2719                   case TYPE_WIDE_STRING:
2720 #endif
2721                     *fbp++ = 'l';
2722                     break;
2723                   case TYPE_LONGDOUBLE:
2724                     *fbp++ = 'L';
2725                     break;
2726                   default:
2727                     break;
2728                   }
2729 #if NEED_PRINTF_DIRECTIVE_F
2730                 if (dp->conversion == 'F')
2731                   *fbp = 'f';
2732                 else
2733 #endif
2734                   *fbp = dp->conversion;
2735 #if USE_SNPRINTF
2736                 fbp[1] = '%';
2737                 fbp[2] = 'n';
2738                 fbp[3] = '\0';
2739 #else
2740                 fbp[1] = '\0';
2741 #endif
2742
2743                 /* Construct the arguments for calling snprintf or sprintf.  */
2744                 prefix_count = 0;
2745                 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
2746                   {
2747                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2748                       abort ();
2749                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
2750                   }
2751                 if (dp->precision_arg_index != ARG_NONE)
2752                   {
2753                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2754                       abort ();
2755                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
2756                   }
2757
2758 #if USE_SNPRINTF
2759                 /* Prepare checking whether snprintf returns the count
2760                    via %n.  */
2761                 ENSURE_ALLOCATION (xsum (length, 1));
2762                 result[length] = '\0';
2763 #endif
2764
2765                 for (;;)
2766                   {
2767                     size_t maxlen;
2768                     int count;
2769                     int retcount;
2770
2771                     maxlen = allocated - length;
2772                     count = -1;
2773                     retcount = 0;
2774
2775 #if USE_SNPRINTF
2776                     /* SNPRINTF can fail if maxlen > INT_MAX.  */
2777                     if (maxlen > INT_MAX)
2778                       goto overflow;
2779 # define SNPRINTF_BUF(arg) \
2780                     switch (prefix_count)                                   \
2781                       {                                                     \
2782                       case 0:                                               \
2783                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2784                                              arg, &count);                  \
2785                         break;                                              \
2786                       case 1:                                               \
2787                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2788                                              prefixes[0], arg, &count);     \
2789                         break;                                              \
2790                       case 2:                                               \
2791                         retcount = SNPRINTF (result + length, maxlen, buf,  \
2792                                              prefixes[0], prefixes[1], arg, \
2793                                              &count);                       \
2794                         break;                                              \
2795                       default:                                              \
2796                         abort ();                                           \
2797                       }
2798 #else
2799 # define SNPRINTF_BUF(arg) \
2800                     switch (prefix_count)                                   \
2801                       {                                                     \
2802                       case 0:                                               \
2803                         count = sprintf (tmp, buf, arg);                    \
2804                         break;                                              \
2805                       case 1:                                               \
2806                         count = sprintf (tmp, buf, prefixes[0], arg);       \
2807                         break;                                              \
2808                       case 2:                                               \
2809                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
2810                                          arg);                              \
2811                         break;                                              \
2812                       default:                                              \
2813                         abort ();                                           \
2814                       }
2815 #endif
2816
2817                     switch (type)
2818                       {
2819                       case TYPE_SCHAR:
2820                         {
2821                           int arg = a.arg[dp->arg_index].a.a_schar;
2822                           SNPRINTF_BUF (arg);
2823                         }
2824                         break;
2825                       case TYPE_UCHAR:
2826                         {
2827                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
2828                           SNPRINTF_BUF (arg);
2829                         }
2830                         break;
2831                       case TYPE_SHORT:
2832                         {
2833                           int arg = a.arg[dp->arg_index].a.a_short;
2834                           SNPRINTF_BUF (arg);
2835                         }
2836                         break;
2837                       case TYPE_USHORT:
2838                         {
2839                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
2840                           SNPRINTF_BUF (arg);
2841                         }
2842                         break;
2843                       case TYPE_INT:
2844                         {
2845                           int arg = a.arg[dp->arg_index].a.a_int;
2846                           SNPRINTF_BUF (arg);
2847                         }
2848                         break;
2849                       case TYPE_UINT:
2850                         {
2851                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
2852                           SNPRINTF_BUF (arg);
2853                         }
2854                         break;
2855                       case TYPE_LONGINT:
2856                         {
2857                           long int arg = a.arg[dp->arg_index].a.a_longint;
2858                           SNPRINTF_BUF (arg);
2859                         }
2860                         break;
2861                       case TYPE_ULONGINT:
2862                         {
2863                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
2864                           SNPRINTF_BUF (arg);
2865                         }
2866                         break;
2867 #if HAVE_LONG_LONG_INT
2868                       case TYPE_LONGLONGINT:
2869                         {
2870                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
2871                           SNPRINTF_BUF (arg);
2872                         }
2873                         break;
2874                       case TYPE_ULONGLONGINT:
2875                         {
2876                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
2877                           SNPRINTF_BUF (arg);
2878                         }
2879                         break;
2880 #endif
2881                       case TYPE_DOUBLE:
2882                         {
2883                           double arg = a.arg[dp->arg_index].a.a_double;
2884                           SNPRINTF_BUF (arg);
2885                         }
2886                         break;
2887                       case TYPE_LONGDOUBLE:
2888                         {
2889                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
2890                           SNPRINTF_BUF (arg);
2891                         }
2892                         break;
2893                       case TYPE_CHAR:
2894                         {
2895                           int arg = a.arg[dp->arg_index].a.a_char;
2896                           SNPRINTF_BUF (arg);
2897                         }
2898                         break;
2899 #if HAVE_WINT_T
2900                       case TYPE_WIDE_CHAR:
2901                         {
2902                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
2903                           SNPRINTF_BUF (arg);
2904                         }
2905                         break;
2906 #endif
2907                       case TYPE_STRING:
2908                         {
2909                           const char *arg = a.arg[dp->arg_index].a.a_string;
2910                           SNPRINTF_BUF (arg);
2911                         }
2912                         break;
2913 #if HAVE_WCHAR_T
2914                       case TYPE_WIDE_STRING:
2915                         {
2916                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2917                           SNPRINTF_BUF (arg);
2918                         }
2919                         break;
2920 #endif
2921                       case TYPE_POINTER:
2922                         {
2923                           void *arg = a.arg[dp->arg_index].a.a_pointer;
2924                           SNPRINTF_BUF (arg);
2925                         }
2926                         break;
2927                       default:
2928                         abort ();
2929                       }
2930
2931 #if USE_SNPRINTF
2932                     /* Portability: Not all implementations of snprintf()
2933                        are ISO C 99 compliant.  Determine the number of
2934                        bytes that snprintf() has produced or would have
2935                        produced.  */
2936                     if (count >= 0)
2937                       {
2938                         /* Verify that snprintf() has NUL-terminated its
2939                            result.  */
2940                         if (count < maxlen && result[length + count] != '\0')
2941                           abort ();
2942                         /* Portability hack.  */
2943                         if (retcount > count)
2944                           count = retcount;
2945                       }
2946                     else
2947                       {
2948                         /* snprintf() doesn't understand the '%n'
2949                            directive.  */
2950                         if (fbp[1] != '\0')
2951                           {
2952                             /* Don't use the '%n' directive; instead, look
2953                                at the snprintf() return value.  */
2954                             fbp[1] = '\0';
2955                             continue;
2956                           }
2957                         else
2958                           {
2959                             /* Look at the snprintf() return value.  */
2960                             if (retcount < 0)
2961                               {
2962                                 /* HP-UX 10.20 snprintf() is doubly deficient:
2963                                    It doesn't understand the '%n' directive,
2964                                    *and* it returns -1 (rather than the length
2965                                    that would have been required) when the
2966                                    buffer is too small.  */
2967                                 size_t bigger_need =
2968                                   xsum (xtimes (allocated, 2), 12);
2969                                 ENSURE_ALLOCATION (bigger_need);
2970                                 continue;
2971                               }
2972                             else
2973                               count = retcount;
2974                           }
2975                       }
2976 #endif
2977
2978                     /* Attempt to handle failure.  */
2979                     if (count < 0)
2980                       {
2981                         if (!(result == resultbuf || result == NULL))
2982                           free (result);
2983                         if (buf_malloced != NULL)
2984                           free (buf_malloced);
2985                         CLEANUP ();
2986                         errno = EINVAL;
2987                         return NULL;
2988                       }
2989
2990                     /* Make room for the result.  */
2991                     if (count >= maxlen)
2992                       {
2993                         /* Need at least count bytes.  But allocate
2994                            proportionally, to avoid looping eternally if
2995                            snprintf() reports a too small count.  */
2996                         size_t n =
2997                           xmax (xsum (length, count), xtimes (allocated, 2));
2998
2999                         ENSURE_ALLOCATION (n);
3000 #if USE_SNPRINTF
3001                         continue;
3002 #else
3003                         maxlen = allocated - length;
3004 #endif
3005                       }
3006
3007                     /* Perform padding.  */
3008 #if NEED_PRINTF_FLAG_ZERO
3009                     if (pad_ourselves && has_width && count < width)
3010                       {
3011 # if USE_SNPRINTF
3012                         /* Make room for the result.  */
3013                         if (width >= maxlen)
3014                           {
3015                             /* Need at least width bytes.  But allocate
3016                                proportionally, to avoid looping eternally if
3017                                snprintf() reports a too small count.  */
3018                             size_t n =
3019                               xmax (xsum (length + 1, width),
3020                                     xtimes (allocated, 2));
3021
3022                             length += count;
3023                             ENSURE_ALLOCATION (n);
3024                             length -= count;
3025                             maxlen = allocated - length; /* > width */
3026                           }
3027                         /* Here width < maxlen.  */
3028 # endif
3029                         {
3030 # if USE_SNPRINTF
3031                           CHAR_T * const rp = result + length;
3032 # else
3033                           CHAR_T * const rp = tmp;
3034 # endif
3035                           CHAR_T *p = rp + count;
3036                           size_t pad = width - count;
3037                           CHAR_T *end = p + pad;
3038                           CHAR_T *pad_ptr = (*rp == '-' ? rp + 1 : rp);
3039                           /* No zero-padding of "inf" and "nan".  */
3040                           if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
3041                               || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
3042                             pad_ptr = NULL;
3043                           /* The generated string now extends from rp to p,
3044                              with the zero padding insertion point being at
3045                              pad_ptr.  */
3046
3047                           if (flags & FLAG_LEFT)
3048                             {
3049                               /* Pad with spaces on the right.  */
3050                               for (; pad > 0; pad--)
3051                                 *p++ = ' ';
3052                             }
3053                           else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3054                             {
3055                               /* Pad with zeroes.  */
3056                               CHAR_T *q = end;
3057
3058                               while (p > pad_ptr)
3059                                 *--q = *--p;
3060                               for (; pad > 0; pad--)
3061                                 *p++ = '0';
3062                             }
3063                           else
3064                             {
3065                               /* Pad with spaces on the left.  */
3066                               CHAR_T *q = end;
3067
3068                               while (p > rp)
3069                                 *--q = *--p;
3070                               for (; pad > 0; pad--)
3071                                 *p++ = ' ';
3072                             }
3073
3074                           count = width; /* = count + pad = end - rp */
3075                         }
3076                       }
3077 #endif
3078
3079 #if !USE_SNPRINTF
3080                     if (count >= tmp_length)
3081                       /* tmp_length was incorrectly calculated - fix the
3082                          code above!  */
3083                       abort ();
3084 #endif
3085
3086                     /* Here still count < maxlen.  */
3087
3088 #if USE_SNPRINTF
3089                     /* The snprintf() result did fit.  */
3090 #else
3091                     /* Append the sprintf() result.  */
3092                     memcpy (result + length, tmp, count * sizeof (CHAR_T));
3093                     if (tmp != tmpbuf)
3094                       free (tmp);
3095 #endif
3096
3097 #if NEED_PRINTF_DIRECTIVE_F
3098                     if (dp->conversion == 'F')
3099                       {
3100                         /* Convert the %f result to upper case for %F.  */
3101                         CHAR_T *rp = result + length;
3102                         size_t rc;
3103                         for (rc = count; rc > 0; rc--, rp++)
3104                           if (*rp >= 'a' && *rp <= 'z')
3105                             *rp = *rp - 'a' + 'A';
3106                       }
3107 #endif
3108
3109                     length += count;
3110                     break;
3111                   }
3112               }
3113           }
3114       }
3115
3116     /* Add the final NUL.  */
3117     ENSURE_ALLOCATION (xsum (length, 1));
3118     result[length] = '\0';
3119
3120     if (result != resultbuf && length + 1 < allocated)
3121       {
3122         /* Shrink the allocated memory if possible.  */
3123         CHAR_T *memory;
3124
3125         memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
3126         if (memory != NULL)
3127           result = memory;
3128       }
3129
3130     if (buf_malloced != NULL)
3131       free (buf_malloced);
3132     CLEANUP ();
3133     *lengthp = length;
3134     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
3135        says that snprintf() fails with errno = EOVERFLOW in this case, but
3136        that's only because snprintf() returns an 'int'.  This function does
3137        not have this limitation.  */
3138     return result;
3139
3140   overflow:
3141     if (!(result == resultbuf || result == NULL))
3142       free (result);
3143     if (buf_malloced != NULL)
3144       free (buf_malloced);
3145     CLEANUP ();
3146     errno = EOVERFLOW;
3147     return NULL;
3148
3149   out_of_memory:
3150     if (!(result == resultbuf || result == NULL))
3151       free (result);
3152     if (buf_malloced != NULL)
3153       free (buf_malloced);
3154   out_of_memory_1:
3155     CLEANUP ();
3156     errno = ENOMEM;
3157     return NULL;
3158   }
3159 }
3160
3161 #undef SNPRINTF
3162 #undef USE_SNPRINTF
3163 #undef PRINTF_PARSE
3164 #undef DIRECTIVES
3165 #undef DIRECTIVE
3166 #undef CHAR_T
3167 #undef VASNPRINTF