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