Assume 'long double' exists.
[gnulib.git] / lib / vasnprintf.c
1 /* vsprintf with automatic memory allocation.
2    Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
19    This must come before <config.h> because <config.h> may include
20    <features.h>, and once <features.h> has been included, it's too late.  */
21 #ifndef _GNU_SOURCE
22 # define _GNU_SOURCE    1
23 #endif
24
25 #include <config.h>
26 #ifndef IN_LIBINTL
27 # include <alloca.h>
28 #endif
29
30 /* Specification.  */
31 #if WIDE_CHAR_VERSION
32 # include "vasnwprintf.h"
33 #else
34 # include "vasnprintf.h"
35 #endif
36
37 #include <locale.h>     /* localeconv() */
38 #include <stdio.h>      /* snprintf(), sprintf() */
39 #include <stdlib.h>     /* abort(), malloc(), realloc(), free() */
40 #include <string.h>     /* memcpy(), strlen() */
41 #include <errno.h>      /* errno */
42 #include <limits.h>     /* CHAR_BIT */
43 #include <float.h>      /* DBL_MAX_EXP, LDBL_MAX_EXP */
44 #if HAVE_NL_LANGINFO
45 # include <langinfo.h>
46 #endif
47 #if WIDE_CHAR_VERSION
48 # include "wprintf-parse.h"
49 #else
50 # include "printf-parse.h"
51 #endif
52
53 /* Checked size_t computations.  */
54 #include "xsize.h"
55
56 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
57 # include "float+.h"
58 # include "isnan.h"
59 # include "printf-frexp.h"
60 # include "isnanl-nolibm.h"
61 # include "printf-frexpl.h"
62 # include "fpucw.h"
63 #endif
64
65 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW.  */
66 #ifndef EOVERFLOW
67 # define EOVERFLOW E2BIG
68 #endif
69
70 #if HAVE_WCHAR_T
71 # if HAVE_WCSLEN
72 #  define local_wcslen wcslen
73 # else
74    /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
75       a dependency towards this library, here is a local substitute.
76       Define this substitute only once, even if this file is included
77       twice in the same compilation unit.  */
78 #  ifndef local_wcslen_defined
79 #   define local_wcslen_defined 1
80 static size_t
81 local_wcslen (const wchar_t *s)
82 {
83   const wchar_t *ptr;
84
85   for (ptr = s; *ptr != (wchar_t) 0; ptr++)
86     ;
87   return ptr - s;
88 }
89 #  endif
90 # endif
91 #endif
92
93 #if WIDE_CHAR_VERSION
94 # define VASNPRINTF vasnwprintf
95 # define CHAR_T wchar_t
96 # define DIRECTIVE wchar_t_directive
97 # define DIRECTIVES wchar_t_directives
98 # define PRINTF_PARSE wprintf_parse
99 # define USE_SNPRINTF 1
100 # if HAVE_DECL__SNWPRINTF
101    /* On Windows, the function swprintf() has a different signature than
102       on Unix; we use the _snwprintf() function instead.  */
103 #  define SNPRINTF _snwprintf
104 # else
105    /* Unix.  */
106 #  define SNPRINTF swprintf
107 # endif
108 #else
109 # define VASNPRINTF vasnprintf
110 # define CHAR_T char
111 # define DIRECTIVE char_directive
112 # define DIRECTIVES char_directives
113 # define PRINTF_PARSE printf_parse
114 # define USE_SNPRINTF (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF)
115 # if HAVE_DECL__SNPRINTF
116    /* Windows.  */
117 #  define SNPRINTF _snprintf
118 # else
119    /* Unix.  */
120 #  define SNPRINTF snprintf
121    /* Here we need to call the native snprintf, not rpl_snprintf.  */
122 #  undef snprintf
123 # endif
124 #endif
125 /* Here we need to call the native sprintf, not rpl_sprintf.  */
126 #undef sprintf
127
128 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
129 /* Determine the decimal-point character according to the current locale.  */
130 # ifndef decimal_point_char_defined
131 #  define decimal_point_char_defined 1
132 static char
133 decimal_point_char ()
134 {
135   const char *point;
136   /* Determine it in a multithread-safe way.  We know nl_langinfo is
137      multithread-safe on glibc systems, but is not required to be multithread-
138      safe by POSIX.  sprintf(), however, is multithread-safe.  localeconv()
139      is rarely multithread-safe.  */
140 #  if HAVE_NL_LANGINFO && __GLIBC__
141   point = nl_langinfo (RADIXCHAR);
142 #  elif 1
143   char pointbuf[5];
144   sprintf (pointbuf, "%#.0f", 1.0);
145   point = &pointbuf[1];
146 #  else
147   point = localeconv () -> decimal_point;
148 #  endif
149   /* The decimal point is always a single byte: either '.' or ','.  */
150   return (point[0] != '\0' ? point[0] : '.');
151 }
152 # endif
153 #endif
154
155 CHAR_T *
156 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
157 {
158   DIRECTIVES d;
159   arguments a;
160
161   if (PRINTF_PARSE (format, &d, &a) < 0)
162     {
163       errno = EINVAL;
164       return NULL;
165     }
166
167 #define CLEANUP() \
168   free (d.dir);                                                         \
169   if (a.arg)                                                            \
170     free (a.arg);
171
172   if (printf_fetchargs (args, &a) < 0)
173     {
174       CLEANUP ();
175       errno = EINVAL;
176       return NULL;
177     }
178
179   {
180     size_t buf_neededlength;
181     CHAR_T *buf;
182     CHAR_T *buf_malloced;
183     const CHAR_T *cp;
184     size_t i;
185     DIRECTIVE *dp;
186     /* Output string accumulator.  */
187     CHAR_T *result;
188     size_t allocated;
189     size_t length;
190
191     /* Allocate a small buffer that will hold a directive passed to
192        sprintf or snprintf.  */
193     buf_neededlength =
194       xsum4 (7, d.max_width_length, d.max_precision_length, 6);
195 #if HAVE_ALLOCA
196     if (buf_neededlength < 4000 / sizeof (CHAR_T))
197       {
198         buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
199         buf_malloced = NULL;
200       }
201     else
202 #endif
203       {
204         size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
205         if (size_overflow_p (buf_memsize))
206           goto out_of_memory_1;
207         buf = (CHAR_T *) malloc (buf_memsize);
208         if (buf == NULL)
209           goto out_of_memory_1;
210         buf_malloced = buf;
211       }
212
213     if (resultbuf != NULL)
214       {
215         result = resultbuf;
216         allocated = *lengthp;
217       }
218     else
219       {
220         result = NULL;
221         allocated = 0;
222       }
223     length = 0;
224     /* Invariants:
225        result is either == resultbuf or == NULL or malloc-allocated.
226        If length > 0, then result != NULL.  */
227
228     /* Ensures that allocated >= needed.  Aborts through a jump to
229        out_of_memory if needed is SIZE_MAX or otherwise too big.  */
230 #define ENSURE_ALLOCATION(needed) \
231     if ((needed) > allocated)                                                \
232       {                                                                      \
233         size_t memory_size;                                                  \
234         CHAR_T *memory;                                                      \
235                                                                              \
236         allocated = (allocated > 0 ? xtimes (allocated, 2) : 12);            \
237         if ((needed) > allocated)                                            \
238           allocated = (needed);                                              \
239         memory_size = xtimes (allocated, sizeof (CHAR_T));                   \
240         if (size_overflow_p (memory_size))                                   \
241           goto out_of_memory;                                                \
242         if (result == resultbuf || result == NULL)                           \
243           memory = (CHAR_T *) malloc (memory_size);                          \
244         else                                                                 \
245           memory = (CHAR_T *) realloc (result, memory_size);                 \
246         if (memory == NULL)                                                  \
247           goto out_of_memory;                                                \
248         if (result == resultbuf && length > 0)                               \
249           memcpy (memory, result, length * sizeof (CHAR_T));                 \
250         result = memory;                                                     \
251       }
252
253     for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
254       {
255         if (cp != dp->dir_start)
256           {
257             size_t n = dp->dir_start - cp;
258             size_t augmented_length = xsum (length, n);
259
260             ENSURE_ALLOCATION (augmented_length);
261             memcpy (result + length, cp, n * sizeof (CHAR_T));
262             length = augmented_length;
263           }
264         if (i == d.count)
265           break;
266
267         /* Execute a single directive.  */
268         if (dp->conversion == '%')
269           {
270             size_t augmented_length;
271
272             if (!(dp->arg_index == ARG_NONE))
273               abort ();
274             augmented_length = xsum (length, 1);
275             ENSURE_ALLOCATION (augmented_length);
276             result[length] = '%';
277             length = augmented_length;
278           }
279         else
280           {
281             if (!(dp->arg_index != ARG_NONE))
282               abort ();
283
284             if (dp->conversion == 'n')
285               {
286                 switch (a.arg[dp->arg_index].type)
287                   {
288                   case TYPE_COUNT_SCHAR_POINTER:
289                     *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
290                     break;
291                   case TYPE_COUNT_SHORT_POINTER:
292                     *a.arg[dp->arg_index].a.a_count_short_pointer = length;
293                     break;
294                   case TYPE_COUNT_INT_POINTER:
295                     *a.arg[dp->arg_index].a.a_count_int_pointer = length;
296                     break;
297                   case TYPE_COUNT_LONGINT_POINTER:
298                     *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
299                     break;
300 #if HAVE_LONG_LONG_INT
301                   case TYPE_COUNT_LONGLONGINT_POINTER:
302                     *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
303                     break;
304 #endif
305                   default:
306                     abort ();
307                   }
308               }
309 #if NEED_PRINTF_DIRECTIVE_A && !defined IN_LIBINTL
310             else if (dp->conversion == 'a' || dp->conversion == 'A')
311               {
312                 arg_type type = a.arg[dp->arg_index].type;
313                 int flags = dp->flags;
314                 int has_width;
315                 size_t width;
316                 int has_precision;
317                 size_t precision;
318                 size_t tmp_length;
319                 CHAR_T tmpbuf[700];
320                 CHAR_T *tmp;
321                 CHAR_T *pad_ptr;
322                 CHAR_T *p;
323
324                 has_width = 0;
325                 width = 0;
326                 if (dp->width_start != dp->width_end)
327                   {
328                     if (dp->width_arg_index != ARG_NONE)
329                       {
330                         int arg;
331
332                         if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
333                           abort ();
334                         arg = a.arg[dp->width_arg_index].a.a_int;
335                         if (arg < 0)
336                           {
337                             /* "A negative field width is taken as a '-' flag
338                                 followed by a positive field width."  */
339                             flags |= FLAG_LEFT;
340                             width = (unsigned int) (-arg);
341                           }
342                         else
343                           width = arg;
344                       }
345                     else
346                       {
347                         const CHAR_T *digitp = dp->width_start;
348
349                         do
350                           width = xsum (xtimes (width, 10), *digitp++ - '0');
351                         while (digitp != dp->width_end);
352                       }
353                     has_width = 1;
354                   }
355
356                 has_precision = 0;
357                 precision = 0;
358                 if (dp->precision_start != dp->precision_end)
359                   {
360                     if (dp->precision_arg_index != ARG_NONE)
361                       {
362                         int arg;
363
364                         if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
365                           abort ();
366                         arg = a.arg[dp->precision_arg_index].a.a_int;
367                         /* "A negative precision is taken as if the precision
368                             were omitted."  */
369                         if (arg >= 0)
370                           {
371                             precision = arg;
372                             has_precision = 1;
373                           }
374                       }
375                     else
376                       {
377                         const CHAR_T *digitp = dp->precision_start + 1;
378
379                         precision = 0;
380                         while (digitp != dp->precision_end)
381                           precision = xsum (xtimes (precision, 10), *digitp++ - '0');
382                         has_precision = 1;
383                       }
384                   }
385
386                 /* Allocate a temporary buffer of sufficient size.  */
387                 if (type == TYPE_LONGDOUBLE)
388                   tmp_length =
389                     (unsigned int) ((LDBL_DIG + 1)
390                                     * 0.831 /* decimal -> hexadecimal */
391                                    )
392                     + 1; /* turn floor into ceil */
393                 else
394                   tmp_length =
395                     (unsigned int) ((DBL_DIG + 1)
396                                     * 0.831 /* decimal -> hexadecimal */
397                                    )
398                     + 1; /* turn floor into ceil */
399                 if (tmp_length < precision)
400                   tmp_length = precision;
401                 /* Account for sign, decimal point etc. */
402                 tmp_length = xsum (tmp_length, 12);
403
404                 if (tmp_length < width)
405                   tmp_length = width;
406
407                 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
408
409                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
410                   tmp = tmpbuf;
411                 else
412                   {
413                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
414
415                     if (size_overflow_p (tmp_memsize))
416                       /* Overflow, would lead to out of memory.  */
417                       goto out_of_memory;
418                     tmp = (CHAR_T *) malloc (tmp_memsize);
419                     if (tmp == NULL)
420                       /* Out of memory.  */
421                       goto out_of_memory;
422                   }
423
424                 pad_ptr = NULL;
425                 p = tmp;
426                 if (type == TYPE_LONGDOUBLE)
427                   {
428                     long double arg = a.arg[dp->arg_index].a.a_longdouble;
429
430                     if (isnanl (arg))
431                       {
432                         if (dp->conversion == 'A')
433                           {
434                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
435                           }
436                         else
437                           {
438                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
439                           }
440                       }
441                     else
442                       {
443                         int sign = 0;
444                         DECL_LONG_DOUBLE_ROUNDING
445
446                         BEGIN_LONG_DOUBLE_ROUNDING ();
447
448                         if (arg < 0.0L)
449                           {
450                             sign = -1;
451                             arg = -arg;
452                           }
453                         else if (arg == 0.0L)
454                           {
455                             /* Distinguish 0.0L and -0.0L.  */
456                             static long double plus_zero = 0.0L;
457                             long double arg_mem = arg;
458                             if (memcmp (&plus_zero, &arg_mem, SIZEOF_LDBL) != 0)
459                               {
460                                 sign = -1;
461                                 arg = -arg;
462                               }
463                           }
464
465                         if (sign < 0)
466                           *p++ = '-';
467                         else if (flags & FLAG_SHOWSIGN)
468                           *p++ = '+';
469                         else if (flags & FLAG_SPACE)
470                           *p++ = ' ';
471
472                         if (arg > 0.0L && arg + arg == arg)
473                           {
474                             if (dp->conversion == 'A')
475                               {
476                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
477                               }
478                             else
479                               {
480                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
481                               }
482                           }
483                         else
484                           {
485                             int exponent;
486                             long double mantissa;
487
488                             if (arg > 0.0L)
489                               mantissa = printf_frexpl (arg, &exponent);
490                             else
491                               {
492                                 exponent = 0;
493                                 mantissa = 0.0L;
494                               }
495
496                             if (has_precision
497                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
498                               {
499                                 /* Round the mantissa.  */
500                                 long double tail = mantissa;
501                                 size_t q;
502
503                                 for (q = precision; ; q--)
504                                   {
505                                     int digit = (int) tail;
506                                     tail -= digit;
507                                     if (q == 0)
508                                       {
509                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
510                                           tail = 1 - tail;
511                                         else
512                                           tail = - tail;
513                                         break;
514                                       }
515                                     tail *= 16.0L;
516                                   }
517                                 if (tail != 0.0L)
518                                   for (q = precision; q > 0; q--)
519                                     tail *= 0.0625L;
520                                 mantissa += tail;
521                               }
522
523                             *p++ = '0';
524                             *p++ = dp->conversion - 'A' + 'X';
525                             pad_ptr = p;
526                             {
527                               int digit;
528
529                               digit = (int) mantissa;
530                               mantissa -= digit;
531                               *p++ = '0' + digit;
532                               if ((flags & FLAG_ALT)
533                                   || mantissa > 0.0L || precision > 0)
534                                 {
535                                   *p++ = decimal_point_char ();
536                                   /* This loop terminates because we assume
537                                      that FLT_RADIX is a power of 2.  */
538                                   while (mantissa > 0.0L)
539                                     {
540                                       mantissa *= 16.0L;
541                                       digit = (int) mantissa;
542                                       mantissa -= digit;
543                                       *p++ = digit
544                                              + (digit < 10
545                                                 ? '0'
546                                                 : dp->conversion - 10);
547                                       if (precision > 0)
548                                         precision--;
549                                     }
550                                   while (precision > 0)
551                                     {
552                                       *p++ = '0';
553                                       precision--;
554                                     }
555                                 }
556                               }
557                               *p++ = dp->conversion - 'A' + 'P';
558 # if WIDE_CHAR_VERSION
559                               {
560                                 static const wchar_t decimal_format[] =
561                                   { '%', '+', 'd', '\0' };
562                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
563                               }
564 # else
565                               sprintf (p, "%+d", exponent);
566 # endif
567                               while (*p != '\0')
568                                 p++;
569                           }
570
571                         END_LONG_DOUBLE_ROUNDING ();
572                       }
573                   }
574                 else
575                   {
576                     double arg = a.arg[dp->arg_index].a.a_double;
577
578                     if (isnan (arg))
579                       {
580                         if (dp->conversion == 'A')
581                           {
582                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
583                           }
584                         else
585                           {
586                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
587                           }
588                       }
589                     else
590                       {
591                         int sign = 0;
592
593                         if (arg < 0.0)
594                           {
595                             sign = -1;
596                             arg = -arg;
597                           }
598                         else if (arg == 0.0)
599                           {
600                             /* Distinguish 0.0 and -0.0.  */
601                             static double plus_zero = 0.0;
602                             double arg_mem = arg;
603                             if (memcmp (&plus_zero, &arg_mem, SIZEOF_DBL) != 0)
604                               {
605                                 sign = -1;
606                                 arg = -arg;
607                               }
608                           }
609
610                         if (sign < 0)
611                           *p++ = '-';
612                         else if (flags & FLAG_SHOWSIGN)
613                           *p++ = '+';
614                         else if (flags & FLAG_SPACE)
615                           *p++ = ' ';
616
617                         if (arg > 0.0 && arg + arg == arg)
618                           {
619                             if (dp->conversion == 'A')
620                               {
621                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
622                               }
623                             else
624                               {
625                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
626                               }
627                           }
628                         else
629                           {
630                             int exponent;
631                             double mantissa;
632
633                             if (arg > 0.0)
634                               mantissa = printf_frexp (arg, &exponent);
635                             else
636                               {
637                                 exponent = 0;
638                                 mantissa = 0.0;
639                               }
640
641                             if (has_precision
642                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
643                               {
644                                 /* Round the mantissa.  */
645                                 double tail = mantissa;
646                                 size_t q;
647
648                                 for (q = precision; ; q--)
649                                   {
650                                     int digit = (int) tail;
651                                     tail -= digit;
652                                     if (q == 0)
653                                       {
654                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
655                                           tail = 1 - tail;
656                                         else
657                                           tail = - tail;
658                                         break;
659                                       }
660                                     tail *= 16.0;
661                                   }
662                                 if (tail != 0.0)
663                                   for (q = precision; q > 0; q--)
664                                     tail *= 0.0625;
665                                 mantissa += tail;
666                               }
667
668                             *p++ = '0';
669                             *p++ = dp->conversion - 'A' + 'X';
670                             pad_ptr = p;
671                             {
672                               int digit;
673
674                               digit = (int) mantissa;
675                               mantissa -= digit;
676                               *p++ = '0' + digit;
677                               if ((flags & FLAG_ALT)
678                                   || mantissa > 0.0 || precision > 0)
679                                 {
680                                   *p++ = decimal_point_char ();
681                                   /* This loop terminates because we assume
682                                      that FLT_RADIX is a power of 2.  */
683                                   while (mantissa > 0.0)
684                                     {
685                                       mantissa *= 16.0;
686                                       digit = (int) mantissa;
687                                       mantissa -= digit;
688                                       *p++ = digit
689                                              + (digit < 10
690                                                 ? '0'
691                                                 : dp->conversion - 10);
692                                       if (precision > 0)
693                                         precision--;
694                                     }
695                                   while (precision > 0)
696                                     {
697                                       *p++ = '0';
698                                       precision--;
699                                     }
700                                 }
701                               }
702                               *p++ = dp->conversion - 'A' + 'P';
703 # if WIDE_CHAR_VERSION
704                               {
705                                 static const wchar_t decimal_format[] =
706                                   { '%', '+', 'd', '\0' };
707                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
708                               }
709 # else
710                               sprintf (p, "%+d", exponent);
711 # endif
712                               while (*p != '\0')
713                                 p++;
714                           }
715                       }
716                   }
717                 /* The generated string now extends from tmp to p, with the
718                    zero padding insertion point being at pad_ptr.  */
719                 if (has_width && p - tmp < width)
720                   {
721                     size_t pad = width - (p - tmp);
722                     CHAR_T *end = p + pad;
723
724                     if (flags & FLAG_LEFT)
725                       {
726                         /* Pad with spaces on the right.  */
727                         for (; pad > 0; pad--)
728                           *p++ = ' ';
729                       }
730                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
731                       {
732                         /* Pad with zeroes.  */
733                         CHAR_T *q = end;
734
735                         while (p > pad_ptr)
736                           *--q = *--p;
737                         for (; pad > 0; pad--)
738                           *p++ = '0';
739                       }
740                     else
741                       {
742                         /* Pad with spaces on the left.  */
743                         CHAR_T *q = end;
744
745                         while (p > tmp)
746                           *--q = *--p;
747                         for (; pad > 0; pad--)
748                           *p++ = ' ';
749                       }
750
751                     p = end;
752                   }
753
754                 {
755                   size_t count = p - tmp;
756
757                   if (count >= tmp_length)
758                     /* tmp_length was incorrectly calculated - fix the
759                        code above!  */
760                     abort ();
761
762                   /* Make room for the result.  */
763                   if (count >= allocated - length)
764                     {
765                       size_t n = xsum (length, count);
766
767                       ENSURE_ALLOCATION (n);
768                     }
769
770                   /* Append the result.  */
771                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
772                   if (tmp != tmpbuf)
773                     free (tmp);
774                   length += count;
775                 }
776               }
777 #endif
778             else
779               {
780                 arg_type type = a.arg[dp->arg_index].type;
781                 CHAR_T *p;
782                 unsigned int prefix_count;
783                 int prefixes[2];
784 #if !USE_SNPRINTF
785                 size_t tmp_length;
786                 CHAR_T tmpbuf[700];
787                 CHAR_T *tmp;
788
789                 /* Allocate a temporary buffer of sufficient size for calling
790                    sprintf.  */
791                 {
792                   size_t width;
793                   size_t precision;
794
795                   width = 0;
796                   if (dp->width_start != dp->width_end)
797                     {
798                       if (dp->width_arg_index != ARG_NONE)
799                         {
800                           int arg;
801
802                           if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
803                             abort ();
804                           arg = a.arg[dp->width_arg_index].a.a_int;
805                           width = (arg < 0 ? (unsigned int) (-arg) : arg);
806                         }
807                       else
808                         {
809                           const CHAR_T *digitp = dp->width_start;
810
811                           do
812                             width = xsum (xtimes (width, 10), *digitp++ - '0');
813                           while (digitp != dp->width_end);
814                         }
815                     }
816
817                   precision = 6;
818                   if (dp->precision_start != dp->precision_end)
819                     {
820                       if (dp->precision_arg_index != ARG_NONE)
821                         {
822                           int arg;
823
824                           if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
825                             abort ();
826                           arg = a.arg[dp->precision_arg_index].a.a_int;
827                           precision = (arg < 0 ? 0 : arg);
828                         }
829                       else
830                         {
831                           const CHAR_T *digitp = dp->precision_start + 1;
832
833                           precision = 0;
834                           while (digitp != dp->precision_end)
835                             precision = xsum (xtimes (precision, 10), *digitp++ - '0');
836                         }
837                     }
838
839                   switch (dp->conversion)
840                     {
841
842                     case 'd': case 'i': case 'u':
843 # if HAVE_LONG_LONG_INT
844                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
845                         tmp_length =
846                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
847                                           * 0.30103 /* binary -> decimal */
848                                          )
849                           + 1; /* turn floor into ceil */
850                       else
851 # endif
852                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
853                         tmp_length =
854                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
855                                           * 0.30103 /* binary -> decimal */
856                                          )
857                           + 1; /* turn floor into ceil */
858                       else
859                         tmp_length =
860                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
861                                           * 0.30103 /* binary -> decimal */
862                                          )
863                           + 1; /* turn floor into ceil */
864                       if (tmp_length < precision)
865                         tmp_length = precision;
866                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
867                       tmp_length = xsum (tmp_length, tmp_length);
868                       /* Add 1, to account for a leading sign.  */
869                       tmp_length = xsum (tmp_length, 1);
870                       break;
871
872                     case 'o':
873 # if HAVE_LONG_LONG_INT
874                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
875                         tmp_length =
876                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
877                                           * 0.333334 /* binary -> octal */
878                                          )
879                           + 1; /* turn floor into ceil */
880                       else
881 # endif
882                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
883                         tmp_length =
884                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
885                                           * 0.333334 /* binary -> octal */
886                                          )
887                           + 1; /* turn floor into ceil */
888                       else
889                         tmp_length =
890                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
891                                           * 0.333334 /* binary -> octal */
892                                          )
893                           + 1; /* turn floor into ceil */
894                       if (tmp_length < precision)
895                         tmp_length = precision;
896                       /* Add 1, to account for a leading sign.  */
897                       tmp_length = xsum (tmp_length, 1);
898                       break;
899
900                     case 'x': case 'X':
901 # if HAVE_LONG_LONG_INT
902                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
903                         tmp_length =
904                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
905                                           * 0.25 /* binary -> hexadecimal */
906                                          )
907                           + 1; /* turn floor into ceil */
908                       else
909 # endif
910                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
911                         tmp_length =
912                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
913                                           * 0.25 /* binary -> hexadecimal */
914                                          )
915                           + 1; /* turn floor into ceil */
916                       else
917                         tmp_length =
918                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
919                                           * 0.25 /* binary -> hexadecimal */
920                                          )
921                           + 1; /* turn floor into ceil */
922                       if (tmp_length < precision)
923                         tmp_length = precision;
924                       /* Add 2, to account for a leading sign or alternate form.  */
925                       tmp_length = xsum (tmp_length, 2);
926                       break;
927
928                     case 'f': case 'F':
929                       if (type == TYPE_LONGDOUBLE)
930                         tmp_length =
931                           (unsigned int) (LDBL_MAX_EXP
932                                           * 0.30103 /* binary -> decimal */
933                                           * 2 /* estimate for FLAG_GROUP */
934                                          )
935                           + 1 /* turn floor into ceil */
936                           + 10; /* sign, decimal point etc. */
937                       else
938                         tmp_length =
939                           (unsigned int) (DBL_MAX_EXP
940                                           * 0.30103 /* binary -> decimal */
941                                           * 2 /* estimate for FLAG_GROUP */
942                                          )
943                           + 1 /* turn floor into ceil */
944                           + 10; /* sign, decimal point etc. */
945                       tmp_length = xsum (tmp_length, precision);
946                       break;
947
948                     case 'e': case 'E': case 'g': case 'G':
949                       tmp_length =
950                         12; /* sign, decimal point, exponent etc. */
951                       tmp_length = xsum (tmp_length, precision);
952                       break;
953
954                     case 'a': case 'A':
955                       if (type == TYPE_LONGDOUBLE)
956                         tmp_length =
957                           (unsigned int) (LDBL_DIG
958                                           * 0.831 /* decimal -> hexadecimal */
959                                          )
960                           + 1; /* turn floor into ceil */
961                       else
962                         tmp_length =
963                           (unsigned int) (DBL_DIG
964                                           * 0.831 /* decimal -> hexadecimal */
965                                          )
966                           + 1; /* turn floor into ceil */
967                       if (tmp_length < precision)
968                         tmp_length = precision;
969                       /* Account for sign, decimal point etc. */
970                       tmp_length = xsum (tmp_length, 12);
971                       break;
972
973                     case 'c':
974 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
975                       if (type == TYPE_WIDE_CHAR)
976                         tmp_length = MB_CUR_MAX;
977                       else
978 # endif
979                         tmp_length = 1;
980                       break;
981
982                     case 's':
983 # if HAVE_WCHAR_T
984                       if (type == TYPE_WIDE_STRING)
985                         {
986                           tmp_length =
987                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
988
989 #  if !WIDE_CHAR_VERSION
990                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
991 #  endif
992                         }
993                       else
994 # endif
995                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
996                       break;
997
998                     case 'p':
999                       tmp_length =
1000                         (unsigned int) (sizeof (void *) * CHAR_BIT
1001                                         * 0.25 /* binary -> hexadecimal */
1002                                        )
1003                           + 1 /* turn floor into ceil */
1004                           + 2; /* account for leading 0x */
1005                       break;
1006
1007                     default:
1008                       abort ();
1009                     }
1010
1011                   if (tmp_length < width)
1012                     tmp_length = width;
1013
1014                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1015                 }
1016
1017                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
1018                   tmp = tmpbuf;
1019                 else
1020                   {
1021                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1022
1023                     if (size_overflow_p (tmp_memsize))
1024                       /* Overflow, would lead to out of memory.  */
1025                       goto out_of_memory;
1026                     tmp = (CHAR_T *) malloc (tmp_memsize);
1027                     if (tmp == NULL)
1028                       /* Out of memory.  */
1029                       goto out_of_memory;
1030                   }
1031 #endif
1032
1033                 /* Construct the format string for calling snprintf or
1034                    sprintf.  */
1035                 p = buf;
1036                 *p++ = '%';
1037                 if (dp->flags & FLAG_GROUP)
1038                   *p++ = '\'';
1039                 if (dp->flags & FLAG_LEFT)
1040                   *p++ = '-';
1041                 if (dp->flags & FLAG_SHOWSIGN)
1042                   *p++ = '+';
1043                 if (dp->flags & FLAG_SPACE)
1044                   *p++ = ' ';
1045                 if (dp->flags & FLAG_ALT)
1046                   *p++ = '#';
1047                 if (dp->flags & FLAG_ZERO)
1048                   *p++ = '0';
1049                 if (dp->width_start != dp->width_end)
1050                   {
1051                     size_t n = dp->width_end - dp->width_start;
1052                     memcpy (p, dp->width_start, n * sizeof (CHAR_T));
1053                     p += n;
1054                   }
1055                 if (dp->precision_start != dp->precision_end)
1056                   {
1057                     size_t n = dp->precision_end - dp->precision_start;
1058                     memcpy (p, dp->precision_start, n * sizeof (CHAR_T));
1059                     p += n;
1060                   }
1061
1062                 switch (type)
1063                   {
1064 #if HAVE_LONG_LONG_INT
1065                   case TYPE_LONGLONGINT:
1066                   case TYPE_ULONGLONGINT:
1067                     *p++ = 'l';
1068                     /*FALLTHROUGH*/
1069 #endif
1070                   case TYPE_LONGINT:
1071                   case TYPE_ULONGINT:
1072 #if HAVE_WINT_T
1073                   case TYPE_WIDE_CHAR:
1074 #endif
1075 #if HAVE_WCHAR_T
1076                   case TYPE_WIDE_STRING:
1077 #endif
1078                     *p++ = 'l';
1079                     break;
1080                   case TYPE_LONGDOUBLE:
1081                     *p++ = 'L';
1082                     break;
1083                   default:
1084                     break;
1085                   }
1086                 *p = dp->conversion;
1087 #if USE_SNPRINTF
1088                 p[1] = '%';
1089                 p[2] = 'n';
1090                 p[3] = '\0';
1091 #else
1092                 p[1] = '\0';
1093 #endif
1094
1095                 /* Construct the arguments for calling snprintf or sprintf.  */
1096                 prefix_count = 0;
1097                 if (dp->width_arg_index != ARG_NONE)
1098                   {
1099                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1100                       abort ();
1101                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
1102                   }
1103                 if (dp->precision_arg_index != ARG_NONE)
1104                   {
1105                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1106                       abort ();
1107                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
1108                   }
1109
1110 #if USE_SNPRINTF
1111                 /* Prepare checking whether snprintf returns the count
1112                    via %n.  */
1113                 ENSURE_ALLOCATION (xsum (length, 1));
1114                 result[length] = '\0';
1115 #endif
1116
1117                 for (;;)
1118                   {
1119                     size_t maxlen;
1120                     int count;
1121                     int retcount;
1122
1123                     maxlen = allocated - length;
1124                     count = -1;
1125                     retcount = 0;
1126
1127 #if USE_SNPRINTF
1128                     /* SNPRINTF can fail if maxlen > INT_MAX.  */
1129                     if (maxlen > INT_MAX)
1130                       goto overflow;
1131 # define SNPRINTF_BUF(arg) \
1132                     switch (prefix_count)                                   \
1133                       {                                                     \
1134                       case 0:                                               \
1135                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1136                                              arg, &count);                  \
1137                         break;                                              \
1138                       case 1:                                               \
1139                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1140                                              prefixes[0], arg, &count);     \
1141                         break;                                              \
1142                       case 2:                                               \
1143                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1144                                              prefixes[0], prefixes[1], arg, \
1145                                              &count);                       \
1146                         break;                                              \
1147                       default:                                              \
1148                         abort ();                                           \
1149                       }
1150 #else
1151 # define SNPRINTF_BUF(arg) \
1152                     switch (prefix_count)                                   \
1153                       {                                                     \
1154                       case 0:                                               \
1155                         count = sprintf (tmp, buf, arg);                    \
1156                         break;                                              \
1157                       case 1:                                               \
1158                         count = sprintf (tmp, buf, prefixes[0], arg);       \
1159                         break;                                              \
1160                       case 2:                                               \
1161                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
1162                                          arg);                              \
1163                         break;                                              \
1164                       default:                                              \
1165                         abort ();                                           \
1166                       }
1167 #endif
1168
1169                     switch (type)
1170                       {
1171                       case TYPE_SCHAR:
1172                         {
1173                           int arg = a.arg[dp->arg_index].a.a_schar;
1174                           SNPRINTF_BUF (arg);
1175                         }
1176                         break;
1177                       case TYPE_UCHAR:
1178                         {
1179                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
1180                           SNPRINTF_BUF (arg);
1181                         }
1182                         break;
1183                       case TYPE_SHORT:
1184                         {
1185                           int arg = a.arg[dp->arg_index].a.a_short;
1186                           SNPRINTF_BUF (arg);
1187                         }
1188                         break;
1189                       case TYPE_USHORT:
1190                         {
1191                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
1192                           SNPRINTF_BUF (arg);
1193                         }
1194                         break;
1195                       case TYPE_INT:
1196                         {
1197                           int arg = a.arg[dp->arg_index].a.a_int;
1198                           SNPRINTF_BUF (arg);
1199                         }
1200                         break;
1201                       case TYPE_UINT:
1202                         {
1203                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
1204                           SNPRINTF_BUF (arg);
1205                         }
1206                         break;
1207                       case TYPE_LONGINT:
1208                         {
1209                           long int arg = a.arg[dp->arg_index].a.a_longint;
1210                           SNPRINTF_BUF (arg);
1211                         }
1212                         break;
1213                       case TYPE_ULONGINT:
1214                         {
1215                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
1216                           SNPRINTF_BUF (arg);
1217                         }
1218                         break;
1219 #if HAVE_LONG_LONG_INT
1220                       case TYPE_LONGLONGINT:
1221                         {
1222                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
1223                           SNPRINTF_BUF (arg);
1224                         }
1225                         break;
1226                       case TYPE_ULONGLONGINT:
1227                         {
1228                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
1229                           SNPRINTF_BUF (arg);
1230                         }
1231                         break;
1232 #endif
1233                       case TYPE_DOUBLE:
1234                         {
1235                           double arg = a.arg[dp->arg_index].a.a_double;
1236                           SNPRINTF_BUF (arg);
1237                         }
1238                         break;
1239                       case TYPE_LONGDOUBLE:
1240                         {
1241                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
1242                           SNPRINTF_BUF (arg);
1243                         }
1244                         break;
1245                       case TYPE_CHAR:
1246                         {
1247                           int arg = a.arg[dp->arg_index].a.a_char;
1248                           SNPRINTF_BUF (arg);
1249                         }
1250                         break;
1251 #if HAVE_WINT_T
1252                       case TYPE_WIDE_CHAR:
1253                         {
1254                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
1255                           SNPRINTF_BUF (arg);
1256                         }
1257                         break;
1258 #endif
1259                       case TYPE_STRING:
1260                         {
1261                           const char *arg = a.arg[dp->arg_index].a.a_string;
1262                           SNPRINTF_BUF (arg);
1263                         }
1264                         break;
1265 #if HAVE_WCHAR_T
1266                       case TYPE_WIDE_STRING:
1267                         {
1268                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
1269                           SNPRINTF_BUF (arg);
1270                         }
1271                         break;
1272 #endif
1273                       case TYPE_POINTER:
1274                         {
1275                           void *arg = a.arg[dp->arg_index].a.a_pointer;
1276                           SNPRINTF_BUF (arg);
1277                         }
1278                         break;
1279                       default:
1280                         abort ();
1281                       }
1282
1283 #if USE_SNPRINTF
1284                     /* Portability: Not all implementations of snprintf()
1285                        are ISO C 99 compliant.  Determine the number of
1286                        bytes that snprintf() has produced or would have
1287                        produced.  */
1288                     if (count >= 0)
1289                       {
1290                         /* Verify that snprintf() has NUL-terminated its
1291                            result.  */
1292                         if (count < maxlen && result[length + count] != '\0')
1293                           abort ();
1294                         /* Portability hack.  */
1295                         if (retcount > count)
1296                           count = retcount;
1297                       }
1298                     else
1299                       {
1300                         /* snprintf() doesn't understand the '%n'
1301                            directive.  */
1302                         if (p[1] != '\0')
1303                           {
1304                             /* Don't use the '%n' directive; instead, look
1305                                at the snprintf() return value.  */
1306                             p[1] = '\0';
1307                             continue;
1308                           }
1309                         else
1310                           {
1311                             /* Look at the snprintf() return value.  */
1312                             if (retcount < 0)
1313                               {
1314                                 /* HP-UX 10.20 snprintf() is doubly deficient:
1315                                    It doesn't understand the '%n' directive,
1316                                    *and* it returns -1 (rather than the length
1317                                    that would have been required) when the
1318                                    buffer is too small.  */
1319                                 size_t bigger_need =
1320                                   xsum (xtimes (allocated, 2), 12);
1321                                 ENSURE_ALLOCATION (bigger_need);
1322                                 continue;
1323                               }
1324                             else
1325                               count = retcount;
1326                           }
1327                       }
1328 #endif
1329
1330                     /* Attempt to handle failure.  */
1331                     if (count < 0)
1332                       {
1333                         if (!(result == resultbuf || result == NULL))
1334                           free (result);
1335                         if (buf_malloced != NULL)
1336                           free (buf_malloced);
1337                         CLEANUP ();
1338                         errno = EINVAL;
1339                         return NULL;
1340                       }
1341
1342 #if !USE_SNPRINTF
1343                     if (count >= tmp_length)
1344                       /* tmp_length was incorrectly calculated - fix the
1345                          code above!  */
1346                       abort ();
1347 #endif
1348
1349                     /* Make room for the result.  */
1350                     if (count >= maxlen)
1351                       {
1352                         /* Need at least count bytes.  But allocate
1353                            proportionally, to avoid looping eternally if
1354                            snprintf() reports a too small count.  */
1355                         size_t n =
1356                           xmax (xsum (length, count), xtimes (allocated, 2));
1357
1358                         ENSURE_ALLOCATION (n);
1359 #if USE_SNPRINTF
1360                         continue;
1361 #endif
1362                       }
1363
1364 #if USE_SNPRINTF
1365                     /* The snprintf() result did fit.  */
1366 #else
1367                     /* Append the sprintf() result.  */
1368                     memcpy (result + length, tmp, count * sizeof (CHAR_T));
1369                     if (tmp != tmpbuf)
1370                       free (tmp);
1371 #endif
1372
1373                     length += count;
1374                     break;
1375                   }
1376               }
1377           }
1378       }
1379
1380     /* Add the final NUL.  */
1381     ENSURE_ALLOCATION (xsum (length, 1));
1382     result[length] = '\0';
1383
1384     if (result != resultbuf && length + 1 < allocated)
1385       {
1386         /* Shrink the allocated memory if possible.  */
1387         CHAR_T *memory;
1388
1389         memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
1390         if (memory != NULL)
1391           result = memory;
1392       }
1393
1394     if (buf_malloced != NULL)
1395       free (buf_malloced);
1396     CLEANUP ();
1397     *lengthp = length;
1398     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
1399        says that snprintf() fails with errno = EOVERFLOW in this case, but
1400        that's only because snprintf() returns an 'int'.  This function does
1401        not have this limitation.  */
1402     return result;
1403
1404   overflow:
1405     if (!(result == resultbuf || result == NULL))
1406       free (result);
1407     if (buf_malloced != NULL)
1408       free (buf_malloced);
1409     CLEANUP ();
1410     errno = EOVERFLOW;
1411     return NULL;
1412
1413   out_of_memory:
1414     if (!(result == resultbuf || result == NULL))
1415       free (result);
1416     if (buf_malloced != NULL)
1417       free (buf_malloced);
1418   out_of_memory_1:
1419     CLEANUP ();
1420     errno = ENOMEM;
1421     return NULL;
1422   }
1423 }
1424
1425 #undef SNPRINTF
1426 #undef USE_SNPRINTF
1427 #undef PRINTF_PARSE
1428 #undef DIRECTIVES
1429 #undef DIRECTIVE
1430 #undef CHAR_T
1431 #undef VASNPRINTF