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