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