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