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