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