]> git.cworth.org Git - tar/blob - lib/vasnprintf.c
Imported Upstream version 1.20
[tar] / lib / vasnprintf.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* vsprintf with automatic memory allocation.
4    Copyright (C) 1999, 2002-2008 Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License along
17    with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 /* This file can be parametrized with the following macros:
21      VASNPRINTF         The name of the function being defined.
22      FCHAR_T            The element type of the format string.
23      DCHAR_T            The element type of the destination (result) string.
24      FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
25                         in the format string are ASCII. MUST be set if
26                         FCHAR_T and DCHAR_T are not the same type.
27      DIRECTIVE          Structure denoting a format directive.
28                         Depends on FCHAR_T.
29      DIRECTIVES         Structure denoting the set of format directives of a
30                         format string.  Depends on FCHAR_T.
31      PRINTF_PARSE       Function that parses a format string.
32                         Depends on FCHAR_T.
33      DCHAR_CPY          memcpy like function for DCHAR_T[] arrays.
34      DCHAR_SET          memset like function for DCHAR_T[] arrays.
35      DCHAR_MBSNLEN      mbsnlen like function for DCHAR_T[] arrays.
36      SNPRINTF           The system's snprintf (or similar) function.
37                         This may be either snprintf or swprintf.
38      TCHAR_T            The element type of the argument and result string
39                         of the said SNPRINTF function.  This may be either
40                         char or wchar_t.  The code exploits that
41                         sizeof (TCHAR_T) | sizeof (DCHAR_T) and
42                         alignof (TCHAR_T) <= alignof (DCHAR_T).
43      DCHAR_IS_TCHAR     Set to 1 if DCHAR_T and TCHAR_T are the same type.
44      DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
45      DCHAR_IS_UINT8_T   Set to 1 if DCHAR_T is uint8_t.
46      DCHAR_IS_UINT16_T  Set to 1 if DCHAR_T is uint16_t.
47      DCHAR_IS_UINT32_T  Set to 1 if DCHAR_T is uint32_t.  */
48
49 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
50    This must come before <config.h> because <config.h> may include
51    <features.h>, and once <features.h> has been included, it's too late.  */
52 #ifndef _GNU_SOURCE
53 # define _GNU_SOURCE    1
54 #endif
55
56 #ifndef VASNPRINTF
57 # include <config.h>
58 #endif
59 #ifndef IN_LIBINTL
60 # include <alloca.h>
61 #endif
62
63 /* Specification.  */
64 #ifndef VASNPRINTF
65 # if WIDE_CHAR_VERSION
66 #  include "vasnwprintf.h"
67 # else
68 #  include "vasnprintf.h"
69 # endif
70 #endif
71
72 #include <locale.h>     /* localeconv() */
73 #include <stdio.h>      /* snprintf(), sprintf() */
74 #include <stdlib.h>     /* abort(), malloc(), realloc(), free() */
75 #include <string.h>     /* memcpy(), strlen() */
76 #include <errno.h>      /* errno */
77 #include <limits.h>     /* CHAR_BIT */
78 #include <float.h>      /* DBL_MAX_EXP, LDBL_MAX_EXP */
79 #if HAVE_NL_LANGINFO
80 # include <langinfo.h>
81 #endif
82 #ifndef VASNPRINTF
83 # if WIDE_CHAR_VERSION
84 #  include "wprintf-parse.h"
85 # else
86 #  include "printf-parse.h"
87 # endif
88 #endif
89
90 /* Checked size_t computations.  */
91 #include "xsize.h"
92
93 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
94 # include <math.h>
95 # include "float+.h"
96 #endif
97
98 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
99 # include <math.h>
100 # include "isnand.h"
101 #endif
102
103 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
104 # include <math.h>
105 # include "isnanl-nolibm.h"
106 # include "fpucw.h"
107 #endif
108
109 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
110 # include <math.h>
111 # include "isnand.h"
112 # include "printf-frexp.h"
113 #endif
114
115 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
116 # include <math.h>
117 # include "isnanl-nolibm.h"
118 # include "printf-frexpl.h"
119 # include "fpucw.h"
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_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 && !NEED_PRINTF_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 isnand (x) || x + x == x;
237 }
238
239 #endif
240
241 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_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 || NEED_PRINTF_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 # if NEED_PRINTF_LONG_DOUBLE
799
800 /* Assuming x is finite and >= 0:
801    write x as x = 2^e * m, where m is a bignum.
802    Return the allocated memory in case of success, NULL in case of memory
803    allocation failure.  */
804 static void *
805 decode_long_double (long double x, int *ep, mpn_t *mp)
806 {
807   mpn_t m;
808   int exp;
809   long double y;
810   size_t i;
811
812   /* Allocate memory for result.  */
813   m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
814   m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
815   if (m.limbs == NULL)
816     return NULL;
817   /* Split into exponential part and mantissa.  */
818   y = frexpl (x, &exp);
819   if (!(y >= 0.0L && y < 1.0L))
820     abort ();
821   /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * LDBL_MANT_BIT), and the
822      latter is an integer.  */
823   /* Convert the mantissa (y * LDBL_MANT_BIT) to a sequence of limbs.
824      I'm not sure whether it's safe to cast a 'long double' value between
825      2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
826      'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
827      doesn't matter).  */
828 #  if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
829 #   if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
830     {
831       mp_limb_t hi, lo;
832       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
833       hi = (int) y;
834       y -= hi;
835       if (!(y >= 0.0L && y < 1.0L))
836         abort ();
837       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
838       lo = (int) y;
839       y -= lo;
840       if (!(y >= 0.0L && y < 1.0L))
841         abort ();
842       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
843     }
844 #   else
845     {
846       mp_limb_t d;
847       y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
848       d = (int) y;
849       y -= d;
850       if (!(y >= 0.0L && y < 1.0L))
851         abort ();
852       m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
853     }
854 #   endif
855 #  endif
856   for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
857     {
858       mp_limb_t hi, lo;
859       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
860       hi = (int) y;
861       y -= hi;
862       if (!(y >= 0.0L && y < 1.0L))
863         abort ();
864       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
865       lo = (int) y;
866       y -= lo;
867       if (!(y >= 0.0L && y < 1.0L))
868         abort ();
869       m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
870     }
871 #if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
872          precision.  */
873   if (!(y == 0.0L))
874     abort ();
875 #endif
876   /* Normalise.  */
877   while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
878     m.nlimbs--;
879   *mp = m;
880   *ep = exp - LDBL_MANT_BIT;
881   return m.limbs;
882 }
883
884 # endif
885
886 # if NEED_PRINTF_DOUBLE
887
888 /* Assuming x is finite and >= 0:
889    write x as x = 2^e * m, where m is a bignum.
890    Return the allocated memory in case of success, NULL in case of memory
891    allocation failure.  */
892 static void *
893 decode_double (double x, int *ep, mpn_t *mp)
894 {
895   mpn_t m;
896   int exp;
897   double y;
898   size_t i;
899
900   /* Allocate memory for result.  */
901   m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
902   m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
903   if (m.limbs == NULL)
904     return NULL;
905   /* Split into exponential part and mantissa.  */
906   y = frexp (x, &exp);
907   if (!(y >= 0.0 && y < 1.0))
908     abort ();
909   /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * DBL_MANT_BIT), and the
910      latter is an integer.  */
911   /* Convert the mantissa (y * DBL_MANT_BIT) to a sequence of limbs.
912      I'm not sure whether it's safe to cast a 'double' value between
913      2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
914      'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
915      doesn't matter).  */
916 #  if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
917 #   if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
918     {
919       mp_limb_t hi, lo;
920       y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
921       hi = (int) y;
922       y -= hi;
923       if (!(y >= 0.0 && y < 1.0))
924         abort ();
925       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
926       lo = (int) y;
927       y -= lo;
928       if (!(y >= 0.0 && y < 1.0))
929         abort ();
930       m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
931     }
932 #   else
933     {
934       mp_limb_t d;
935       y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
936       d = (int) y;
937       y -= d;
938       if (!(y >= 0.0 && y < 1.0))
939         abort ();
940       m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
941     }
942 #   endif
943 #  endif
944   for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
945     {
946       mp_limb_t hi, lo;
947       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
948       hi = (int) y;
949       y -= hi;
950       if (!(y >= 0.0 && y < 1.0))
951         abort ();
952       y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
953       lo = (int) y;
954       y -= lo;
955       if (!(y >= 0.0 && y < 1.0))
956         abort ();
957       m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
958     }
959   if (!(y == 0.0))
960     abort ();
961   /* Normalise.  */
962   while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
963     m.nlimbs--;
964   *mp = m;
965   *ep = exp - DBL_MANT_BIT;
966   return m.limbs;
967 }
968
969 # endif
970
971 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
972    Returns the decimal representation of round (x * 10^n).
973    Return the allocated memory - containing the decimal digits in low-to-high
974    order, terminated with a NUL character - in case of success, NULL in case
975    of memory allocation failure.  */
976 static char *
977 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
978 {
979   int s;
980   size_t extra_zeroes;
981   unsigned int abs_n;
982   unsigned int abs_s;
983   mp_limb_t *pow5_ptr;
984   size_t pow5_len;
985   unsigned int s_limbs;
986   unsigned int s_bits;
987   mpn_t pow5;
988   mpn_t z;
989   void *z_memory;
990   char *digits;
991
992   if (memory == NULL)
993     return NULL;
994   /* x = 2^e * m, hence
995      y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
996        = round (2^s * 5^n * m).  */
997   s = e + n;
998   extra_zeroes = 0;
999   /* Factor out a common power of 10 if possible.  */
1000   if (s > 0 && n > 0)
1001     {
1002       extra_zeroes = (s < n ? s : n);
1003       s -= extra_zeroes;
1004       n -= extra_zeroes;
1005     }
1006   /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1007      Before converting to decimal, we need to compute
1008      z = round (2^s * 5^n * m).  */
1009   /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1010      sign.  2.322 is slightly larger than log(5)/log(2).  */
1011   abs_n = (n >= 0 ? n : -n);
1012   abs_s = (s >= 0 ? s : -s);
1013   pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1014                                     + abs_s / GMP_LIMB_BITS + 1)
1015                                    * sizeof (mp_limb_t));
1016   if (pow5_ptr == NULL)
1017     {
1018       free (memory);
1019       return NULL;
1020     }
1021   /* Initialize with 1.  */
1022   pow5_ptr[0] = 1;
1023   pow5_len = 1;
1024   /* Multiply with 5^|n|.  */
1025   if (abs_n > 0)
1026     {
1027       static mp_limb_t const small_pow5[13 + 1] =
1028         {
1029           1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1030           48828125, 244140625, 1220703125
1031         };
1032       unsigned int n13;
1033       for (n13 = 0; n13 <= abs_n; n13 += 13)
1034         {
1035           mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1036           size_t j;
1037           mp_twolimb_t carry = 0;
1038           for (j = 0; j < pow5_len; j++)
1039             {
1040               mp_limb_t digit2 = pow5_ptr[j];
1041               carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1042               pow5_ptr[j] = (mp_limb_t) carry;
1043               carry = carry >> GMP_LIMB_BITS;
1044             }
1045           if (carry > 0)
1046             pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1047         }
1048     }
1049   s_limbs = abs_s / GMP_LIMB_BITS;
1050   s_bits = abs_s % GMP_LIMB_BITS;
1051   if (n >= 0 ? s >= 0 : s <= 0)
1052     {
1053       /* Multiply with 2^|s|.  */
1054       if (s_bits > 0)
1055         {
1056           mp_limb_t *ptr = pow5_ptr;
1057           mp_twolimb_t accu = 0;
1058           size_t count;
1059           for (count = pow5_len; count > 0; count--)
1060             {
1061               accu += (mp_twolimb_t) *ptr << s_bits;
1062               *ptr++ = (mp_limb_t) accu;
1063               accu = accu >> GMP_LIMB_BITS;
1064             }
1065           if (accu > 0)
1066             {
1067               *ptr = (mp_limb_t) accu;
1068               pow5_len++;
1069             }
1070         }
1071       if (s_limbs > 0)
1072         {
1073           size_t count;
1074           for (count = pow5_len; count > 0;)
1075             {
1076               count--;
1077               pow5_ptr[s_limbs + count] = pow5_ptr[count];
1078             }
1079           for (count = s_limbs; count > 0;)
1080             {
1081               count--;
1082               pow5_ptr[count] = 0;
1083             }
1084           pow5_len += s_limbs;
1085         }
1086       pow5.limbs = pow5_ptr;
1087       pow5.nlimbs = pow5_len;
1088       if (n >= 0)
1089         {
1090           /* Multiply m with pow5.  No division needed.  */
1091           z_memory = multiply (m, pow5, &z);
1092         }
1093       else
1094         {
1095           /* Divide m by pow5 and round.  */
1096           z_memory = divide (m, pow5, &z);
1097         }
1098     }
1099   else
1100     {
1101       pow5.limbs = pow5_ptr;
1102       pow5.nlimbs = pow5_len;
1103       if (n >= 0)
1104         {
1105           /* n >= 0, s < 0.
1106              Multiply m with pow5, then divide by 2^|s|.  */
1107           mpn_t numerator;
1108           mpn_t denominator;
1109           void *tmp_memory;
1110           tmp_memory = multiply (m, pow5, &numerator);
1111           if (tmp_memory == NULL)
1112             {
1113               free (pow5_ptr);
1114               free (memory);
1115               return NULL;
1116             }
1117           /* Construct 2^|s|.  */
1118           {
1119             mp_limb_t *ptr = pow5_ptr + pow5_len;
1120             size_t i;
1121             for (i = 0; i < s_limbs; i++)
1122               ptr[i] = 0;
1123             ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1124             denominator.limbs = ptr;
1125             denominator.nlimbs = s_limbs + 1;
1126           }
1127           z_memory = divide (numerator, denominator, &z);
1128           free (tmp_memory);
1129         }
1130       else
1131         {
1132           /* n < 0, s > 0.
1133              Multiply m with 2^s, then divide by pow5.  */
1134           mpn_t numerator;
1135           mp_limb_t *num_ptr;
1136           num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1137                                           * sizeof (mp_limb_t));
1138           if (num_ptr == NULL)
1139             {
1140               free (pow5_ptr);
1141               free (memory);
1142               return NULL;
1143             }
1144           {
1145             mp_limb_t *destptr = num_ptr;
1146             {
1147               size_t i;
1148               for (i = 0; i < s_limbs; i++)
1149                 *destptr++ = 0;
1150             }
1151             if (s_bits > 0)
1152               {
1153                 const mp_limb_t *sourceptr = m.limbs;
1154                 mp_twolimb_t accu = 0;
1155                 size_t count;
1156                 for (count = m.nlimbs; count > 0; count--)
1157                   {
1158                     accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1159                     *destptr++ = (mp_limb_t) accu;
1160                     accu = accu >> GMP_LIMB_BITS;
1161                   }
1162                 if (accu > 0)
1163                   *destptr++ = (mp_limb_t) accu;
1164               }
1165             else
1166               {
1167                 const mp_limb_t *sourceptr = m.limbs;
1168                 size_t count;
1169                 for (count = m.nlimbs; count > 0; count--)
1170                   *destptr++ = *sourceptr++;
1171               }
1172             numerator.limbs = num_ptr;
1173             numerator.nlimbs = destptr - num_ptr;
1174           }
1175           z_memory = divide (numerator, pow5, &z);
1176           free (num_ptr);
1177         }
1178     }
1179   free (pow5_ptr);
1180   free (memory);
1181
1182   /* Here y = round (x * 10^n) = z * 10^extra_zeroes.  */
1183
1184   if (z_memory == NULL)
1185     return NULL;
1186   digits = convert_to_decimal (z, extra_zeroes);
1187   free (z_memory);
1188   return digits;
1189 }
1190
1191 # if NEED_PRINTF_LONG_DOUBLE
1192
1193 /* Assuming x is finite and >= 0, and n is an integer:
1194    Returns the decimal representation of round (x * 10^n).
1195    Return the allocated memory - containing the decimal digits in low-to-high
1196    order, terminated with a NUL character - in case of success, NULL in case
1197    of memory allocation failure.  */
1198 static char *
1199 scale10_round_decimal_long_double (long double x, int n)
1200 {
1201   int e;
1202   mpn_t m;
1203   void *memory = decode_long_double (x, &e, &m);
1204   return scale10_round_decimal_decoded (e, m, memory, n);
1205 }
1206
1207 # endif
1208
1209 # if NEED_PRINTF_DOUBLE
1210
1211 /* Assuming x is finite and >= 0, and n is an integer:
1212    Returns the decimal representation of round (x * 10^n).
1213    Return the allocated memory - containing the decimal digits in low-to-high
1214    order, terminated with a NUL character - in case of success, NULL in case
1215    of memory allocation failure.  */
1216 static char *
1217 scale10_round_decimal_double (double x, int n)
1218 {
1219   int e;
1220   mpn_t m;
1221   void *memory = decode_double (x, &e, &m);
1222   return scale10_round_decimal_decoded (e, m, memory, n);
1223 }
1224
1225 # endif
1226
1227 # if NEED_PRINTF_LONG_DOUBLE
1228
1229 /* Assuming x is finite and > 0:
1230    Return an approximation for n with 10^n <= x < 10^(n+1).
1231    The approximation is usually the right n, but may be off by 1 sometimes.  */
1232 static int
1233 floorlog10l (long double x)
1234 {
1235   int exp;
1236   long double y;
1237   double z;
1238   double l;
1239
1240   /* Split into exponential part and mantissa.  */
1241   y = frexpl (x, &exp);
1242   if (!(y >= 0.0L && y < 1.0L))
1243     abort ();
1244   if (y == 0.0L)
1245     return INT_MIN;
1246   if (y < 0.5L)
1247     {
1248       while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1249         {
1250           y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1251           exp -= GMP_LIMB_BITS;
1252         }
1253       if (y < (1.0L / (1 << 16)))
1254         {
1255           y *= 1.0L * (1 << 16);
1256           exp -= 16;
1257         }
1258       if (y < (1.0L / (1 << 8)))
1259         {
1260           y *= 1.0L * (1 << 8);
1261           exp -= 8;
1262         }
1263       if (y < (1.0L / (1 << 4)))
1264         {
1265           y *= 1.0L * (1 << 4);
1266           exp -= 4;
1267         }
1268       if (y < (1.0L / (1 << 2)))
1269         {
1270           y *= 1.0L * (1 << 2);
1271           exp -= 2;
1272         }
1273       if (y < (1.0L / (1 << 1)))
1274         {
1275           y *= 1.0L * (1 << 1);
1276           exp -= 1;
1277         }
1278     }
1279   if (!(y >= 0.5L && y < 1.0L))
1280     abort ();
1281   /* Compute an approximation for l = log2(x) = exp + log2(y).  */
1282   l = exp;
1283   z = y;
1284   if (z < 0.70710678118654752444)
1285     {
1286       z *= 1.4142135623730950488;
1287       l -= 0.5;
1288     }
1289   if (z < 0.8408964152537145431)
1290     {
1291       z *= 1.1892071150027210667;
1292       l -= 0.25;
1293     }
1294   if (z < 0.91700404320467123175)
1295     {
1296       z *= 1.0905077326652576592;
1297       l -= 0.125;
1298     }
1299   if (z < 0.9576032806985736469)
1300     {
1301       z *= 1.0442737824274138403;
1302       l -= 0.0625;
1303     }
1304   /* Now 0.95 <= z <= 1.01.  */
1305   z = 1 - z;
1306   /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1307      Four terms are enough to get an approximation with error < 10^-7.  */
1308   l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1309   /* Finally multiply with log(2)/log(10), yields an approximation for
1310      log10(x).  */
1311   l *= 0.30102999566398119523;
1312   /* Round down to the next integer.  */
1313   return (int) l + (l < 0 ? -1 : 0);
1314 }
1315
1316 # endif
1317
1318 # if NEED_PRINTF_DOUBLE
1319
1320 /* Assuming x is finite and > 0:
1321    Return an approximation for n with 10^n <= x < 10^(n+1).
1322    The approximation is usually the right n, but may be off by 1 sometimes.  */
1323 static int
1324 floorlog10 (double x)
1325 {
1326   int exp;
1327   double y;
1328   double z;
1329   double l;
1330
1331   /* Split into exponential part and mantissa.  */
1332   y = frexp (x, &exp);
1333   if (!(y >= 0.0 && y < 1.0))
1334     abort ();
1335   if (y == 0.0)
1336     return INT_MIN;
1337   if (y < 0.5)
1338     {
1339       while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1340         {
1341           y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1342           exp -= GMP_LIMB_BITS;
1343         }
1344       if (y < (1.0 / (1 << 16)))
1345         {
1346           y *= 1.0 * (1 << 16);
1347           exp -= 16;
1348         }
1349       if (y < (1.0 / (1 << 8)))
1350         {
1351           y *= 1.0 * (1 << 8);
1352           exp -= 8;
1353         }
1354       if (y < (1.0 / (1 << 4)))
1355         {
1356           y *= 1.0 * (1 << 4);
1357           exp -= 4;
1358         }
1359       if (y < (1.0 / (1 << 2)))
1360         {
1361           y *= 1.0 * (1 << 2);
1362           exp -= 2;
1363         }
1364       if (y < (1.0 / (1 << 1)))
1365         {
1366           y *= 1.0 * (1 << 1);
1367           exp -= 1;
1368         }
1369     }
1370   if (!(y >= 0.5 && y < 1.0))
1371     abort ();
1372   /* Compute an approximation for l = log2(x) = exp + log2(y).  */
1373   l = exp;
1374   z = y;
1375   if (z < 0.70710678118654752444)
1376     {
1377       z *= 1.4142135623730950488;
1378       l -= 0.5;
1379     }
1380   if (z < 0.8408964152537145431)
1381     {
1382       z *= 1.1892071150027210667;
1383       l -= 0.25;
1384     }
1385   if (z < 0.91700404320467123175)
1386     {
1387       z *= 1.0905077326652576592;
1388       l -= 0.125;
1389     }
1390   if (z < 0.9576032806985736469)
1391     {
1392       z *= 1.0442737824274138403;
1393       l -= 0.0625;
1394     }
1395   /* Now 0.95 <= z <= 1.01.  */
1396   z = 1 - z;
1397   /* log(1-z) = - z - z^2/2 - z^3/3 - z^4/4 - ...
1398      Four terms are enough to get an approximation with error < 10^-7.  */
1399   l -= z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1400   /* Finally multiply with log(2)/log(10), yields an approximation for
1401      log10(x).  */
1402   l *= 0.30102999566398119523;
1403   /* Round down to the next integer.  */
1404   return (int) l + (l < 0 ? -1 : 0);
1405 }
1406
1407 # endif
1408
1409 #endif
1410
1411 DCHAR_T *
1412 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1413             const FCHAR_T *format, va_list args)
1414 {
1415   DIRECTIVES d;
1416   arguments a;
1417
1418   if (PRINTF_PARSE (format, &d, &a) < 0)
1419     /* errno is already set.  */
1420     return NULL;
1421
1422 #define CLEANUP() \
1423   free (d.dir);                                                         \
1424   if (a.arg)                                                            \
1425     free (a.arg);
1426
1427   if (PRINTF_FETCHARGS (args, &a) < 0)
1428     {
1429       CLEANUP ();
1430       errno = EINVAL;
1431       return NULL;
1432     }
1433
1434   {
1435     size_t buf_neededlength;
1436     TCHAR_T *buf;
1437     TCHAR_T *buf_malloced;
1438     const FCHAR_T *cp;
1439     size_t i;
1440     DIRECTIVE *dp;
1441     /* Output string accumulator.  */
1442     DCHAR_T *result;
1443     size_t allocated;
1444     size_t length;
1445
1446     /* Allocate a small buffer that will hold a directive passed to
1447        sprintf or snprintf.  */
1448     buf_neededlength =
1449       xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1450 #if HAVE_ALLOCA
1451     if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1452       {
1453         buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1454         buf_malloced = NULL;
1455       }
1456     else
1457 #endif
1458       {
1459         size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1460         if (size_overflow_p (buf_memsize))
1461           goto out_of_memory_1;
1462         buf = (TCHAR_T *) malloc (buf_memsize);
1463         if (buf == NULL)
1464           goto out_of_memory_1;
1465         buf_malloced = buf;
1466       }
1467
1468     if (resultbuf != NULL)
1469       {
1470         result = resultbuf;
1471         allocated = *lengthp;
1472       }
1473     else
1474       {
1475         result = NULL;
1476         allocated = 0;
1477       }
1478     length = 0;
1479     /* Invariants:
1480        result is either == resultbuf or == NULL or malloc-allocated.
1481        If length > 0, then result != NULL.  */
1482
1483     /* Ensures that allocated >= needed.  Aborts through a jump to
1484        out_of_memory if needed is SIZE_MAX or otherwise too big.  */
1485 #define ENSURE_ALLOCATION(needed) \
1486     if ((needed) > allocated)                                                \
1487       {                                                                      \
1488         size_t memory_size;                                                  \
1489         DCHAR_T *memory;                                                     \
1490                                                                              \
1491         allocated = (allocated > 0 ? xtimes (allocated, 2) : 12);            \
1492         if ((needed) > allocated)                                            \
1493           allocated = (needed);                                              \
1494         memory_size = xtimes (allocated, sizeof (DCHAR_T));                  \
1495         if (size_overflow_p (memory_size))                                   \
1496           goto out_of_memory;                                                \
1497         if (result == resultbuf || result == NULL)                           \
1498           memory = (DCHAR_T *) malloc (memory_size);                         \
1499         else                                                                 \
1500           memory = (DCHAR_T *) realloc (result, memory_size);                \
1501         if (memory == NULL)                                                  \
1502           goto out_of_memory;                                                \
1503         if (result == resultbuf && length > 0)                               \
1504           DCHAR_CPY (memory, result, length);                                \
1505         result = memory;                                                     \
1506       }
1507
1508     for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1509       {
1510         if (cp != dp->dir_start)
1511           {
1512             size_t n = dp->dir_start - cp;
1513             size_t augmented_length = xsum (length, n);
1514
1515             ENSURE_ALLOCATION (augmented_length);
1516             /* This copies a piece of FCHAR_T[] into a DCHAR_T[].  Here we
1517                need that the format string contains only ASCII characters
1518                if FCHAR_T and DCHAR_T are not the same type.  */
1519             if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1520               {
1521                 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1522                 length = augmented_length;
1523               }
1524             else
1525               {
1526                 do
1527                   result[length++] = (unsigned char) *cp++;
1528                 while (--n > 0);
1529               }
1530           }
1531         if (i == d.count)
1532           break;
1533
1534         /* Execute a single directive.  */
1535         if (dp->conversion == '%')
1536           {
1537             size_t augmented_length;
1538
1539             if (!(dp->arg_index == ARG_NONE))
1540               abort ();
1541             augmented_length = xsum (length, 1);
1542             ENSURE_ALLOCATION (augmented_length);
1543             result[length] = '%';
1544             length = augmented_length;
1545           }
1546         else
1547           {
1548             if (!(dp->arg_index != ARG_NONE))
1549               abort ();
1550
1551             if (dp->conversion == 'n')
1552               {
1553                 switch (a.arg[dp->arg_index].type)
1554                   {
1555                   case TYPE_COUNT_SCHAR_POINTER:
1556                     *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
1557                     break;
1558                   case TYPE_COUNT_SHORT_POINTER:
1559                     *a.arg[dp->arg_index].a.a_count_short_pointer = length;
1560                     break;
1561                   case TYPE_COUNT_INT_POINTER:
1562                     *a.arg[dp->arg_index].a.a_count_int_pointer = length;
1563                     break;
1564                   case TYPE_COUNT_LONGINT_POINTER:
1565                     *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
1566                     break;
1567 #if HAVE_LONG_LONG_INT
1568                   case TYPE_COUNT_LONGLONGINT_POINTER:
1569                     *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
1570                     break;
1571 #endif
1572                   default:
1573                     abort ();
1574                   }
1575               }
1576 #if ENABLE_UNISTDIO
1577             /* The unistdio extensions.  */
1578             else if (dp->conversion == 'U')
1579               {
1580                 arg_type type = a.arg[dp->arg_index].type;
1581                 int flags = dp->flags;
1582                 int has_width;
1583                 size_t width;
1584                 int has_precision;
1585                 size_t precision;
1586
1587                 has_width = 0;
1588                 width = 0;
1589                 if (dp->width_start != dp->width_end)
1590                   {
1591                     if (dp->width_arg_index != ARG_NONE)
1592                       {
1593                         int arg;
1594
1595                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1596                           abort ();
1597                         arg = a.arg[dp->width_arg_index].a.a_int;
1598                         if (arg < 0)
1599                           {
1600                             /* "A negative field width is taken as a '-' flag
1601                                 followed by a positive field width."  */
1602                             flags |= FLAG_LEFT;
1603                             width = (unsigned int) (-arg);
1604                           }
1605                         else
1606                           width = arg;
1607                       }
1608                     else
1609                       {
1610                         const FCHAR_T *digitp = dp->width_start;
1611
1612                         do
1613                           width = xsum (xtimes (width, 10), *digitp++ - '0');
1614                         while (digitp != dp->width_end);
1615                       }
1616                     has_width = 1;
1617                   }
1618
1619                 has_precision = 0;
1620                 precision = 0;
1621                 if (dp->precision_start != dp->precision_end)
1622                   {
1623                     if (dp->precision_arg_index != ARG_NONE)
1624                       {
1625                         int arg;
1626
1627                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1628                           abort ();
1629                         arg = a.arg[dp->precision_arg_index].a.a_int;
1630                         /* "A negative precision is taken as if the precision
1631                             were omitted."  */
1632                         if (arg >= 0)
1633                           {
1634                             precision = arg;
1635                             has_precision = 1;
1636                           }
1637                       }
1638                     else
1639                       {
1640                         const FCHAR_T *digitp = dp->precision_start + 1;
1641
1642                         precision = 0;
1643                         while (digitp != dp->precision_end)
1644                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
1645                         has_precision = 1;
1646                       }
1647                   }
1648
1649                 switch (type)
1650                   {
1651                   case TYPE_U8_STRING:
1652                     {
1653                       const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
1654                       const uint8_t *arg_end;
1655                       size_t characters;
1656
1657                       if (has_precision)
1658                         {
1659                           /* Use only PRECISION characters, from the left.  */
1660                           arg_end = arg;
1661                           characters = 0;
1662                           for (; precision > 0; precision--)
1663                             {
1664                               int count = u8_strmblen (arg_end);
1665                               if (count == 0)
1666                                 break;
1667                               if (count < 0)
1668                                 {
1669                                   if (!(result == resultbuf || result == NULL))
1670                                     free (result);
1671                                   if (buf_malloced != NULL)
1672                                     free (buf_malloced);
1673                                   CLEANUP ();
1674                                   errno = EILSEQ;
1675                                   return NULL;
1676                                 }
1677                               arg_end += count;
1678                               characters++;
1679                             }
1680                         }
1681                       else if (has_width)
1682                         {
1683                           /* Use the entire string, and count the number of
1684                              characters.  */
1685                           arg_end = arg;
1686                           characters = 0;
1687                           for (;;)
1688                             {
1689                               int count = u8_strmblen (arg_end);
1690                               if (count == 0)
1691                                 break;
1692                               if (count < 0)
1693                                 {
1694                                   if (!(result == resultbuf || result == NULL))
1695                                     free (result);
1696                                   if (buf_malloced != NULL)
1697                                     free (buf_malloced);
1698                                   CLEANUP ();
1699                                   errno = EILSEQ;
1700                                   return NULL;
1701                                 }
1702                               arg_end += count;
1703                               characters++;
1704                             }
1705                         }
1706                       else
1707                         {
1708                           /* Use the entire string.  */
1709                           arg_end = arg + u8_strlen (arg);
1710                           /* The number of characters doesn't matter.  */
1711                           characters = 0;
1712                         }
1713
1714                       if (has_width && width > characters
1715                           && !(dp->flags & FLAG_LEFT))
1716                         {
1717                           size_t n = width - characters;
1718                           ENSURE_ALLOCATION (xsum (length, n));
1719                           DCHAR_SET (result + length, ' ', n);
1720                           length += n;
1721                         }
1722
1723 # if DCHAR_IS_UINT8_T
1724                       {
1725                         size_t n = arg_end - arg;
1726                         ENSURE_ALLOCATION (xsum (length, n));
1727                         DCHAR_CPY (result + length, arg, n);
1728                         length += n;
1729                       }
1730 # else
1731                       { /* Convert.  */
1732                         DCHAR_T *converted = result + length;
1733                         size_t converted_len = allocated - length;
1734 #  if DCHAR_IS_TCHAR
1735                         /* Convert from UTF-8 to locale encoding.  */
1736                         if (u8_conv_to_encoding (locale_charset (),
1737                                                  iconveh_question_mark,
1738                                                  arg, arg_end - arg, NULL,
1739                                                  &converted, &converted_len)
1740                             < 0)
1741 #  else
1742                         /* Convert from UTF-8 to UTF-16/UTF-32.  */
1743                         converted =
1744                           U8_TO_DCHAR (arg, arg_end - arg,
1745                                        converted, &converted_len);
1746                         if (converted == NULL)
1747 #  endif
1748                           {
1749                             int saved_errno = errno;
1750                             if (!(result == resultbuf || result == NULL))
1751                               free (result);
1752                             if (buf_malloced != NULL)
1753                               free (buf_malloced);
1754                             CLEANUP ();
1755                             errno = saved_errno;
1756                             return NULL;
1757                           }
1758                         if (converted != result + length)
1759                           {
1760                             ENSURE_ALLOCATION (xsum (length, converted_len));
1761                             DCHAR_CPY (result + length, converted, converted_len);
1762                             free (converted);
1763                           }
1764                         length += converted_len;
1765                       }
1766 # endif
1767
1768                       if (has_width && width > characters
1769                           && (dp->flags & FLAG_LEFT))
1770                         {
1771                           size_t n = width - characters;
1772                           ENSURE_ALLOCATION (xsum (length, n));
1773                           DCHAR_SET (result + length, ' ', n);
1774                           length += n;
1775                         }
1776                     }
1777                     break;
1778
1779                   case TYPE_U16_STRING:
1780                     {
1781                       const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
1782                       const uint16_t *arg_end;
1783                       size_t characters;
1784
1785                       if (has_precision)
1786                         {
1787                           /* Use only PRECISION characters, from the left.  */
1788                           arg_end = arg;
1789                           characters = 0;
1790                           for (; precision > 0; precision--)
1791                             {
1792                               int count = u16_strmblen (arg_end);
1793                               if (count == 0)
1794                                 break;
1795                               if (count < 0)
1796                                 {
1797                                   if (!(result == resultbuf || result == NULL))
1798                                     free (result);
1799                                   if (buf_malloced != NULL)
1800                                     free (buf_malloced);
1801                                   CLEANUP ();
1802                                   errno = EILSEQ;
1803                                   return NULL;
1804                                 }
1805                               arg_end += count;
1806                               characters++;
1807                             }
1808                         }
1809                       else if (has_width)
1810                         {
1811                           /* Use the entire string, and count the number of
1812                              characters.  */
1813                           arg_end = arg;
1814                           characters = 0;
1815                           for (;;)
1816                             {
1817                               int count = u16_strmblen (arg_end);
1818                               if (count == 0)
1819                                 break;
1820                               if (count < 0)
1821                                 {
1822                                   if (!(result == resultbuf || result == NULL))
1823                                     free (result);
1824                                   if (buf_malloced != NULL)
1825                                     free (buf_malloced);
1826                                   CLEANUP ();
1827                                   errno = EILSEQ;
1828                                   return NULL;
1829                                 }
1830                               arg_end += count;
1831                               characters++;
1832                             }
1833                         }
1834                       else
1835                         {
1836                           /* Use the entire string.  */
1837                           arg_end = arg + u16_strlen (arg);
1838                           /* The number of characters doesn't matter.  */
1839                           characters = 0;
1840                         }
1841
1842                       if (has_width && width > characters
1843                           && !(dp->flags & FLAG_LEFT))
1844                         {
1845                           size_t n = width - characters;
1846                           ENSURE_ALLOCATION (xsum (length, n));
1847                           DCHAR_SET (result + length, ' ', n);
1848                           length += n;
1849                         }
1850
1851 # if DCHAR_IS_UINT16_T
1852                       {
1853                         size_t n = arg_end - arg;
1854                         ENSURE_ALLOCATION (xsum (length, n));
1855                         DCHAR_CPY (result + length, arg, n);
1856                         length += n;
1857                       }
1858 # else
1859                       { /* Convert.  */
1860                         DCHAR_T *converted = result + length;
1861                         size_t converted_len = allocated - length;
1862 #  if DCHAR_IS_TCHAR
1863                         /* Convert from UTF-16 to locale encoding.  */
1864                         if (u16_conv_to_encoding (locale_charset (),
1865                                                   iconveh_question_mark,
1866                                                   arg, arg_end - arg, NULL,
1867                                                   &converted, &converted_len)
1868                             < 0)
1869 #  else
1870                         /* Convert from UTF-16 to UTF-8/UTF-32.  */
1871                         converted =
1872                           U16_TO_DCHAR (arg, arg_end - arg,
1873                                         converted, &converted_len);
1874                         if (converted == NULL)
1875 #  endif
1876                           {
1877                             int saved_errno = errno;
1878                             if (!(result == resultbuf || result == NULL))
1879                               free (result);
1880                             if (buf_malloced != NULL)
1881                               free (buf_malloced);
1882                             CLEANUP ();
1883                             errno = saved_errno;
1884                             return NULL;
1885                           }
1886                         if (converted != result + length)
1887                           {
1888                             ENSURE_ALLOCATION (xsum (length, converted_len));
1889                             DCHAR_CPY (result + length, converted, converted_len);
1890                             free (converted);
1891                           }
1892                         length += converted_len;
1893                       }
1894 # endif
1895
1896                       if (has_width && width > characters
1897                           && (dp->flags & FLAG_LEFT))
1898                         {
1899                           size_t n = width - characters;
1900                           ENSURE_ALLOCATION (xsum (length, n));
1901                           DCHAR_SET (result + length, ' ', n);
1902                           length += n;
1903                         }
1904                     }
1905                     break;
1906
1907                   case TYPE_U32_STRING:
1908                     {
1909                       const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
1910                       const uint32_t *arg_end;
1911                       size_t characters;
1912
1913                       if (has_precision)
1914                         {
1915                           /* Use only PRECISION characters, from the left.  */
1916                           arg_end = arg;
1917                           characters = 0;
1918                           for (; precision > 0; precision--)
1919                             {
1920                               int count = u32_strmblen (arg_end);
1921                               if (count == 0)
1922                                 break;
1923                               if (count < 0)
1924                                 {
1925                                   if (!(result == resultbuf || result == NULL))
1926                                     free (result);
1927                                   if (buf_malloced != NULL)
1928                                     free (buf_malloced);
1929                                   CLEANUP ();
1930                                   errno = EILSEQ;
1931                                   return NULL;
1932                                 }
1933                               arg_end += count;
1934                               characters++;
1935                             }
1936                         }
1937                       else if (has_width)
1938                         {
1939                           /* Use the entire string, and count the number of
1940                              characters.  */
1941                           arg_end = arg;
1942                           characters = 0;
1943                           for (;;)
1944                             {
1945                               int count = u32_strmblen (arg_end);
1946                               if (count == 0)
1947                                 break;
1948                               if (count < 0)
1949                                 {
1950                                   if (!(result == resultbuf || result == NULL))
1951                                     free (result);
1952                                   if (buf_malloced != NULL)
1953                                     free (buf_malloced);
1954                                   CLEANUP ();
1955                                   errno = EILSEQ;
1956                                   return NULL;
1957                                 }
1958                               arg_end += count;
1959                               characters++;
1960                             }
1961                         }
1962                       else
1963                         {
1964                           /* Use the entire string.  */
1965                           arg_end = arg + u32_strlen (arg);
1966                           /* The number of characters doesn't matter.  */
1967                           characters = 0;
1968                         }
1969
1970                       if (has_width && width > characters
1971                           && !(dp->flags & FLAG_LEFT))
1972                         {
1973                           size_t n = width - characters;
1974                           ENSURE_ALLOCATION (xsum (length, n));
1975                           DCHAR_SET (result + length, ' ', n);
1976                           length += n;
1977                         }
1978
1979 # if DCHAR_IS_UINT32_T
1980                       {
1981                         size_t n = arg_end - arg;
1982                         ENSURE_ALLOCATION (xsum (length, n));
1983                         DCHAR_CPY (result + length, arg, n);
1984                         length += n;
1985                       }
1986 # else
1987                       { /* Convert.  */
1988                         DCHAR_T *converted = result + length;
1989                         size_t converted_len = allocated - length;
1990 #  if DCHAR_IS_TCHAR
1991                         /* Convert from UTF-32 to locale encoding.  */
1992                         if (u32_conv_to_encoding (locale_charset (),
1993                                                   iconveh_question_mark,
1994                                                   arg, arg_end - arg, NULL,
1995                                                   &converted, &converted_len)
1996                             < 0)
1997 #  else
1998                         /* Convert from UTF-32 to UTF-8/UTF-16.  */
1999                         converted =
2000                           U32_TO_DCHAR (arg, arg_end - arg,
2001                                         converted, &converted_len);
2002                         if (converted == NULL)
2003 #  endif
2004                           {
2005                             int saved_errno = errno;
2006                             if (!(result == resultbuf || result == NULL))
2007                               free (result);
2008                             if (buf_malloced != NULL)
2009                               free (buf_malloced);
2010                             CLEANUP ();
2011                             errno = saved_errno;
2012                             return NULL;
2013                           }
2014                         if (converted != result + length)
2015                           {
2016                             ENSURE_ALLOCATION (xsum (length, converted_len));
2017                             DCHAR_CPY (result + length, converted, converted_len);
2018                             free (converted);
2019                           }
2020                         length += converted_len;
2021                       }
2022 # endif
2023
2024                       if (has_width && width > characters
2025                           && (dp->flags & FLAG_LEFT))
2026                         {
2027                           size_t n = width - characters;
2028                           ENSURE_ALLOCATION (xsum (length, n));
2029                           DCHAR_SET (result + length, ' ', n);
2030                           length += n;
2031                         }
2032                     }
2033                     break;
2034
2035                   default:
2036                     abort ();
2037                   }
2038               }
2039 #endif
2040 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
2041             else if ((dp->conversion == 'a' || dp->conversion == 'A')
2042 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
2043                      && (0
2044 #  if NEED_PRINTF_DOUBLE
2045                          || a.arg[dp->arg_index].type == TYPE_DOUBLE
2046 #  endif
2047 #  if NEED_PRINTF_LONG_DOUBLE
2048                          || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2049 #  endif
2050                         )
2051 # endif
2052                     )
2053               {
2054                 arg_type type = a.arg[dp->arg_index].type;
2055                 int flags = dp->flags;
2056                 int has_width;
2057                 size_t width;
2058                 int has_precision;
2059                 size_t precision;
2060                 size_t tmp_length;
2061                 DCHAR_T tmpbuf[700];
2062                 DCHAR_T *tmp;
2063                 DCHAR_T *pad_ptr;
2064                 DCHAR_T *p;
2065
2066                 has_width = 0;
2067                 width = 0;
2068                 if (dp->width_start != dp->width_end)
2069                   {
2070                     if (dp->width_arg_index != ARG_NONE)
2071                       {
2072                         int arg;
2073
2074                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2075                           abort ();
2076                         arg = a.arg[dp->width_arg_index].a.a_int;
2077                         if (arg < 0)
2078                           {
2079                             /* "A negative field width is taken as a '-' flag
2080                                 followed by a positive field width."  */
2081                             flags |= FLAG_LEFT;
2082                             width = (unsigned int) (-arg);
2083                           }
2084                         else
2085                           width = arg;
2086                       }
2087                     else
2088                       {
2089                         const FCHAR_T *digitp = dp->width_start;
2090
2091                         do
2092                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2093                         while (digitp != dp->width_end);
2094                       }
2095                     has_width = 1;
2096                   }
2097
2098                 has_precision = 0;
2099                 precision = 0;
2100                 if (dp->precision_start != dp->precision_end)
2101                   {
2102                     if (dp->precision_arg_index != ARG_NONE)
2103                       {
2104                         int arg;
2105
2106                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2107                           abort ();
2108                         arg = a.arg[dp->precision_arg_index].a.a_int;
2109                         /* "A negative precision is taken as if the precision
2110                             were omitted."  */
2111                         if (arg >= 0)
2112                           {
2113                             precision = arg;
2114                             has_precision = 1;
2115                           }
2116                       }
2117                     else
2118                       {
2119                         const FCHAR_T *digitp = dp->precision_start + 1;
2120
2121                         precision = 0;
2122                         while (digitp != dp->precision_end)
2123                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2124                         has_precision = 1;
2125                       }
2126                   }
2127
2128                 /* Allocate a temporary buffer of sufficient size.  */
2129                 if (type == TYPE_LONGDOUBLE)
2130                   tmp_length =
2131                     (unsigned int) ((LDBL_DIG + 1)
2132                                     * 0.831 /* decimal -> hexadecimal */
2133                                    )
2134                     + 1; /* turn floor into ceil */
2135                 else
2136                   tmp_length =
2137                     (unsigned int) ((DBL_DIG + 1)
2138                                     * 0.831 /* decimal -> hexadecimal */
2139                                    )
2140                     + 1; /* turn floor into ceil */
2141                 if (tmp_length < precision)
2142                   tmp_length = precision;
2143                 /* Account for sign, decimal point etc. */
2144                 tmp_length = xsum (tmp_length, 12);
2145
2146                 if (tmp_length < width)
2147                   tmp_length = width;
2148
2149                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2150
2151                 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2152                   tmp = tmpbuf;
2153                 else
2154                   {
2155                     size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2156
2157                     if (size_overflow_p (tmp_memsize))
2158                       /* Overflow, would lead to out of memory.  */
2159                       goto out_of_memory;
2160                     tmp = (DCHAR_T *) malloc (tmp_memsize);
2161                     if (tmp == NULL)
2162                       /* Out of memory.  */
2163                       goto out_of_memory;
2164                   }
2165
2166                 pad_ptr = NULL;
2167                 p = tmp;
2168                 if (type == TYPE_LONGDOUBLE)
2169                   {
2170 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
2171                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2172
2173                     if (isnanl (arg))
2174                       {
2175                         if (dp->conversion == 'A')
2176                           {
2177                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2178                           }
2179                         else
2180                           {
2181                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2182                           }
2183                       }
2184                     else
2185                       {
2186                         int sign = 0;
2187                         DECL_LONG_DOUBLE_ROUNDING
2188
2189                         BEGIN_LONG_DOUBLE_ROUNDING ();
2190
2191                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2192                           {
2193                             sign = -1;
2194                             arg = -arg;
2195                           }
2196
2197                         if (sign < 0)
2198                           *p++ = '-';
2199                         else if (flags & FLAG_SHOWSIGN)
2200                           *p++ = '+';
2201                         else if (flags & FLAG_SPACE)
2202                           *p++ = ' ';
2203
2204                         if (arg > 0.0L && arg + arg == arg)
2205                           {
2206                             if (dp->conversion == 'A')
2207                               {
2208                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2209                               }
2210                             else
2211                               {
2212                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2213                               }
2214                           }
2215                         else
2216                           {
2217                             int exponent;
2218                             long double mantissa;
2219
2220                             if (arg > 0.0L)
2221                               mantissa = printf_frexpl (arg, &exponent);
2222                             else
2223                               {
2224                                 exponent = 0;
2225                                 mantissa = 0.0L;
2226                               }
2227
2228                             if (has_precision
2229                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
2230                               {
2231                                 /* Round the mantissa.  */
2232                                 long double tail = mantissa;
2233                                 size_t q;
2234
2235                                 for (q = precision; ; q--)
2236                                   {
2237                                     int digit = (int) tail;
2238                                     tail -= digit;
2239                                     if (q == 0)
2240                                       {
2241                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
2242                                           tail = 1 - tail;
2243                                         else
2244                                           tail = - tail;
2245                                         break;
2246                                       }
2247                                     tail *= 16.0L;
2248                                   }
2249                                 if (tail != 0.0L)
2250                                   for (q = precision; q > 0; q--)
2251                                     tail *= 0.0625L;
2252                                 mantissa += tail;
2253                               }
2254
2255                             *p++ = '0';
2256                             *p++ = dp->conversion - 'A' + 'X';
2257                             pad_ptr = p;
2258                             {
2259                               int digit;
2260
2261                               digit = (int) mantissa;
2262                               mantissa -= digit;
2263                               *p++ = '0' + digit;
2264                               if ((flags & FLAG_ALT)
2265                                   || mantissa > 0.0L || precision > 0)
2266                                 {
2267                                   *p++ = decimal_point_char ();
2268                                   /* This loop terminates because we assume
2269                                      that FLT_RADIX is a power of 2.  */
2270                                   while (mantissa > 0.0L)
2271                                     {
2272                                       mantissa *= 16.0L;
2273                                       digit = (int) mantissa;
2274                                       mantissa -= digit;
2275                                       *p++ = digit
2276                                              + (digit < 10
2277                                                 ? '0'
2278                                                 : dp->conversion - 10);
2279                                       if (precision > 0)
2280                                         precision--;
2281                                     }
2282                                   while (precision > 0)
2283                                     {
2284                                       *p++ = '0';
2285                                       precision--;
2286                                     }
2287                                 }
2288                               }
2289                               *p++ = dp->conversion - 'A' + 'P';
2290 #  if WIDE_CHAR_VERSION
2291                               {
2292                                 static const wchar_t decimal_format[] =
2293                                   { '%', '+', 'd', '\0' };
2294                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2295                               }
2296                               while (*p != '\0')
2297                                 p++;
2298 #  else
2299                               if (sizeof (DCHAR_T) == 1)
2300                                 {
2301                                   sprintf ((char *) p, "%+d", exponent);
2302                                   while (*p != '\0')
2303                                     p++;
2304                                 }
2305                               else
2306                                 {
2307                                   char expbuf[6 + 1];
2308                                   const char *ep;
2309                                   sprintf (expbuf, "%+d", exponent);
2310                                   for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2311                                     p++;
2312                                 }
2313 #  endif
2314                           }
2315
2316                         END_LONG_DOUBLE_ROUNDING ();
2317                       }
2318 # else
2319                     abort ();
2320 # endif
2321                   }
2322                 else
2323                   {
2324 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
2325                     double arg = a.arg[dp->arg_index].a.a_double;
2326
2327                     if (isnand (arg))
2328                       {
2329                         if (dp->conversion == 'A')
2330                           {
2331                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2332                           }
2333                         else
2334                           {
2335                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2336                           }
2337                       }
2338                     else
2339                       {
2340                         int sign = 0;
2341
2342                         if (signbit (arg)) /* arg < 0.0 or negative zero */
2343                           {
2344                             sign = -1;
2345                             arg = -arg;
2346                           }
2347
2348                         if (sign < 0)
2349                           *p++ = '-';
2350                         else if (flags & FLAG_SHOWSIGN)
2351                           *p++ = '+';
2352                         else if (flags & FLAG_SPACE)
2353                           *p++ = ' ';
2354
2355                         if (arg > 0.0 && arg + arg == arg)
2356                           {
2357                             if (dp->conversion == 'A')
2358                               {
2359                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2360                               }
2361                             else
2362                               {
2363                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2364                               }
2365                           }
2366                         else
2367                           {
2368                             int exponent;
2369                             double mantissa;
2370
2371                             if (arg > 0.0)
2372                               mantissa = printf_frexp (arg, &exponent);
2373                             else
2374                               {
2375                                 exponent = 0;
2376                                 mantissa = 0.0;
2377                               }
2378
2379                             if (has_precision
2380                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
2381                               {
2382                                 /* Round the mantissa.  */
2383                                 double tail = mantissa;
2384                                 size_t q;
2385
2386                                 for (q = precision; ; q--)
2387                                   {
2388                                     int digit = (int) tail;
2389                                     tail -= digit;
2390                                     if (q == 0)
2391                                       {
2392                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
2393                                           tail = 1 - tail;
2394                                         else
2395                                           tail = - tail;
2396                                         break;
2397                                       }
2398                                     tail *= 16.0;
2399                                   }
2400                                 if (tail != 0.0)
2401                                   for (q = precision; q > 0; q--)
2402                                     tail *= 0.0625;
2403                                 mantissa += tail;
2404                               }
2405
2406                             *p++ = '0';
2407                             *p++ = dp->conversion - 'A' + 'X';
2408                             pad_ptr = p;
2409                             {
2410                               int digit;
2411
2412                               digit = (int) mantissa;
2413                               mantissa -= digit;
2414                               *p++ = '0' + digit;
2415                               if ((flags & FLAG_ALT)
2416                                   || mantissa > 0.0 || precision > 0)
2417                                 {
2418                                   *p++ = decimal_point_char ();
2419                                   /* This loop terminates because we assume
2420                                      that FLT_RADIX is a power of 2.  */
2421                                   while (mantissa > 0.0)
2422                                     {
2423                                       mantissa *= 16.0;
2424                                       digit = (int) mantissa;
2425                                       mantissa -= digit;
2426                                       *p++ = digit
2427                                              + (digit < 10
2428                                                 ? '0'
2429                                                 : dp->conversion - 10);
2430                                       if (precision > 0)
2431                                         precision--;
2432                                     }
2433                                   while (precision > 0)
2434                                     {
2435                                       *p++ = '0';
2436                                       precision--;
2437                                     }
2438                                 }
2439                               }
2440                               *p++ = dp->conversion - 'A' + 'P';
2441 #  if WIDE_CHAR_VERSION
2442                               {
2443                                 static const wchar_t decimal_format[] =
2444                                   { '%', '+', 'd', '\0' };
2445                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
2446                               }
2447                               while (*p != '\0')
2448                                 p++;
2449 #  else
2450                               if (sizeof (DCHAR_T) == 1)
2451                                 {
2452                                   sprintf ((char *) p, "%+d", exponent);
2453                                   while (*p != '\0')
2454                                     p++;
2455                                 }
2456                               else
2457                                 {
2458                                   char expbuf[6 + 1];
2459                                   const char *ep;
2460                                   sprintf (expbuf, "%+d", exponent);
2461                                   for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2462                                     p++;
2463                                 }
2464 #  endif
2465                           }
2466                       }
2467 # else
2468                     abort ();
2469 # endif
2470                   }
2471                 /* The generated string now extends from tmp to p, with the
2472                    zero padding insertion point being at pad_ptr.  */
2473                 if (has_width && p - tmp < width)
2474                   {
2475                     size_t pad = width - (p - tmp);
2476                     DCHAR_T *end = p + pad;
2477
2478                     if (flags & FLAG_LEFT)
2479                       {
2480                         /* Pad with spaces on the right.  */
2481                         for (; pad > 0; pad--)
2482                           *p++ = ' ';
2483                       }
2484                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
2485                       {
2486                         /* Pad with zeroes.  */
2487                         DCHAR_T *q = end;
2488
2489                         while (p > pad_ptr)
2490                           *--q = *--p;
2491                         for (; pad > 0; pad--)
2492                           *p++ = '0';
2493                       }
2494                     else
2495                       {
2496                         /* Pad with spaces on the left.  */
2497                         DCHAR_T *q = end;
2498
2499                         while (p > tmp)
2500                           *--q = *--p;
2501                         for (; pad > 0; pad--)
2502                           *p++ = ' ';
2503                       }
2504
2505                     p = end;
2506                   }
2507
2508                 {
2509                   size_t count = p - tmp;
2510
2511                   if (count >= tmp_length)
2512                     /* tmp_length was incorrectly calculated - fix the
2513                        code above!  */
2514                     abort ();
2515
2516                   /* Make room for the result.  */
2517                   if (count >= allocated - length)
2518                     {
2519                       size_t n = xsum (length, count);
2520
2521                       ENSURE_ALLOCATION (n);
2522                     }
2523
2524                   /* Append the result.  */
2525                   memcpy (result + length, tmp, count * sizeof (DCHAR_T));
2526                   if (tmp != tmpbuf)
2527                     free (tmp);
2528                   length += count;
2529                 }
2530               }
2531 #endif
2532 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
2533             else if ((dp->conversion == 'f' || dp->conversion == 'F'
2534                       || dp->conversion == 'e' || dp->conversion == 'E'
2535                       || dp->conversion == 'g' || dp->conversion == 'G'
2536                       || dp->conversion == 'a' || dp->conversion == 'A')
2537                      && (0
2538 # if NEED_PRINTF_DOUBLE
2539                          || a.arg[dp->arg_index].type == TYPE_DOUBLE
2540 # elif NEED_PRINTF_INFINITE_DOUBLE
2541                          || (a.arg[dp->arg_index].type == TYPE_DOUBLE
2542                              /* The systems (mingw) which produce wrong output
2543                                 for Inf, -Inf, and NaN also do so for -0.0.
2544                                 Therefore we treat this case here as well.  */
2545                              && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
2546 # endif
2547 # if NEED_PRINTF_LONG_DOUBLE
2548                          || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2549 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
2550                          || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
2551                              /* Some systems produce wrong output for Inf,
2552                                 -Inf, and NaN.  */
2553                              && is_infinitel (a.arg[dp->arg_index].a.a_longdouble))
2554 # endif
2555                         ))
2556               {
2557 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
2558                 arg_type type = a.arg[dp->arg_index].type;
2559 # endif
2560                 int flags = dp->flags;
2561                 int has_width;
2562                 size_t width;
2563                 int has_precision;
2564                 size_t precision;
2565                 size_t tmp_length;
2566                 DCHAR_T tmpbuf[700];
2567                 DCHAR_T *tmp;
2568                 DCHAR_T *pad_ptr;
2569                 DCHAR_T *p;
2570
2571                 has_width = 0;
2572                 width = 0;
2573                 if (dp->width_start != dp->width_end)
2574                   {
2575                     if (dp->width_arg_index != ARG_NONE)
2576                       {
2577                         int arg;
2578
2579                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2580                           abort ();
2581                         arg = a.arg[dp->width_arg_index].a.a_int;
2582                         if (arg < 0)
2583                           {
2584                             /* "A negative field width is taken as a '-' flag
2585                                 followed by a positive field width."  */
2586                             flags |= FLAG_LEFT;
2587                             width = (unsigned int) (-arg);
2588                           }
2589                         else
2590                           width = arg;
2591                       }
2592                     else
2593                       {
2594                         const FCHAR_T *digitp = dp->width_start;
2595
2596                         do
2597                           width = xsum (xtimes (width, 10), *digitp++ - '0');
2598                         while (digitp != dp->width_end);
2599                       }
2600                     has_width = 1;
2601                   }
2602
2603                 has_precision = 0;
2604                 precision = 0;
2605                 if (dp->precision_start != dp->precision_end)
2606                   {
2607                     if (dp->precision_arg_index != ARG_NONE)
2608                       {
2609                         int arg;
2610
2611                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2612                           abort ();
2613                         arg = a.arg[dp->precision_arg_index].a.a_int;
2614                         /* "A negative precision is taken as if the precision
2615                             were omitted."  */
2616                         if (arg >= 0)
2617                           {
2618                             precision = arg;
2619                             has_precision = 1;
2620                           }
2621                       }
2622                     else
2623                       {
2624                         const FCHAR_T *digitp = dp->precision_start + 1;
2625
2626                         precision = 0;
2627                         while (digitp != dp->precision_end)
2628                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2629                         has_precision = 1;
2630                       }
2631                   }
2632
2633                 /* POSIX specifies the default precision to be 6 for %f, %F,
2634                    %e, %E, but not for %g, %G.  Implementations appear to use
2635                    the same default precision also for %g, %G.  */
2636                 if (!has_precision)
2637                   precision = 6;
2638
2639                 /* Allocate a temporary buffer of sufficient size.  */
2640 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2641                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
2642 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
2643                 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
2644 # elif NEED_PRINTF_LONG_DOUBLE
2645                 tmp_length = LDBL_DIG + 1;
2646 # elif NEED_PRINTF_DOUBLE
2647                 tmp_length = DBL_DIG + 1;
2648 # else
2649                 tmp_length = 0;
2650 # endif
2651                 if (tmp_length < precision)
2652                   tmp_length = precision;
2653 # if NEED_PRINTF_LONG_DOUBLE
2654 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2655                 if (type == TYPE_LONGDOUBLE)
2656 #  endif
2657                   if (dp->conversion == 'f' || dp->conversion == 'F')
2658                     {
2659                       long double arg = a.arg[dp->arg_index].a.a_longdouble;
2660                       if (!(isnanl (arg) || arg + arg == arg))
2661                         {
2662                           /* arg is finite and nonzero.  */
2663                           int exponent = floorlog10l (arg < 0 ? -arg : arg);
2664                           if (exponent >= 0 && tmp_length < exponent + precision)
2665                             tmp_length = exponent + precision;
2666                         }
2667                     }
2668 # endif
2669 # if NEED_PRINTF_DOUBLE
2670 #  if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2671                 if (type == TYPE_DOUBLE)
2672 #  endif
2673                   if (dp->conversion == 'f' || dp->conversion == 'F')
2674                     {
2675                       double arg = a.arg[dp->arg_index].a.a_double;
2676                       if (!(isnand (arg) || arg + arg == arg))
2677                         {
2678                           /* arg is finite and nonzero.  */
2679                           int exponent = floorlog10 (arg < 0 ? -arg : arg);
2680                           if (exponent >= 0 && tmp_length < exponent + precision)
2681                             tmp_length = exponent + precision;
2682                         }
2683                     }
2684 # endif
2685                 /* Account for sign, decimal point etc. */
2686                 tmp_length = xsum (tmp_length, 12);
2687
2688                 if (tmp_length < width)
2689                   tmp_length = width;
2690
2691                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2692
2693                 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
2694                   tmp = tmpbuf;
2695                 else
2696                   {
2697                     size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
2698
2699                     if (size_overflow_p (tmp_memsize))
2700                       /* Overflow, would lead to out of memory.  */
2701                       goto out_of_memory;
2702                     tmp = (DCHAR_T *) malloc (tmp_memsize);
2703                     if (tmp == NULL)
2704                       /* Out of memory.  */
2705                       goto out_of_memory;
2706                   }
2707
2708                 pad_ptr = NULL;
2709                 p = tmp;
2710
2711 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
2712 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
2713                 if (type == TYPE_LONGDOUBLE)
2714 #  endif
2715                   {
2716                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
2717
2718                     if (isnanl (arg))
2719                       {
2720                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2721                           {
2722                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
2723                           }
2724                         else
2725                           {
2726                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
2727                           }
2728                       }
2729                     else
2730                       {
2731                         int sign = 0;
2732                         DECL_LONG_DOUBLE_ROUNDING
2733
2734                         BEGIN_LONG_DOUBLE_ROUNDING ();
2735
2736                         if (signbit (arg)) /* arg < 0.0L or negative zero */
2737                           {
2738                             sign = -1;
2739                             arg = -arg;
2740                           }
2741
2742                         if (sign < 0)
2743                           *p++ = '-';
2744                         else if (flags & FLAG_SHOWSIGN)
2745                           *p++ = '+';
2746                         else if (flags & FLAG_SPACE)
2747                           *p++ = ' ';
2748
2749                         if (arg > 0.0L && arg + arg == arg)
2750                           {
2751                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
2752                               {
2753                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
2754                               }
2755                             else
2756                               {
2757                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
2758                               }
2759                           }
2760                         else
2761                           {
2762 #  if NEED_PRINTF_LONG_DOUBLE
2763                             pad_ptr = p;
2764
2765                             if (dp->conversion == 'f' || dp->conversion == 'F')
2766                               {
2767                                 char *digits;
2768                                 size_t ndigits;
2769
2770                                 digits =
2771                                   scale10_round_decimal_long_double (arg, precision);
2772                                 if (digits == NULL)
2773                                   {
2774                                     END_LONG_DOUBLE_ROUNDING ();
2775                                     goto out_of_memory;
2776                                   }
2777                                 ndigits = strlen (digits);
2778
2779                                 if (ndigits > precision)
2780                                   do
2781                                     {
2782                                       --ndigits;
2783                                       *p++ = digits[ndigits];
2784                                     }
2785                                   while (ndigits > precision);
2786                                 else
2787                                   *p++ = '0';
2788                                 /* Here ndigits <= precision.  */
2789                                 if ((flags & FLAG_ALT) || precision > 0)
2790                                   {
2791                                     *p++ = decimal_point_char ();
2792                                     for (; precision > ndigits; precision--)
2793                                       *p++ = '0';
2794                                     while (ndigits > 0)
2795                                       {
2796                                         --ndigits;
2797                                         *p++ = digits[ndigits];
2798                                       }
2799                                   }
2800
2801                                 free (digits);
2802                               }
2803                             else if (dp->conversion == 'e' || dp->conversion == 'E')
2804                               {
2805                                 int exponent;
2806
2807                                 if (arg == 0.0L)
2808                                   {
2809                                     exponent = 0;
2810                                     *p++ = '0';
2811                                     if ((flags & FLAG_ALT) || precision > 0)
2812                                       {
2813                                         *p++ = decimal_point_char ();
2814                                         for (; precision > 0; precision--)
2815                                           *p++ = '0';
2816                                       }
2817                                   }
2818                                 else
2819                                   {
2820                                     /* arg > 0.0L.  */
2821                                     int adjusted;
2822                                     char *digits;
2823                                     size_t ndigits;
2824
2825                                     exponent = floorlog10l (arg);
2826                                     adjusted = 0;
2827                                     for (;;)
2828                                       {
2829                                         digits =
2830                                           scale10_round_decimal_long_double (arg,
2831                                                                              (int)precision - exponent);
2832                                         if (digits == NULL)
2833                                           {
2834                                             END_LONG_DOUBLE_ROUNDING ();
2835                                             goto out_of_memory;
2836                                           }
2837                                         ndigits = strlen (digits);
2838
2839                                         if (ndigits == precision + 1)
2840                                           break;
2841                                         if (ndigits < precision
2842                                             || ndigits > precision + 2)
2843                                           /* The exponent was not guessed
2844                                              precisely enough.  */
2845                                           abort ();
2846                                         if (adjusted)
2847                                           /* None of two values of exponent is
2848                                              the right one.  Prevent an endless
2849                                              loop.  */
2850                                           abort ();
2851                                         free (digits);
2852                                         if (ndigits == precision)
2853                                           exponent -= 1;
2854                                         else
2855                                           exponent += 1;
2856                                         adjusted = 1;
2857                                       }
2858
2859                                     /* Here ndigits = precision+1.  */
2860                                     *p++ = digits[--ndigits];
2861                                     if ((flags & FLAG_ALT) || precision > 0)
2862                                       {
2863                                         *p++ = decimal_point_char ();
2864                                         while (ndigits > 0)
2865                                           {
2866                                             --ndigits;
2867                                             *p++ = digits[ndigits];
2868                                           }
2869                                       }
2870
2871                                     free (digits);
2872                                   }
2873
2874                                 *p++ = dp->conversion; /* 'e' or 'E' */
2875 #   if WIDE_CHAR_VERSION
2876                                 {
2877                                   static const wchar_t decimal_format[] =
2878                                     { '%', '+', '.', '2', 'd', '\0' };
2879                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
2880                                 }
2881                                 while (*p != '\0')
2882                                   p++;
2883 #   else
2884                                 if (sizeof (DCHAR_T) == 1)
2885                                   {
2886                                     sprintf ((char *) p, "%+.2d", exponent);
2887                                     while (*p != '\0')
2888                                       p++;
2889                                   }
2890                                 else
2891                                   {
2892                                     char expbuf[6 + 1];
2893                                     const char *ep;
2894                                     sprintf (expbuf, "%+.2d", exponent);
2895                                     for (ep = expbuf; (*p = *ep) != '\0'; ep++)
2896                                       p++;
2897                                   }
2898 #   endif
2899                               }
2900                             else if (dp->conversion == 'g' || dp->conversion == 'G')
2901                               {
2902                                 if (precision == 0)
2903                                   precision = 1;
2904                                 /* precision >= 1.  */
2905
2906                                 if (arg == 0.0L)
2907                                   /* The exponent is 0, >= -4, < precision.
2908                                      Use fixed-point notation.  */
2909                                   {
2910                                     size_t ndigits = precision;
2911                                     /* Number of trailing zeroes that have to be
2912                                        dropped.  */
2913                                     size_t nzeroes =
2914                                       (flags & FLAG_ALT ? 0 : precision - 1);
2915
2916                                     --ndigits;
2917                                     *p++ = '0';
2918                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
2919                                       {
2920                                         *p++ = decimal_point_char ();
2921                                         while (ndigits > nzeroes)
2922                                           {
2923                                             --ndigits;
2924                                             *p++ = '0';
2925                                           }
2926                                       }
2927                                   }
2928                                 else
2929                                   {
2930                                     /* arg > 0.0L.  */
2931                                     int exponent;
2932                                     int adjusted;
2933                                     char *digits;
2934                                     size_t ndigits;
2935                                     size_t nzeroes;
2936
2937                                     exponent = floorlog10l (arg);
2938                                     adjusted = 0;
2939                                     for (;;)
2940                                       {
2941                                         digits =
2942                                           scale10_round_decimal_long_double (arg,
2943                                                                              (int)(precision - 1) - exponent);
2944                                         if (digits == NULL)
2945                                           {
2946                                             END_LONG_DOUBLE_ROUNDING ();
2947                                             goto out_of_memory;
2948                                           }
2949                                         ndigits = strlen (digits);
2950
2951                                         if (ndigits == precision)
2952                                           break;
2953                                         if (ndigits < precision - 1
2954                                             || ndigits > precision + 1)
2955                                           /* The exponent was not guessed
2956                                              precisely enough.  */
2957                                           abort ();
2958                                         if (adjusted)
2959                                           /* None of two values of exponent is
2960                                              the right one.  Prevent an endless
2961                                              loop.  */
2962                                           abort ();
2963                                         free (digits);
2964                                         if (ndigits < precision)
2965                                           exponent -= 1;
2966                                         else
2967                                           exponent += 1;
2968                                         adjusted = 1;
2969                                       }
2970                                     /* Here ndigits = precision.  */
2971
2972                                     /* Determine the number of trailing zeroes
2973                                        that have to be dropped.  */
2974                                     nzeroes = 0;
2975                                     if ((flags & FLAG_ALT) == 0)
2976                                       while (nzeroes < ndigits
2977                                              && digits[nzeroes] == '0')
2978                                         nzeroes++;
2979
2980                                     /* The exponent is now determined.  */
2981                                     if (exponent >= -4
2982                                         && exponent < (long)precision)
2983                                       {
2984                                         /* Fixed-point notation:
2985                                            max(exponent,0)+1 digits, then the
2986                                            decimal point, then the remaining
2987                                            digits without trailing zeroes.  */
2988                                         if (exponent >= 0)
2989                                           {
2990                                             size_t count = exponent + 1;
2991                                             /* Note: count <= precision = ndigits.  */
2992                                             for (; count > 0; count--)
2993                                               *p++ = digits[--ndigits];
2994                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
2995                                               {
2996                                                 *p++ = decimal_point_char ();
2997                                                 while (ndigits > nzeroes)
2998                                                   {
2999                                                     --ndigits;
3000                                                     *p++ = digits[ndigits];
3001                                                   }
3002                                               }
3003                                           }
3004                                         else
3005                                           {
3006                                             size_t count = -exponent - 1;
3007                                             *p++ = '0';
3008                                             *p++ = decimal_point_char ();
3009                                             for (; count > 0; count--)
3010                                               *p++ = '0';
3011                                             while (ndigits > nzeroes)
3012                                               {
3013                                                 --ndigits;
3014                                                 *p++ = digits[ndigits];
3015                                               }
3016                                           }
3017                                       }
3018                                     else
3019                                       {
3020                                         /* Exponential notation.  */
3021                                         *p++ = digits[--ndigits];
3022                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
3023                                           {
3024                                             *p++ = decimal_point_char ();
3025                                             while (ndigits > nzeroes)
3026                                               {
3027                                                 --ndigits;
3028                                                 *p++ = digits[ndigits];
3029                                               }
3030                                           }
3031                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3032 #   if WIDE_CHAR_VERSION
3033                                         {
3034                                           static const wchar_t decimal_format[] =
3035                                             { '%', '+', '.', '2', 'd', '\0' };
3036                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
3037                                         }
3038                                         while (*p != '\0')
3039                                           p++;
3040 #   else
3041                                         if (sizeof (DCHAR_T) == 1)
3042                                           {
3043                                             sprintf ((char *) p, "%+.2d", exponent);
3044                                             while (*p != '\0')
3045                                               p++;
3046                                           }
3047                                         else
3048                                           {
3049                                             char expbuf[6 + 1];
3050                                             const char *ep;
3051                                             sprintf (expbuf, "%+.2d", exponent);
3052                                             for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3053                                               p++;
3054                                           }
3055 #   endif
3056                                       }
3057
3058                                     free (digits);
3059                                   }
3060                               }
3061                             else
3062                               abort ();
3063 #  else
3064                             /* arg is finite.  */
3065                             abort ();
3066 #  endif
3067                           }
3068
3069                         END_LONG_DOUBLE_ROUNDING ();
3070                       }
3071                   }
3072 #  if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3073                 else
3074 #  endif
3075 # endif
3076 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3077                   {
3078                     double arg = a.arg[dp->arg_index].a.a_double;
3079
3080                     if (isnand (arg))
3081                       {
3082                         if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3083                           {
3084                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3085                           }
3086                         else
3087                           {
3088                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3089                           }
3090                       }
3091                     else
3092                       {
3093                         int sign = 0;
3094
3095                         if (signbit (arg)) /* arg < 0.0 or negative zero */
3096                           {
3097                             sign = -1;
3098                             arg = -arg;
3099                           }
3100
3101                         if (sign < 0)
3102                           *p++ = '-';
3103                         else if (flags & FLAG_SHOWSIGN)
3104                           *p++ = '+';
3105                         else if (flags & FLAG_SPACE)
3106                           *p++ = ' ';
3107
3108                         if (arg > 0.0 && arg + arg == arg)
3109                           {
3110                             if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3111                               {
3112                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3113                               }
3114                             else
3115                               {
3116                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3117                               }
3118                           }
3119                         else
3120                           {
3121 #  if NEED_PRINTF_DOUBLE
3122                             pad_ptr = p;
3123
3124                             if (dp->conversion == 'f' || dp->conversion == 'F')
3125                               {
3126                                 char *digits;
3127                                 size_t ndigits;
3128
3129                                 digits =
3130                                   scale10_round_decimal_double (arg, precision);
3131                                 if (digits == NULL)
3132                                   goto out_of_memory;
3133                                 ndigits = strlen (digits);
3134
3135                                 if (ndigits > precision)
3136                                   do
3137                                     {
3138                                       --ndigits;
3139                                       *p++ = digits[ndigits];
3140                                     }
3141                                   while (ndigits > precision);
3142                                 else
3143                                   *p++ = '0';
3144                                 /* Here ndigits <= precision.  */
3145                                 if ((flags & FLAG_ALT) || precision > 0)
3146                                   {
3147                                     *p++ = decimal_point_char ();
3148                                     for (; precision > ndigits; precision--)
3149                                       *p++ = '0';
3150                                     while (ndigits > 0)
3151                                       {
3152                                         --ndigits;
3153                                         *p++ = digits[ndigits];
3154                                       }
3155                                   }
3156
3157                                 free (digits);
3158                               }
3159                             else if (dp->conversion == 'e' || dp->conversion == 'E')
3160                               {
3161                                 int exponent;
3162
3163                                 if (arg == 0.0)
3164                                   {
3165                                     exponent = 0;
3166                                     *p++ = '0';
3167                                     if ((flags & FLAG_ALT) || precision > 0)
3168                                       {
3169                                         *p++ = decimal_point_char ();
3170                                         for (; precision > 0; precision--)
3171                                           *p++ = '0';
3172                                       }
3173                                   }
3174                                 else
3175                                   {
3176                                     /* arg > 0.0.  */
3177                                     int adjusted;
3178                                     char *digits;
3179                                     size_t ndigits;
3180
3181                                     exponent = floorlog10 (arg);
3182                                     adjusted = 0;
3183                                     for (;;)
3184                                       {
3185                                         digits =
3186                                           scale10_round_decimal_double (arg,
3187                                                                         (int)precision - exponent);
3188                                         if (digits == NULL)
3189                                           goto out_of_memory;
3190                                         ndigits = strlen (digits);
3191
3192                                         if (ndigits == precision + 1)
3193                                           break;
3194                                         if (ndigits < precision
3195                                             || ndigits > precision + 2)
3196                                           /* The exponent was not guessed
3197                                              precisely enough.  */
3198                                           abort ();
3199                                         if (adjusted)
3200                                           /* None of two values of exponent is
3201                                              the right one.  Prevent an endless
3202                                              loop.  */
3203                                           abort ();
3204                                         free (digits);
3205                                         if (ndigits == precision)
3206                                           exponent -= 1;
3207                                         else
3208                                           exponent += 1;
3209                                         adjusted = 1;
3210                                       }
3211
3212                                     /* Here ndigits = precision+1.  */
3213                                     *p++ = digits[--ndigits];
3214                                     if ((flags & FLAG_ALT) || precision > 0)
3215                                       {
3216                                         *p++ = decimal_point_char ();
3217                                         while (ndigits > 0)
3218                                           {
3219                                             --ndigits;
3220                                             *p++ = digits[ndigits];
3221                                           }
3222                                       }
3223
3224                                     free (digits);
3225                                   }
3226
3227                                 *p++ = dp->conversion; /* 'e' or 'E' */
3228 #   if WIDE_CHAR_VERSION
3229                                 {
3230                                   static const wchar_t decimal_format[] =
3231                                     /* Produce the same number of exponent digits
3232                                        as the native printf implementation.  */
3233 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3234                                     { '%', '+', '.', '3', 'd', '\0' };
3235 #    else
3236                                     { '%', '+', '.', '2', 'd', '\0' };
3237 #    endif
3238                                   SNPRINTF (p, 6 + 1, decimal_format, exponent);
3239                                 }
3240                                 while (*p != '\0')
3241                                   p++;
3242 #   else
3243                                 {
3244                                   static const char decimal_format[] =
3245                                     /* Produce the same number of exponent digits
3246                                        as the native printf implementation.  */
3247 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3248                                     "%+.3d";
3249 #    else
3250                                     "%+.2d";
3251 #    endif
3252                                   if (sizeof (DCHAR_T) == 1)
3253                                     {
3254                                       sprintf ((char *) p, decimal_format, exponent);
3255                                       while (*p != '\0')
3256                                         p++;
3257                                     }
3258                                   else
3259                                     {
3260                                       char expbuf[6 + 1];
3261                                       const char *ep;
3262                                       sprintf (expbuf, decimal_format, exponent);
3263                                       for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3264                                         p++;
3265                                     }
3266                                 }
3267 #   endif
3268                               }
3269                             else if (dp->conversion == 'g' || dp->conversion == 'G')
3270                               {
3271                                 if (precision == 0)
3272                                   precision = 1;
3273                                 /* precision >= 1.  */
3274
3275                                 if (arg == 0.0)
3276                                   /* The exponent is 0, >= -4, < precision.
3277                                      Use fixed-point notation.  */
3278                                   {
3279                                     size_t ndigits = precision;
3280                                     /* Number of trailing zeroes that have to be
3281                                        dropped.  */
3282                                     size_t nzeroes =
3283                                       (flags & FLAG_ALT ? 0 : precision - 1);
3284
3285                                     --ndigits;
3286                                     *p++ = '0';
3287                                     if ((flags & FLAG_ALT) || ndigits > nzeroes)
3288                                       {
3289                                         *p++ = decimal_point_char ();
3290                                         while (ndigits > nzeroes)
3291                                           {
3292                                             --ndigits;
3293                                             *p++ = '0';
3294                                           }
3295                                       }
3296                                   }
3297                                 else
3298                                   {
3299                                     /* arg > 0.0.  */
3300                                     int exponent;
3301                                     int adjusted;
3302                                     char *digits;
3303                                     size_t ndigits;
3304                                     size_t nzeroes;
3305
3306                                     exponent = floorlog10 (arg);
3307                                     adjusted = 0;
3308                                     for (;;)
3309                                       {
3310                                         digits =
3311                                           scale10_round_decimal_double (arg,
3312                                                                         (int)(precision - 1) - exponent);
3313                                         if (digits == NULL)
3314                                           goto out_of_memory;
3315                                         ndigits = strlen (digits);
3316
3317                                         if (ndigits == precision)
3318                                           break;
3319                                         if (ndigits < precision - 1
3320                                             || ndigits > precision + 1)
3321                                           /* The exponent was not guessed
3322                                              precisely enough.  */
3323                                           abort ();
3324                                         if (adjusted)
3325                                           /* None of two values of exponent is
3326                                              the right one.  Prevent an endless
3327                                              loop.  */
3328                                           abort ();
3329                                         free (digits);
3330                                         if (ndigits < precision)
3331                                           exponent -= 1;
3332                                         else
3333                                           exponent += 1;
3334                                         adjusted = 1;
3335                                       }
3336                                     /* Here ndigits = precision.  */
3337
3338                                     /* Determine the number of trailing zeroes
3339                                        that have to be dropped.  */
3340                                     nzeroes = 0;
3341                                     if ((flags & FLAG_ALT) == 0)
3342                                       while (nzeroes < ndigits
3343                                              && digits[nzeroes] == '0')
3344                                         nzeroes++;
3345
3346                                     /* The exponent is now determined.  */
3347                                     if (exponent >= -4
3348                                         && exponent < (long)precision)
3349                                       {
3350                                         /* Fixed-point notation:
3351                                            max(exponent,0)+1 digits, then the
3352                                            decimal point, then the remaining
3353                                            digits without trailing zeroes.  */
3354                                         if (exponent >= 0)
3355                                           {
3356                                             size_t count = exponent + 1;
3357                                             /* Note: count <= precision = ndigits.  */
3358                                             for (; count > 0; count--)
3359                                               *p++ = digits[--ndigits];
3360                                             if ((flags & FLAG_ALT) || ndigits > nzeroes)
3361                                               {
3362                                                 *p++ = decimal_point_char ();
3363                                                 while (ndigits > nzeroes)
3364                                                   {
3365                                                     --ndigits;
3366                                                     *p++ = digits[ndigits];
3367                                                   }
3368                                               }
3369                                           }
3370                                         else
3371                                           {
3372                                             size_t count = -exponent - 1;
3373                                             *p++ = '0';
3374                                             *p++ = decimal_point_char ();
3375                                             for (; count > 0; count--)
3376                                               *p++ = '0';
3377                                             while (ndigits > nzeroes)
3378                                               {
3379                                                 --ndigits;
3380                                                 *p++ = digits[ndigits];
3381                                               }
3382                                           }
3383                                       }
3384                                     else
3385                                       {
3386                                         /* Exponential notation.  */
3387                                         *p++ = digits[--ndigits];
3388                                         if ((flags & FLAG_ALT) || ndigits > nzeroes)
3389                                           {
3390                                             *p++ = decimal_point_char ();
3391                                             while (ndigits > nzeroes)
3392                                               {
3393                                                 --ndigits;
3394                                                 *p++ = digits[ndigits];
3395                                               }
3396                                           }
3397                                         *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
3398 #   if WIDE_CHAR_VERSION
3399                                         {
3400                                           static const wchar_t decimal_format[] =
3401                                             /* Produce the same number of exponent digits
3402                                                as the native printf implementation.  */
3403 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3404                                             { '%', '+', '.', '3', 'd', '\0' };
3405 #    else
3406                                             { '%', '+', '.', '2', 'd', '\0' };
3407 #    endif
3408                                           SNPRINTF (p, 6 + 1, decimal_format, exponent);
3409                                         }
3410                                         while (*p != '\0')
3411                                           p++;
3412 #   else
3413                                         {
3414                                           static const char decimal_format[] =
3415                                             /* Produce the same number of exponent digits
3416                                                as the native printf implementation.  */
3417 #    if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3418                                             "%+.3d";
3419 #    else
3420                                             "%+.2d";
3421 #    endif
3422                                           if (sizeof (DCHAR_T) == 1)
3423                                             {
3424                                               sprintf ((char *) p, decimal_format, exponent);
3425                                               while (*p != '\0')
3426                                                 p++;
3427                                             }
3428                                           else
3429                                             {
3430                                               char expbuf[6 + 1];
3431                                               const char *ep;
3432                                               sprintf (expbuf, decimal_format, exponent);
3433                                               for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3434                                                 p++;
3435                                             }
3436                                         }
3437 #   endif
3438                                       }
3439
3440                                     free (digits);
3441                                   }
3442                               }
3443                             else
3444                               abort ();
3445 #  else
3446                             /* arg is finite.  */
3447                             if (!(arg == 0.0))
3448                               abort ();
3449
3450                             pad_ptr = p;
3451
3452                             if (dp->conversion == 'f' || dp->conversion == 'F')
3453                               {
3454                                 *p++ = '0';
3455                                 if ((flags & FLAG_ALT) || precision > 0)
3456                                   {
3457                                     *p++ = decimal_point_char ();
3458                                     for (; precision > 0; precision--)
3459                                       *p++ = '0';
3460                                   }
3461                               }
3462                             else if (dp->conversion == 'e' || dp->conversion == 'E')
3463                               {
3464                                 *p++ = '0';
3465                                 if ((flags & FLAG_ALT) || precision > 0)
3466                                   {
3467                                     *p++ = decimal_point_char ();
3468                                     for (; precision > 0; precision--)
3469                                       *p++ = '0';
3470                                   }
3471                                 *p++ = dp->conversion; /* 'e' or 'E' */
3472                                 *p++ = '+';
3473                                 /* Produce the same number of exponent digits as
3474                                    the native printf implementation.  */
3475 #   if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3476                                 *p++ = '0';
3477 #   endif
3478                                 *p++ = '0';
3479                                 *p++ = '0';
3480                               }
3481                             else if (dp->conversion == 'g' || dp->conversion == 'G')
3482                               {
3483                                 *p++ = '0';
3484                                 if (flags & FLAG_ALT)
3485                                   {
3486                                     size_t ndigits =
3487                                       (precision > 0 ? precision - 1 : 0);
3488                                     *p++ = decimal_point_char ();
3489                                     for (; ndigits > 0; --ndigits)
3490                                       *p++ = '0';
3491                                   }
3492                               }
3493                             else
3494                               abort ();
3495 #  endif
3496                           }
3497                       }
3498                   }
3499 # endif
3500
3501                 /* The generated string now extends from tmp to p, with the
3502                    zero padding insertion point being at pad_ptr.  */
3503                 if (has_width && p - tmp < width)
3504                   {
3505                     size_t pad = width - (p - tmp);
3506                     DCHAR_T *end = p + pad;
3507
3508                     if (flags & FLAG_LEFT)
3509                       {
3510                         /* Pad with spaces on the right.  */
3511                         for (; pad > 0; pad--)
3512                           *p++ = ' ';
3513                       }
3514                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3515                       {
3516                         /* Pad with zeroes.  */
3517                         DCHAR_T *q = end;
3518
3519                         while (p > pad_ptr)
3520                           *--q = *--p;
3521                         for (; pad > 0; pad--)
3522                           *p++ = '0';
3523                       }
3524                     else
3525                       {
3526                         /* Pad with spaces on the left.  */
3527                         DCHAR_T *q = end;
3528
3529                         while (p > tmp)
3530                           *--q = *--p;
3531                         for (; pad > 0; pad--)
3532                           *p++ = ' ';
3533                       }
3534
3535                     p = end;
3536                   }
3537
3538                 {
3539                   size_t count = p - tmp;
3540
3541                   if (count >= tmp_length)
3542                     /* tmp_length was incorrectly calculated - fix the
3543                        code above!  */
3544                     abort ();
3545
3546                   /* Make room for the result.  */
3547                   if (count >= allocated - length)
3548                     {
3549                       size_t n = xsum (length, count);
3550
3551                       ENSURE_ALLOCATION (n);
3552                     }
3553
3554                   /* Append the result.  */
3555                   memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3556                   if (tmp != tmpbuf)
3557                     free (tmp);
3558                   length += count;
3559                 }
3560               }
3561 #endif
3562             else
3563               {
3564                 arg_type type = a.arg[dp->arg_index].type;
3565                 int flags = dp->flags;
3566 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3567                 int has_width;
3568                 size_t width;
3569 #endif
3570 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3571                 int has_precision;
3572                 size_t precision;
3573 #endif
3574 #if NEED_PRINTF_UNBOUNDED_PRECISION
3575                 int prec_ourselves;
3576 #else
3577 #               define prec_ourselves 0
3578 #endif
3579 #if NEED_PRINTF_FLAG_LEFTADJUST
3580 #               define pad_ourselves 1
3581 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3582                 int pad_ourselves;
3583 #else
3584 #               define pad_ourselves 0
3585 #endif
3586                 TCHAR_T *fbp;
3587                 unsigned int prefix_count;
3588                 int prefixes[2];
3589 #if !USE_SNPRINTF
3590                 size_t tmp_length;
3591                 TCHAR_T tmpbuf[700];
3592                 TCHAR_T *tmp;
3593 #endif
3594
3595 #if !USE_SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
3596                 has_width = 0;
3597                 width = 0;
3598                 if (dp->width_start != dp->width_end)
3599                   {
3600                     if (dp->width_arg_index != ARG_NONE)
3601                       {
3602                         int arg;
3603
3604                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3605                           abort ();
3606                         arg = a.arg[dp->width_arg_index].a.a_int;
3607                         if (arg < 0)
3608                           {
3609                             /* "A negative field width is taken as a '-' flag
3610                                 followed by a positive field width."  */
3611                             flags |= FLAG_LEFT;
3612                             width = (unsigned int) (-arg);
3613                           }
3614                         else
3615                           width = arg;
3616                       }
3617                     else
3618                       {
3619                         const FCHAR_T *digitp = dp->width_start;
3620
3621                         do
3622                           width = xsum (xtimes (width, 10), *digitp++ - '0');
3623                         while (digitp != dp->width_end);
3624                       }
3625                     has_width = 1;
3626                   }
3627 #endif
3628
3629 #if !USE_SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
3630                 has_precision = 0;
3631                 precision = 6;
3632                 if (dp->precision_start != dp->precision_end)
3633                   {
3634                     if (dp->precision_arg_index != ARG_NONE)
3635                       {
3636                         int arg;
3637
3638                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3639                           abort ();
3640                         arg = a.arg[dp->precision_arg_index].a.a_int;
3641                         /* "A negative precision is taken as if the precision
3642                             were omitted."  */
3643                         if (arg >= 0)
3644                           {
3645                             precision = arg;
3646                             has_precision = 1;
3647                           }
3648                       }
3649                     else
3650                       {
3651                         const FCHAR_T *digitp = dp->precision_start + 1;
3652
3653                         precision = 0;
3654                         while (digitp != dp->precision_end)
3655                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3656                         has_precision = 1;
3657                       }
3658                   }
3659 #endif
3660
3661                 /* Decide whether to handle the precision ourselves.  */
3662 #if NEED_PRINTF_UNBOUNDED_PRECISION
3663                 switch (dp->conversion)
3664                   {
3665                   case 'd': case 'i': case 'u':
3666                   case 'o':
3667                   case 'x': case 'X': case 'p':
3668                     prec_ourselves = has_precision && (precision > 0);
3669                     break;
3670                   default:
3671                     prec_ourselves = 0;
3672                     break;
3673                   }
3674 #endif
3675
3676                 /* Decide whether to perform the padding ourselves.  */
3677 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
3678                 switch (dp->conversion)
3679                   {
3680 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
3681                   /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
3682                      to perform the padding after this conversion.  Functions
3683                      with unistdio extensions perform the padding based on
3684                      character count rather than element count.  */
3685                   case 'c': case 's':
3686 # endif
3687 # if NEED_PRINTF_FLAG_ZERO
3688                   case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
3689                   case 'a': case 'A':
3690 # endif
3691                     pad_ourselves = 1;
3692                     break;
3693                   default:
3694                     pad_ourselves = prec_ourselves;
3695                     break;
3696                   }
3697 #endif
3698
3699 #if !USE_SNPRINTF
3700                 /* Allocate a temporary buffer of sufficient size for calling
3701                    sprintf.  */
3702                 {
3703                   switch (dp->conversion)
3704                     {
3705
3706                     case 'd': case 'i': case 'u':
3707 # if HAVE_LONG_LONG_INT
3708                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3709                         tmp_length =
3710                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3711                                           * 0.30103 /* binary -> decimal */
3712                                          )
3713                           + 1; /* turn floor into ceil */
3714                       else
3715 # endif
3716                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3717                         tmp_length =
3718                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3719                                           * 0.30103 /* binary -> decimal */
3720                                          )
3721                           + 1; /* turn floor into ceil */
3722                       else
3723                         tmp_length =
3724                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3725                                           * 0.30103 /* binary -> decimal */
3726                                          )
3727                           + 1; /* turn floor into ceil */
3728                       if (tmp_length < precision)
3729                         tmp_length = precision;
3730                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
3731                       tmp_length = xsum (tmp_length, tmp_length);
3732                       /* Add 1, to account for a leading sign.  */
3733                       tmp_length = xsum (tmp_length, 1);
3734                       break;
3735
3736                     case 'o':
3737 # if HAVE_LONG_LONG_INT
3738                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3739                         tmp_length =
3740                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3741                                           * 0.333334 /* binary -> octal */
3742                                          )
3743                           + 1; /* turn floor into ceil */
3744                       else
3745 # endif
3746                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3747                         tmp_length =
3748                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3749                                           * 0.333334 /* binary -> octal */
3750                                          )
3751                           + 1; /* turn floor into ceil */
3752                       else
3753                         tmp_length =
3754                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3755                                           * 0.333334 /* binary -> octal */
3756                                          )
3757                           + 1; /* turn floor into ceil */
3758                       if (tmp_length < precision)
3759                         tmp_length = precision;
3760                       /* Add 1, to account for a leading sign.  */
3761                       tmp_length = xsum (tmp_length, 1);
3762                       break;
3763
3764                     case 'x': case 'X':
3765 # if HAVE_LONG_LONG_INT
3766                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
3767                         tmp_length =
3768                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
3769                                           * 0.25 /* binary -> hexadecimal */
3770                                          )
3771                           + 1; /* turn floor into ceil */
3772                       else
3773 # endif
3774                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
3775                         tmp_length =
3776                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
3777                                           * 0.25 /* binary -> hexadecimal */
3778                                          )
3779                           + 1; /* turn floor into ceil */
3780                       else
3781                         tmp_length =
3782                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
3783                                           * 0.25 /* binary -> hexadecimal */
3784                                          )
3785                           + 1; /* turn floor into ceil */
3786                       if (tmp_length < precision)
3787                         tmp_length = precision;
3788                       /* Add 2, to account for a leading sign or alternate form.  */
3789                       tmp_length = xsum (tmp_length, 2);
3790                       break;
3791
3792                     case 'f': case 'F':
3793                       if (type == TYPE_LONGDOUBLE)
3794                         tmp_length =
3795                           (unsigned int) (LDBL_MAX_EXP
3796                                           * 0.30103 /* binary -> decimal */
3797                                           * 2 /* estimate for FLAG_GROUP */
3798                                          )
3799                           + 1 /* turn floor into ceil */
3800                           + 10; /* sign, decimal point etc. */
3801                       else
3802                         tmp_length =
3803                           (unsigned int) (DBL_MAX_EXP
3804                                           * 0.30103 /* binary -> decimal */
3805                                           * 2 /* estimate for FLAG_GROUP */
3806                                          )
3807                           + 1 /* turn floor into ceil */
3808                           + 10; /* sign, decimal point etc. */
3809                       tmp_length = xsum (tmp_length, precision);
3810                       break;
3811
3812                     case 'e': case 'E': case 'g': case 'G':
3813                       tmp_length =
3814                         12; /* sign, decimal point, exponent etc. */
3815                       tmp_length = xsum (tmp_length, precision);
3816                       break;
3817
3818                     case 'a': case 'A':
3819                       if (type == TYPE_LONGDOUBLE)
3820                         tmp_length =
3821                           (unsigned int) (LDBL_DIG
3822                                           * 0.831 /* decimal -> hexadecimal */
3823                                          )
3824                           + 1; /* turn floor into ceil */
3825                       else
3826                         tmp_length =
3827                           (unsigned int) (DBL_DIG
3828                                           * 0.831 /* decimal -> hexadecimal */
3829                                          )
3830                           + 1; /* turn floor into ceil */
3831                       if (tmp_length < precision)
3832                         tmp_length = precision;
3833                       /* Account for sign, decimal point etc. */
3834                       tmp_length = xsum (tmp_length, 12);
3835                       break;
3836
3837                     case 'c':
3838 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
3839                       if (type == TYPE_WIDE_CHAR)
3840                         tmp_length = MB_CUR_MAX;
3841                       else
3842 # endif
3843                         tmp_length = 1;
3844                       break;
3845
3846                     case 's':
3847 # if HAVE_WCHAR_T
3848                       if (type == TYPE_WIDE_STRING)
3849                         {
3850                           tmp_length =
3851                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
3852
3853 #  if !WIDE_CHAR_VERSION
3854                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
3855 #  endif
3856                         }
3857                       else
3858 # endif
3859                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
3860                       break;
3861
3862                     case 'p':
3863                       tmp_length =
3864                         (unsigned int) (sizeof (void *) * CHAR_BIT
3865                                         * 0.25 /* binary -> hexadecimal */
3866                                        )
3867                           + 1 /* turn floor into ceil */
3868                           + 2; /* account for leading 0x */
3869                       break;
3870
3871                     default:
3872                       abort ();
3873                     }
3874
3875                   if (!pad_ourselves)
3876                     {
3877 # if ENABLE_UNISTDIO
3878                       /* Padding considers the number of characters, therefore
3879                          the number of elements after padding may be
3880                            > max (tmp_length, width)
3881                          but is certainly
3882                            <= tmp_length + width.  */
3883                       tmp_length = xsum (tmp_length, width);
3884 # else
3885                       /* Padding considers the number of elements,
3886                          says POSIX.  */
3887                       if (tmp_length < width)
3888                         tmp_length = width;
3889 # endif
3890                     }
3891
3892                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3893                 }
3894
3895                 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
3896                   tmp = tmpbuf;
3897                 else
3898                   {
3899                     size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
3900
3901                     if (size_overflow_p (tmp_memsize))
3902                       /* Overflow, would lead to out of memory.  */
3903                       goto out_of_memory;
3904                     tmp = (TCHAR_T *) malloc (tmp_memsize);
3905                     if (tmp == NULL)
3906                       /* Out of memory.  */
3907                       goto out_of_memory;
3908                   }
3909 #endif
3910
3911                 /* Construct the format string for calling snprintf or
3912                    sprintf.  */
3913                 fbp = buf;
3914                 *fbp++ = '%';
3915 #if NEED_PRINTF_FLAG_GROUPING
3916                 /* The underlying implementation doesn't support the ' flag.
3917                    Produce no grouping characters in this case; this is
3918                    acceptable because the grouping is locale dependent.  */
3919 #else
3920                 if (flags & FLAG_GROUP)
3921                   *fbp++ = '\'';
3922 #endif
3923                 if (flags & FLAG_LEFT)
3924                   *fbp++ = '-';
3925                 if (flags & FLAG_SHOWSIGN)
3926                   *fbp++ = '+';
3927                 if (flags & FLAG_SPACE)
3928                   *fbp++ = ' ';
3929                 if (flags & FLAG_ALT)
3930                   *fbp++ = '#';
3931                 if (!pad_ourselves)
3932                   {
3933                     if (flags & FLAG_ZERO)
3934                       *fbp++ = '0';
3935                     if (dp->width_start != dp->width_end)
3936                       {
3937                         size_t n = dp->width_end - dp->width_start;
3938                         /* The width specification is known to consist only
3939                            of standard ASCII characters.  */
3940                         if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3941                           {
3942                             memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
3943                             fbp += n;
3944                           }
3945                         else
3946                           {
3947                             const FCHAR_T *mp = dp->width_start;
3948                             do
3949                               *fbp++ = (unsigned char) *mp++;
3950                             while (--n > 0);
3951                           }
3952                       }
3953                   }
3954                 if (!prec_ourselves)
3955                   {
3956                     if (dp->precision_start != dp->precision_end)
3957                       {
3958                         size_t n = dp->precision_end - dp->precision_start;
3959                         /* The precision specification is known to consist only
3960                            of standard ASCII characters.  */
3961                         if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
3962                           {
3963                             memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
3964                             fbp += n;
3965                           }
3966                         else
3967                           {
3968                             const FCHAR_T *mp = dp->precision_start;
3969                             do
3970                               *fbp++ = (unsigned char) *mp++;
3971                             while (--n > 0);
3972                           }
3973                       }
3974                   }
3975
3976                 switch (type)
3977                   {
3978 #if HAVE_LONG_LONG_INT
3979                   case TYPE_LONGLONGINT:
3980                   case TYPE_ULONGLONGINT:
3981 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
3982                     *fbp++ = 'I';
3983                     *fbp++ = '6';
3984                     *fbp++ = '4';
3985                     break;
3986 # else
3987                     *fbp++ = 'l';
3988                     /*FALLTHROUGH*/
3989 # endif
3990 #endif
3991                   case TYPE_LONGINT:
3992                   case TYPE_ULONGINT:
3993 #if HAVE_WINT_T
3994                   case TYPE_WIDE_CHAR:
3995 #endif
3996 #if HAVE_WCHAR_T
3997                   case TYPE_WIDE_STRING:
3998 #endif
3999                     *fbp++ = 'l';
4000                     break;
4001                   case TYPE_LONGDOUBLE:
4002                     *fbp++ = 'L';
4003                     break;
4004                   default:
4005                     break;
4006                   }
4007 #if NEED_PRINTF_DIRECTIVE_F
4008                 if (dp->conversion == 'F')
4009                   *fbp = 'f';
4010                 else
4011 #endif
4012                   *fbp = dp->conversion;
4013 #if USE_SNPRINTF
4014 # if !(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
4015                 fbp[1] = '%';
4016                 fbp[2] = 'n';
4017                 fbp[3] = '\0';
4018 # else
4019                 /* On glibc2 systems from glibc >= 2.3 - probably also older
4020                    ones - we know that snprintf's returns value conforms to
4021                    ISO C 99: the gl_SNPRINTF_DIRECTIVE_N test passes.
4022                    Therefore we can avoid using %n in this situation.
4023                    On glibc2 systems from 2004-10-18 or newer, the use of %n
4024                    in format strings in writable memory may crash the program
4025                    (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
4026                    in this situation.  */
4027                 /* On native Win32 systems (such as mingw), we can avoid using
4028                    %n because:
4029                      - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
4030                        snprintf does not write more than the specified number
4031                        of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
4032                        '4', '5', '6' into buf, not '4', '5', '\0'.)
4033                      - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
4034                        allows us to recognize the case of an insufficient
4035                        buffer size: it returns -1 in this case.
4036                    On native Win32 systems (such as mingw) where the OS is
4037                    Windows Vista, the use of %n in format strings by default
4038                    crashes the program. See
4039                      <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
4040                      <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
4041                    So we should avoid %n in this situation.  */
4042                 fbp[1] = '\0';
4043 # endif
4044 #else
4045                 fbp[1] = '\0';
4046 #endif
4047
4048                 /* Construct the arguments for calling snprintf or sprintf.  */
4049                 prefix_count = 0;
4050                 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
4051                   {
4052                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4053                       abort ();
4054                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
4055                   }
4056                 if (dp->precision_arg_index != ARG_NONE)
4057                   {
4058                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4059                       abort ();
4060                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
4061                   }
4062
4063 #if USE_SNPRINTF
4064                 /* The SNPRINTF result is appended after result[0..length].
4065                    The latter is an array of DCHAR_T; SNPRINTF appends an
4066                    array of TCHAR_T to it.  This is possible because
4067                    sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
4068                    alignof (TCHAR_T) <= alignof (DCHAR_T).  */
4069 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
4070                 /* Ensure that maxlen below will be >= 2.  Needed on BeOS,
4071                    where an snprintf() with maxlen==1 acts like sprintf().  */
4072                 ENSURE_ALLOCATION (xsum (length,
4073                                          (2 + TCHARS_PER_DCHAR - 1)
4074                                          / TCHARS_PER_DCHAR));
4075                 /* Prepare checking whether snprintf returns the count
4076                    via %n.  */
4077                 *(TCHAR_T *) (result + length) = '\0';
4078 #endif
4079
4080                 for (;;)
4081                   {
4082                     int count = -1;
4083
4084 #if USE_SNPRINTF
4085                     int retcount = 0;
4086                     size_t maxlen = allocated - length;
4087                     /* SNPRINTF can fail if its second argument is
4088                        > INT_MAX.  */
4089                     if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
4090                       maxlen = INT_MAX / TCHARS_PER_DCHAR;
4091                     maxlen = maxlen * TCHARS_PER_DCHAR;
4092 # define SNPRINTF_BUF(arg) \
4093                     switch (prefix_count)                                   \
4094                       {                                                     \
4095                       case 0:                                               \
4096                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4097                                              maxlen, buf,                   \
4098                                              arg, &count);                  \
4099                         break;                                              \
4100                       case 1:                                               \
4101                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4102                                              maxlen, buf,                   \
4103                                              prefixes[0], arg, &count);     \
4104                         break;                                              \
4105                       case 2:                                               \
4106                         retcount = SNPRINTF ((TCHAR_T *) (result + length), \
4107                                              maxlen, buf,                   \
4108                                              prefixes[0], prefixes[1], arg, \
4109                                              &count);                       \
4110                         break;                                              \
4111                       default:                                              \
4112                         abort ();                                           \
4113                       }
4114 #else
4115 # define SNPRINTF_BUF(arg) \
4116                     switch (prefix_count)                                   \
4117                       {                                                     \
4118                       case 0:                                               \
4119                         count = sprintf (tmp, buf, arg);                    \
4120                         break;                                              \
4121                       case 1:                                               \
4122                         count = sprintf (tmp, buf, prefixes[0], arg);       \
4123                         break;                                              \
4124                       case 2:                                               \
4125                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
4126                                          arg);                              \
4127                         break;                                              \
4128                       default:                                              \
4129                         abort ();                                           \
4130                       }
4131 #endif
4132
4133                     switch (type)
4134                       {
4135                       case TYPE_SCHAR:
4136                         {
4137                           int arg = a.arg[dp->arg_index].a.a_schar;
4138                           SNPRINTF_BUF (arg);
4139                         }
4140                         break;
4141                       case TYPE_UCHAR:
4142                         {
4143                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
4144                           SNPRINTF_BUF (arg);
4145                         }
4146                         break;
4147                       case TYPE_SHORT:
4148                         {
4149                           int arg = a.arg[dp->arg_index].a.a_short;
4150                           SNPRINTF_BUF (arg);
4151                         }
4152                         break;
4153                       case TYPE_USHORT:
4154                         {
4155                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
4156                           SNPRINTF_BUF (arg);
4157                         }
4158                         break;
4159                       case TYPE_INT:
4160                         {
4161                           int arg = a.arg[dp->arg_index].a.a_int;
4162                           SNPRINTF_BUF (arg);
4163                         }
4164                         break;
4165                       case TYPE_UINT:
4166                         {
4167                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
4168                           SNPRINTF_BUF (arg);
4169                         }
4170                         break;
4171                       case TYPE_LONGINT:
4172                         {
4173                           long int arg = a.arg[dp->arg_index].a.a_longint;
4174                           SNPRINTF_BUF (arg);
4175                         }
4176                         break;
4177                       case TYPE_ULONGINT:
4178                         {
4179                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
4180                           SNPRINTF_BUF (arg);
4181                         }
4182                         break;
4183 #if HAVE_LONG_LONG_INT
4184                       case TYPE_LONGLONGINT:
4185                         {
4186                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
4187                           SNPRINTF_BUF (arg);
4188                         }
4189                         break;
4190                       case TYPE_ULONGLONGINT:
4191                         {
4192                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
4193                           SNPRINTF_BUF (arg);
4194                         }
4195                         break;
4196 #endif
4197                       case TYPE_DOUBLE:
4198                         {
4199                           double arg = a.arg[dp->arg_index].a.a_double;
4200                           SNPRINTF_BUF (arg);
4201                         }
4202                         break;
4203                       case TYPE_LONGDOUBLE:
4204                         {
4205                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
4206                           SNPRINTF_BUF (arg);
4207                         }
4208                         break;
4209                       case TYPE_CHAR:
4210                         {
4211                           int arg = a.arg[dp->arg_index].a.a_char;
4212                           SNPRINTF_BUF (arg);
4213                         }
4214                         break;
4215 #if HAVE_WINT_T
4216                       case TYPE_WIDE_CHAR:
4217                         {
4218                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
4219                           SNPRINTF_BUF (arg);
4220                         }
4221                         break;
4222 #endif
4223                       case TYPE_STRING:
4224                         {
4225                           const char *arg = a.arg[dp->arg_index].a.a_string;
4226                           SNPRINTF_BUF (arg);
4227                         }
4228                         break;
4229 #if HAVE_WCHAR_T
4230                       case TYPE_WIDE_STRING:
4231                         {
4232                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
4233                           SNPRINTF_BUF (arg);
4234                         }
4235                         break;
4236 #endif
4237                       case TYPE_POINTER:
4238                         {
4239                           void *arg = a.arg[dp->arg_index].a.a_pointer;
4240                           SNPRINTF_BUF (arg);
4241                         }
4242                         break;
4243                       default:
4244                         abort ();
4245                       }
4246
4247 #if USE_SNPRINTF
4248                     /* Portability: Not all implementations of snprintf()
4249                        are ISO C 99 compliant.  Determine the number of
4250                        bytes that snprintf() has produced or would have
4251                        produced.  */
4252                     if (count >= 0)
4253                       {
4254                         /* Verify that snprintf() has NUL-terminated its
4255                            result.  */
4256                         if (count < maxlen
4257                             && ((TCHAR_T *) (result + length)) [count] != '\0')
4258                           abort ();
4259                         /* Portability hack.  */
4260                         if (retcount > count)
4261                           count = retcount;
4262                       }
4263                     else
4264                       {
4265                         /* snprintf() doesn't understand the '%n'
4266                            directive.  */
4267                         if (fbp[1] != '\0')
4268                           {
4269                             /* Don't use the '%n' directive; instead, look
4270                                at the snprintf() return value.  */
4271                             fbp[1] = '\0';
4272                             continue;
4273                           }
4274                         else
4275                           {
4276                             /* Look at the snprintf() return value.  */
4277                             if (retcount < 0)
4278                               {
4279                                 /* HP-UX 10.20 snprintf() is doubly deficient:
4280                                    It doesn't understand the '%n' directive,
4281                                    *and* it returns -1 (rather than the length
4282                                    that would have been required) when the
4283                                    buffer is too small.  */
4284                                 size_t bigger_need =
4285                                   xsum (xtimes (allocated, 2), 12);
4286                                 ENSURE_ALLOCATION (bigger_need);
4287                                 continue;
4288                               }
4289                             else
4290                               count = retcount;
4291                           }
4292                       }
4293 #endif
4294
4295                     /* Attempt to handle failure.  */
4296                     if (count < 0)
4297                       {
4298                         if (!(result == resultbuf || result == NULL))
4299                           free (result);
4300                         if (buf_malloced != NULL)
4301                           free (buf_malloced);
4302                         CLEANUP ();
4303                         errno = EINVAL;
4304                         return NULL;
4305                       }
4306
4307 #if USE_SNPRINTF
4308                     /* Handle overflow of the allocated buffer.
4309                        If such an overflow occurs, a C99 compliant snprintf()
4310                        returns a count >= maxlen.  However, a non-compliant
4311                        snprintf() function returns only count = maxlen - 1.  To
4312                        cover both cases, test whether count >= maxlen - 1.  */
4313                     if ((unsigned int) count + 1 >= maxlen)
4314                       {
4315                         /* If maxlen already has attained its allowed maximum,
4316                            allocating more memory will not increase maxlen.
4317                            Instead of looping, bail out.  */
4318                         if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
4319                           goto overflow;
4320                         else
4321                           {
4322                             /* Need at least (count + 1) * sizeof (TCHAR_T)
4323                                bytes.  (The +1 is for the trailing NUL.)
4324                                But ask for (count + 2) * sizeof (TCHAR_T)
4325                                bytes, so that in the next round, we likely get
4326                                  maxlen > (unsigned int) count + 1
4327                                and so we don't get here again.
4328                                And allocate proportionally, to avoid looping
4329                                eternally if snprintf() reports a too small
4330                                count.  */
4331                             size_t n =
4332                               xmax (xsum (length,
4333                                           ((unsigned int) count + 2
4334                                            + TCHARS_PER_DCHAR - 1)
4335                                           / TCHARS_PER_DCHAR),
4336                                     xtimes (allocated, 2));
4337
4338                             ENSURE_ALLOCATION (n);
4339                             continue;
4340                           }
4341                       }
4342 #endif
4343
4344 #if NEED_PRINTF_UNBOUNDED_PRECISION
4345                     if (prec_ourselves)
4346                       {
4347                         /* Handle the precision.  */
4348                         TCHAR_T *prec_ptr =
4349 # if USE_SNPRINTF
4350                           (TCHAR_T *) (result + length);
4351 # else
4352                           tmp;
4353 # endif
4354                         size_t prefix_count;
4355                         size_t move;
4356
4357                         prefix_count = 0;
4358                         /* Put the additional zeroes after the sign.  */
4359                         if (count >= 1
4360                             && (*prec_ptr == '-' || *prec_ptr == '+'
4361                                 || *prec_ptr == ' '))
4362                           prefix_count = 1;
4363                         /* Put the additional zeroes after the 0x prefix if
4364                            (flags & FLAG_ALT) || (dp->conversion == 'p').  */
4365                         else if (count >= 2
4366                                  && prec_ptr[0] == '0'
4367                                  && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
4368                           prefix_count = 2;
4369
4370                         move = count - prefix_count;
4371                         if (precision > move)
4372                           {
4373                             /* Insert zeroes.  */
4374                             size_t insert = precision - move;
4375                             TCHAR_T *prec_end;
4376
4377 # if USE_SNPRINTF
4378                             size_t n =
4379                               xsum (length,
4380                                     (count + insert + TCHARS_PER_DCHAR - 1)
4381                                     / TCHARS_PER_DCHAR);
4382                             length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4383                             ENSURE_ALLOCATION (n);
4384                             length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
4385                             prec_ptr = (TCHAR_T *) (result + length);
4386 # endif
4387
4388                             prec_end = prec_ptr + count;
4389                             prec_ptr += prefix_count;
4390
4391                             while (prec_end > prec_ptr)
4392                               {
4393                                 prec_end--;
4394                                 prec_end[insert] = prec_end[0];
4395                               }
4396
4397                             prec_end += insert;
4398                             do
4399                               *--prec_end = '0';
4400                             while (prec_end > prec_ptr);
4401
4402                             count += insert;
4403                           }
4404                       }
4405 #endif
4406
4407 #if !USE_SNPRINTF
4408                     if (count >= tmp_length)
4409                       /* tmp_length was incorrectly calculated - fix the
4410                          code above!  */
4411                       abort ();
4412 #endif
4413
4414 #if !DCHAR_IS_TCHAR
4415                     /* Convert from TCHAR_T[] to DCHAR_T[].  */
4416                     if (dp->conversion == 'c' || dp->conversion == 's')
4417                       {
4418                         /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
4419                            TYPE_WIDE_STRING.
4420                            The result string is not certainly ASCII.  */
4421                         const TCHAR_T *tmpsrc;
4422                         DCHAR_T *tmpdst;
4423                         size_t tmpdst_len;
4424                         /* This code assumes that TCHAR_T is 'char'.  */
4425                         typedef int TCHAR_T_verify
4426                                     [2 * (sizeof (TCHAR_T) == 1) - 1];
4427 # if USE_SNPRINTF
4428                         tmpsrc = (TCHAR_T *) (result + length);
4429 # else
4430                         tmpsrc = tmp;
4431 # endif
4432                         tmpdst = NULL;
4433                         tmpdst_len = 0;
4434                         if (DCHAR_CONV_FROM_ENCODING (locale_charset (),
4435                                                       iconveh_question_mark,
4436                                                       tmpsrc, count,
4437                                                       NULL,
4438                                                       &tmpdst, &tmpdst_len)
4439                             < 0)
4440                           {
4441                             int saved_errno = errno;
4442                             if (!(result == resultbuf || result == NULL))
4443                               free (result);
4444                             if (buf_malloced != NULL)
4445                               free (buf_malloced);
4446                             CLEANUP ();
4447                             errno = saved_errno;
4448                             return NULL;
4449                           }
4450                         ENSURE_ALLOCATION (xsum (length, tmpdst_len));
4451                         DCHAR_CPY (result + length, tmpdst, tmpdst_len);
4452                         free (tmpdst);
4453                         count = tmpdst_len;
4454                       }
4455                     else
4456                       {
4457                         /* The result string is ASCII.
4458                            Simple 1:1 conversion.  */
4459 # if USE_SNPRINTF
4460                         /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
4461                            no-op conversion, in-place on the array starting
4462                            at (result + length).  */
4463                         if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
4464 # endif
4465                           {
4466                             const TCHAR_T *tmpsrc;
4467                             DCHAR_T *tmpdst;
4468                             size_t n;
4469
4470 # if USE_SNPRINTF
4471                             if (result == resultbuf)
4472                               {
4473                                 tmpsrc = (TCHAR_T *) (result + length);
4474                                 /* ENSURE_ALLOCATION will not move tmpsrc
4475                                    (because it's part of resultbuf).  */
4476                                 ENSURE_ALLOCATION (xsum (length, count));
4477                               }
4478                             else
4479                               {
4480                                 /* ENSURE_ALLOCATION will move the array
4481                                    (because it uses realloc().  */
4482                                 ENSURE_ALLOCATION (xsum (length, count));
4483                                 tmpsrc = (TCHAR_T *) (result + length);
4484                               }
4485 # else
4486                             tmpsrc = tmp;
4487                             ENSURE_ALLOCATION (xsum (length, count));
4488 # endif
4489                             tmpdst = result + length;
4490                             /* Copy backwards, because of overlapping.  */
4491                             tmpsrc += count;
4492                             tmpdst += count;
4493                             for (n = count; n > 0; n--)
4494                               *--tmpdst = (unsigned char) *--tmpsrc;
4495                           }
4496                       }
4497 #endif
4498
4499 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
4500                     /* Make room for the result.  */
4501                     if (count > allocated - length)
4502                       {
4503                         /* Need at least count elements.  But allocate
4504                            proportionally.  */
4505                         size_t n =
4506                           xmax (xsum (length, count), xtimes (allocated, 2));
4507
4508                         ENSURE_ALLOCATION (n);
4509                       }
4510 #endif
4511
4512                     /* Here count <= allocated - length.  */
4513
4514                     /* Perform padding.  */
4515 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4516                     if (pad_ourselves && has_width)
4517                       {
4518                         size_t w;
4519 # if ENABLE_UNISTDIO
4520                         /* Outside POSIX, it's preferrable to compare the width
4521                            against the number of _characters_ of the converted
4522                            value.  */
4523                         w = DCHAR_MBSNLEN (result + length, count);
4524 # else
4525                         /* The width is compared against the number of _bytes_
4526                            of the converted value, says POSIX.  */
4527                         w = count;
4528 # endif
4529                         if (w < width)
4530                           {
4531                             size_t pad = width - w;
4532
4533                             /* Make room for the result.  */
4534                             if (xsum (count, pad) > allocated - length)
4535                               {
4536                                 /* Need at least count + pad elements.  But
4537                                    allocate proportionally.  */
4538                                 size_t n =
4539                                   xmax (xsum3 (length, count, pad),
4540                                         xtimes (allocated, 2));
4541
4542 # if USE_SNPRINTF
4543                                 length += count;
4544                                 ENSURE_ALLOCATION (n);
4545                                 length -= count;
4546 # else
4547                                 ENSURE_ALLOCATION (n);
4548 # endif
4549                               }
4550                             /* Here count + pad <= allocated - length.  */
4551
4552                             {
4553 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
4554                               DCHAR_T * const rp = result + length;
4555 # else
4556                               DCHAR_T * const rp = tmp;
4557 # endif
4558                               DCHAR_T *p = rp + count;
4559                               DCHAR_T *end = p + pad;
4560                               DCHAR_T *pad_ptr;
4561 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4562                               if (dp->conversion == 'c'
4563                                   || dp->conversion == 's')
4564                                 /* No zero-padding for string directives.  */
4565                                 pad_ptr = NULL;
4566                               else
4567 # endif
4568                                 {
4569                                   pad_ptr = (*rp == '-' ? rp + 1 : rp);
4570                                   /* No zero-padding of "inf" and "nan".  */
4571                                   if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
4572                                       || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
4573                                     pad_ptr = NULL;
4574                                 }
4575                               /* The generated string now extends from rp to p,
4576                                  with the zero padding insertion point being at
4577                                  pad_ptr.  */
4578
4579                               count = count + pad; /* = end - rp */
4580
4581                               if (flags & FLAG_LEFT)
4582                                 {
4583                                   /* Pad with spaces on the right.  */
4584                                   for (; pad > 0; pad--)
4585                                     *p++ = ' ';
4586                                 }
4587                               else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4588                                 {
4589                                   /* Pad with zeroes.  */
4590                                   DCHAR_T *q = end;
4591
4592                                   while (p > pad_ptr)
4593                                     *--q = *--p;
4594                                   for (; pad > 0; pad--)
4595                                     *p++ = '0';
4596                                 }
4597                               else
4598                                 {
4599                                   /* Pad with spaces on the left.  */
4600                                   DCHAR_T *q = end;
4601
4602                                   while (p > rp)
4603                                     *--q = *--p;
4604                                   for (; pad > 0; pad--)
4605                                     *p++ = ' ';
4606                                 }
4607                             }
4608                           }
4609                       }
4610 #endif
4611
4612                     /* Here still count <= allocated - length.  */
4613
4614 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
4615                     /* The snprintf() result did fit.  */
4616 #else
4617                     /* Append the sprintf() result.  */
4618                     memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4619 #endif
4620 #if !USE_SNPRINTF
4621                     if (tmp != tmpbuf)
4622                       free (tmp);
4623 #endif
4624
4625 #if NEED_PRINTF_DIRECTIVE_F
4626                     if (dp->conversion == 'F')
4627                       {
4628                         /* Convert the %f result to upper case for %F.  */
4629                         DCHAR_T *rp = result + length;
4630                         size_t rc;
4631                         for (rc = count; rc > 0; rc--, rp++)
4632                           if (*rp >= 'a' && *rp <= 'z')
4633                             *rp = *rp - 'a' + 'A';
4634                       }
4635 #endif
4636
4637                     length += count;
4638                     break;
4639                   }
4640               }
4641           }
4642       }
4643
4644     /* Add the final NUL.  */
4645     ENSURE_ALLOCATION (xsum (length, 1));
4646     result[length] = '\0';
4647
4648     if (result != resultbuf && length + 1 < allocated)
4649       {
4650         /* Shrink the allocated memory if possible.  */
4651         DCHAR_T *memory;
4652
4653         memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
4654         if (memory != NULL)
4655           result = memory;
4656       }
4657
4658     if (buf_malloced != NULL)
4659       free (buf_malloced);
4660     CLEANUP ();
4661     *lengthp = length;
4662     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
4663        says that snprintf() fails with errno = EOVERFLOW in this case, but
4664        that's only because snprintf() returns an 'int'.  This function does
4665        not have this limitation.  */
4666     return result;
4667
4668 #if USE_SNPRINTF
4669   overflow:
4670     if (!(result == resultbuf || result == NULL))
4671       free (result);
4672     if (buf_malloced != NULL)
4673       free (buf_malloced);
4674     CLEANUP ();
4675     errno = EOVERFLOW;
4676     return NULL;
4677 #endif
4678
4679   out_of_memory:
4680     if (!(result == resultbuf || result == NULL))
4681       free (result);
4682     if (buf_malloced != NULL)
4683       free (buf_malloced);
4684   out_of_memory_1:
4685     CLEANUP ();
4686     errno = ENOMEM;
4687     return NULL;
4688   }
4689 }
4690
4691 #undef TCHARS_PER_DCHAR
4692 #undef SNPRINTF
4693 #undef USE_SNPRINTF
4694 #undef DCHAR_CPY
4695 #undef PRINTF_PARSE
4696 #undef DIRECTIVES
4697 #undef DIRECTIVE
4698 #undef DCHAR_IS_TCHAR
4699 #undef TCHAR_T
4700 #undef DCHAR_T
4701 #undef FCHAR_T
4702 #undef VASNPRINTF