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