Work around lack of support of grouping flag.
[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 <math.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 (signbit (arg)) /* arg < 0.0L or negative zero */
449                           {
450                             sign = -1;
451                             arg = -arg;
452                           }
453
454                         if (sign < 0)
455                           *p++ = '-';
456                         else if (flags & FLAG_SHOWSIGN)
457                           *p++ = '+';
458                         else if (flags & FLAG_SPACE)
459                           *p++ = ' ';
460
461                         if (arg > 0.0L && arg + arg == arg)
462                           {
463                             if (dp->conversion == 'A')
464                               {
465                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
466                               }
467                             else
468                               {
469                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
470                               }
471                           }
472                         else
473                           {
474                             int exponent;
475                             long double mantissa;
476
477                             if (arg > 0.0L)
478                               mantissa = printf_frexpl (arg, &exponent);
479                             else
480                               {
481                                 exponent = 0;
482                                 mantissa = 0.0L;
483                               }
484
485                             if (has_precision
486                                 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
487                               {
488                                 /* Round the mantissa.  */
489                                 long double tail = mantissa;
490                                 size_t q;
491
492                                 for (q = precision; ; q--)
493                                   {
494                                     int digit = (int) tail;
495                                     tail -= digit;
496                                     if (q == 0)
497                                       {
498                                         if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
499                                           tail = 1 - tail;
500                                         else
501                                           tail = - tail;
502                                         break;
503                                       }
504                                     tail *= 16.0L;
505                                   }
506                                 if (tail != 0.0L)
507                                   for (q = precision; q > 0; q--)
508                                     tail *= 0.0625L;
509                                 mantissa += tail;
510                               }
511
512                             *p++ = '0';
513                             *p++ = dp->conversion - 'A' + 'X';
514                             pad_ptr = p;
515                             {
516                               int digit;
517
518                               digit = (int) mantissa;
519                               mantissa -= digit;
520                               *p++ = '0' + digit;
521                               if ((flags & FLAG_ALT)
522                                   || mantissa > 0.0L || precision > 0)
523                                 {
524                                   *p++ = decimal_point_char ();
525                                   /* This loop terminates because we assume
526                                      that FLT_RADIX is a power of 2.  */
527                                   while (mantissa > 0.0L)
528                                     {
529                                       mantissa *= 16.0L;
530                                       digit = (int) mantissa;
531                                       mantissa -= digit;
532                                       *p++ = digit
533                                              + (digit < 10
534                                                 ? '0'
535                                                 : dp->conversion - 10);
536                                       if (precision > 0)
537                                         precision--;
538                                     }
539                                   while (precision > 0)
540                                     {
541                                       *p++ = '0';
542                                       precision--;
543                                     }
544                                 }
545                               }
546                               *p++ = dp->conversion - 'A' + 'P';
547 # if WIDE_CHAR_VERSION
548                               {
549                                 static const wchar_t decimal_format[] =
550                                   { '%', '+', 'd', '\0' };
551                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
552                               }
553 # else
554                               sprintf (p, "%+d", exponent);
555 # endif
556                               while (*p != '\0')
557                                 p++;
558                           }
559
560                         END_LONG_DOUBLE_ROUNDING ();
561                       }
562                   }
563                 else
564                   {
565                     double arg = a.arg[dp->arg_index].a.a_double;
566
567                     if (isnan (arg))
568                       {
569                         if (dp->conversion == 'A')
570                           {
571                             *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
572                           }
573                         else
574                           {
575                             *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
576                           }
577                       }
578                     else
579                       {
580                         int sign = 0;
581
582                         if (signbit (arg)) /* arg < 0.0 or negative zero */
583                           {
584                             sign = -1;
585                             arg = -arg;
586                           }
587
588                         if (sign < 0)
589                           *p++ = '-';
590                         else if (flags & FLAG_SHOWSIGN)
591                           *p++ = '+';
592                         else if (flags & FLAG_SPACE)
593                           *p++ = ' ';
594
595                         if (arg > 0.0 && arg + arg == arg)
596                           {
597                             if (dp->conversion == 'A')
598                               {
599                                 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
600                               }
601                             else
602                               {
603                                 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
604                               }
605                           }
606                         else
607                           {
608                             int exponent;
609                             double mantissa;
610
611                             if (arg > 0.0)
612                               mantissa = printf_frexp (arg, &exponent);
613                             else
614                               {
615                                 exponent = 0;
616                                 mantissa = 0.0;
617                               }
618
619                             if (has_precision
620                                 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
621                               {
622                                 /* Round the mantissa.  */
623                                 double tail = mantissa;
624                                 size_t q;
625
626                                 for (q = precision; ; q--)
627                                   {
628                                     int digit = (int) tail;
629                                     tail -= digit;
630                                     if (q == 0)
631                                       {
632                                         if (digit & 1 ? tail >= 0.5 : tail > 0.5)
633                                           tail = 1 - tail;
634                                         else
635                                           tail = - tail;
636                                         break;
637                                       }
638                                     tail *= 16.0;
639                                   }
640                                 if (tail != 0.0)
641                                   for (q = precision; q > 0; q--)
642                                     tail *= 0.0625;
643                                 mantissa += tail;
644                               }
645
646                             *p++ = '0';
647                             *p++ = dp->conversion - 'A' + 'X';
648                             pad_ptr = p;
649                             {
650                               int digit;
651
652                               digit = (int) mantissa;
653                               mantissa -= digit;
654                               *p++ = '0' + digit;
655                               if ((flags & FLAG_ALT)
656                                   || mantissa > 0.0 || precision > 0)
657                                 {
658                                   *p++ = decimal_point_char ();
659                                   /* This loop terminates because we assume
660                                      that FLT_RADIX is a power of 2.  */
661                                   while (mantissa > 0.0)
662                                     {
663                                       mantissa *= 16.0;
664                                       digit = (int) mantissa;
665                                       mantissa -= digit;
666                                       *p++ = digit
667                                              + (digit < 10
668                                                 ? '0'
669                                                 : dp->conversion - 10);
670                                       if (precision > 0)
671                                         precision--;
672                                     }
673                                   while (precision > 0)
674                                     {
675                                       *p++ = '0';
676                                       precision--;
677                                     }
678                                 }
679                               }
680                               *p++ = dp->conversion - 'A' + 'P';
681 # if WIDE_CHAR_VERSION
682                               {
683                                 static const wchar_t decimal_format[] =
684                                   { '%', '+', 'd', '\0' };
685                                 SNPRINTF (p, 6 + 1, decimal_format, exponent);
686                               }
687 # else
688                               sprintf (p, "%+d", exponent);
689 # endif
690                               while (*p != '\0')
691                                 p++;
692                           }
693                       }
694                   }
695                 /* The generated string now extends from tmp to p, with the
696                    zero padding insertion point being at pad_ptr.  */
697                 if (has_width && p - tmp < width)
698                   {
699                     size_t pad = width - (p - tmp);
700                     CHAR_T *end = p + pad;
701
702                     if (flags & FLAG_LEFT)
703                       {
704                         /* Pad with spaces on the right.  */
705                         for (; pad > 0; pad--)
706                           *p++ = ' ';
707                       }
708                     else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
709                       {
710                         /* Pad with zeroes.  */
711                         CHAR_T *q = end;
712
713                         while (p > pad_ptr)
714                           *--q = *--p;
715                         for (; pad > 0; pad--)
716                           *p++ = '0';
717                       }
718                     else
719                       {
720                         /* Pad with spaces on the left.  */
721                         CHAR_T *q = end;
722
723                         while (p > tmp)
724                           *--q = *--p;
725                         for (; pad > 0; pad--)
726                           *p++ = ' ';
727                       }
728
729                     p = end;
730                   }
731
732                 {
733                   size_t count = p - tmp;
734
735                   if (count >= tmp_length)
736                     /* tmp_length was incorrectly calculated - fix the
737                        code above!  */
738                     abort ();
739
740                   /* Make room for the result.  */
741                   if (count >= allocated - length)
742                     {
743                       size_t n = xsum (length, count);
744
745                       ENSURE_ALLOCATION (n);
746                     }
747
748                   /* Append the result.  */
749                   memcpy (result + length, tmp, count * sizeof (CHAR_T));
750                   if (tmp != tmpbuf)
751                     free (tmp);
752                   length += count;
753                 }
754               }
755 #endif
756             else
757               {
758                 arg_type type = a.arg[dp->arg_index].type;
759                 CHAR_T *p;
760                 unsigned int prefix_count;
761                 int prefixes[2];
762 #if !USE_SNPRINTF
763                 size_t tmp_length;
764                 CHAR_T tmpbuf[700];
765                 CHAR_T *tmp;
766
767                 /* Allocate a temporary buffer of sufficient size for calling
768                    sprintf.  */
769                 {
770                   size_t width;
771                   size_t precision;
772
773                   width = 0;
774                   if (dp->width_start != dp->width_end)
775                     {
776                       if (dp->width_arg_index != ARG_NONE)
777                         {
778                           int arg;
779
780                           if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
781                             abort ();
782                           arg = a.arg[dp->width_arg_index].a.a_int;
783                           width = (arg < 0 ? (unsigned int) (-arg) : arg);
784                         }
785                       else
786                         {
787                           const CHAR_T *digitp = dp->width_start;
788
789                           do
790                             width = xsum (xtimes (width, 10), *digitp++ - '0');
791                           while (digitp != dp->width_end);
792                         }
793                     }
794
795                   precision = 6;
796                   if (dp->precision_start != dp->precision_end)
797                     {
798                       if (dp->precision_arg_index != ARG_NONE)
799                         {
800                           int arg;
801
802                           if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
803                             abort ();
804                           arg = a.arg[dp->precision_arg_index].a.a_int;
805                           precision = (arg < 0 ? 0 : arg);
806                         }
807                       else
808                         {
809                           const CHAR_T *digitp = dp->precision_start + 1;
810
811                           precision = 0;
812                           while (digitp != dp->precision_end)
813                             precision = xsum (xtimes (precision, 10), *digitp++ - '0');
814                         }
815                     }
816
817                   switch (dp->conversion)
818                     {
819
820                     case 'd': case 'i': case 'u':
821 # if HAVE_LONG_LONG_INT
822                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
823                         tmp_length =
824                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
825                                           * 0.30103 /* binary -> decimal */
826                                          )
827                           + 1; /* turn floor into ceil */
828                       else
829 # endif
830                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
831                         tmp_length =
832                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
833                                           * 0.30103 /* binary -> decimal */
834                                          )
835                           + 1; /* turn floor into ceil */
836                       else
837                         tmp_length =
838                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
839                                           * 0.30103 /* binary -> decimal */
840                                          )
841                           + 1; /* turn floor into ceil */
842                       if (tmp_length < precision)
843                         tmp_length = precision;
844                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
845                       tmp_length = xsum (tmp_length, tmp_length);
846                       /* Add 1, to account for a leading sign.  */
847                       tmp_length = xsum (tmp_length, 1);
848                       break;
849
850                     case 'o':
851 # if HAVE_LONG_LONG_INT
852                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
853                         tmp_length =
854                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
855                                           * 0.333334 /* binary -> octal */
856                                          )
857                           + 1; /* turn floor into ceil */
858                       else
859 # endif
860                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
861                         tmp_length =
862                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
863                                           * 0.333334 /* binary -> octal */
864                                          )
865                           + 1; /* turn floor into ceil */
866                       else
867                         tmp_length =
868                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
869                                           * 0.333334 /* binary -> octal */
870                                          )
871                           + 1; /* turn floor into ceil */
872                       if (tmp_length < precision)
873                         tmp_length = precision;
874                       /* Add 1, to account for a leading sign.  */
875                       tmp_length = xsum (tmp_length, 1);
876                       break;
877
878                     case 'x': case 'X':
879 # if HAVE_LONG_LONG_INT
880                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
881                         tmp_length =
882                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
883                                           * 0.25 /* binary -> hexadecimal */
884                                          )
885                           + 1; /* turn floor into ceil */
886                       else
887 # endif
888                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
889                         tmp_length =
890                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
891                                           * 0.25 /* binary -> hexadecimal */
892                                          )
893                           + 1; /* turn floor into ceil */
894                       else
895                         tmp_length =
896                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
897                                           * 0.25 /* binary -> hexadecimal */
898                                          )
899                           + 1; /* turn floor into ceil */
900                       if (tmp_length < precision)
901                         tmp_length = precision;
902                       /* Add 2, to account for a leading sign or alternate form.  */
903                       tmp_length = xsum (tmp_length, 2);
904                       break;
905
906                     case 'f': case 'F':
907                       if (type == TYPE_LONGDOUBLE)
908                         tmp_length =
909                           (unsigned int) (LDBL_MAX_EXP
910                                           * 0.30103 /* binary -> decimal */
911                                           * 2 /* estimate for FLAG_GROUP */
912                                          )
913                           + 1 /* turn floor into ceil */
914                           + 10; /* sign, decimal point etc. */
915                       else
916                         tmp_length =
917                           (unsigned int) (DBL_MAX_EXP
918                                           * 0.30103 /* binary -> decimal */
919                                           * 2 /* estimate for FLAG_GROUP */
920                                          )
921                           + 1 /* turn floor into ceil */
922                           + 10; /* sign, decimal point etc. */
923                       tmp_length = xsum (tmp_length, precision);
924                       break;
925
926                     case 'e': case 'E': case 'g': case 'G':
927                       tmp_length =
928                         12; /* sign, decimal point, exponent etc. */
929                       tmp_length = xsum (tmp_length, precision);
930                       break;
931
932                     case 'a': case 'A':
933                       if (type == TYPE_LONGDOUBLE)
934                         tmp_length =
935                           (unsigned int) (LDBL_DIG
936                                           * 0.831 /* decimal -> hexadecimal */
937                                          )
938                           + 1; /* turn floor into ceil */
939                       else
940                         tmp_length =
941                           (unsigned int) (DBL_DIG
942                                           * 0.831 /* decimal -> hexadecimal */
943                                          )
944                           + 1; /* turn floor into ceil */
945                       if (tmp_length < precision)
946                         tmp_length = precision;
947                       /* Account for sign, decimal point etc. */
948                       tmp_length = xsum (tmp_length, 12);
949                       break;
950
951                     case 'c':
952 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
953                       if (type == TYPE_WIDE_CHAR)
954                         tmp_length = MB_CUR_MAX;
955                       else
956 # endif
957                         tmp_length = 1;
958                       break;
959
960                     case 's':
961 # if HAVE_WCHAR_T
962                       if (type == TYPE_WIDE_STRING)
963                         {
964                           tmp_length =
965                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
966
967 #  if !WIDE_CHAR_VERSION
968                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
969 #  endif
970                         }
971                       else
972 # endif
973                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
974                       break;
975
976                     case 'p':
977                       tmp_length =
978                         (unsigned int) (sizeof (void *) * CHAR_BIT
979                                         * 0.25 /* binary -> hexadecimal */
980                                        )
981                           + 1 /* turn floor into ceil */
982                           + 2; /* account for leading 0x */
983                       break;
984
985                     default:
986                       abort ();
987                     }
988
989                   if (tmp_length < width)
990                     tmp_length = width;
991
992                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
993                 }
994
995                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
996                   tmp = tmpbuf;
997                 else
998                   {
999                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
1000
1001                     if (size_overflow_p (tmp_memsize))
1002                       /* Overflow, would lead to out of memory.  */
1003                       goto out_of_memory;
1004                     tmp = (CHAR_T *) malloc (tmp_memsize);
1005                     if (tmp == NULL)
1006                       /* Out of memory.  */
1007                       goto out_of_memory;
1008                   }
1009 #endif
1010
1011                 /* Construct the format string for calling snprintf or
1012                    sprintf.  */
1013                 p = buf;
1014                 *p++ = '%';
1015 #if NEED_PRINTF_FLAG_GROUPING
1016                 /* The underlying implementation doesn't support the ' flag.
1017                    Produce no grouping characters in this case; this is
1018                    acceptable because the grouping is locale dependent.  */
1019 #else
1020                 if (dp->flags & FLAG_GROUP)
1021                   *p++ = '\'';
1022 #endif
1023                 if (dp->flags & FLAG_LEFT)
1024                   *p++ = '-';
1025                 if (dp->flags & FLAG_SHOWSIGN)
1026                   *p++ = '+';
1027                 if (dp->flags & FLAG_SPACE)
1028                   *p++ = ' ';
1029                 if (dp->flags & FLAG_ALT)
1030                   *p++ = '#';
1031                 if (dp->flags & FLAG_ZERO)
1032                   *p++ = '0';
1033                 if (dp->width_start != dp->width_end)
1034                   {
1035                     size_t n = dp->width_end - dp->width_start;
1036                     memcpy (p, dp->width_start, n * sizeof (CHAR_T));
1037                     p += n;
1038                   }
1039                 if (dp->precision_start != dp->precision_end)
1040                   {
1041                     size_t n = dp->precision_end - dp->precision_start;
1042                     memcpy (p, dp->precision_start, n * sizeof (CHAR_T));
1043                     p += n;
1044                   }
1045
1046                 switch (type)
1047                   {
1048 #if HAVE_LONG_LONG_INT
1049                   case TYPE_LONGLONGINT:
1050                   case TYPE_ULONGLONGINT:
1051                     *p++ = 'l';
1052                     /*FALLTHROUGH*/
1053 #endif
1054                   case TYPE_LONGINT:
1055                   case TYPE_ULONGINT:
1056 #if HAVE_WINT_T
1057                   case TYPE_WIDE_CHAR:
1058 #endif
1059 #if HAVE_WCHAR_T
1060                   case TYPE_WIDE_STRING:
1061 #endif
1062                     *p++ = 'l';
1063                     break;
1064                   case TYPE_LONGDOUBLE:
1065                     *p++ = 'L';
1066                     break;
1067                   default:
1068                     break;
1069                   }
1070 #if NEED_PRINTF_DIRECTIVE_F
1071                 if (dp->conversion == 'F')
1072                   *p = 'f';
1073                 else
1074 #endif
1075                   *p = dp->conversion;
1076 #if USE_SNPRINTF
1077                 p[1] = '%';
1078                 p[2] = 'n';
1079                 p[3] = '\0';
1080 #else
1081                 p[1] = '\0';
1082 #endif
1083
1084                 /* Construct the arguments for calling snprintf or sprintf.  */
1085                 prefix_count = 0;
1086                 if (dp->width_arg_index != ARG_NONE)
1087                   {
1088                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
1089                       abort ();
1090                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
1091                   }
1092                 if (dp->precision_arg_index != ARG_NONE)
1093                   {
1094                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
1095                       abort ();
1096                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
1097                   }
1098
1099 #if USE_SNPRINTF
1100                 /* Prepare checking whether snprintf returns the count
1101                    via %n.  */
1102                 ENSURE_ALLOCATION (xsum (length, 1));
1103                 result[length] = '\0';
1104 #endif
1105
1106                 for (;;)
1107                   {
1108                     size_t maxlen;
1109                     int count;
1110                     int retcount;
1111
1112                     maxlen = allocated - length;
1113                     count = -1;
1114                     retcount = 0;
1115
1116 #if USE_SNPRINTF
1117                     /* SNPRINTF can fail if maxlen > INT_MAX.  */
1118                     if (maxlen > INT_MAX)
1119                       goto overflow;
1120 # define SNPRINTF_BUF(arg) \
1121                     switch (prefix_count)                                   \
1122                       {                                                     \
1123                       case 0:                                               \
1124                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1125                                              arg, &count);                  \
1126                         break;                                              \
1127                       case 1:                                               \
1128                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1129                                              prefixes[0], arg, &count);     \
1130                         break;                                              \
1131                       case 2:                                               \
1132                         retcount = SNPRINTF (result + length, maxlen, buf,  \
1133                                              prefixes[0], prefixes[1], arg, \
1134                                              &count);                       \
1135                         break;                                              \
1136                       default:                                              \
1137                         abort ();                                           \
1138                       }
1139 #else
1140 # define SNPRINTF_BUF(arg) \
1141                     switch (prefix_count)                                   \
1142                       {                                                     \
1143                       case 0:                                               \
1144                         count = sprintf (tmp, buf, arg);                    \
1145                         break;                                              \
1146                       case 1:                                               \
1147                         count = sprintf (tmp, buf, prefixes[0], arg);       \
1148                         break;                                              \
1149                       case 2:                                               \
1150                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
1151                                          arg);                              \
1152                         break;                                              \
1153                       default:                                              \
1154                         abort ();                                           \
1155                       }
1156 #endif
1157
1158                     switch (type)
1159                       {
1160                       case TYPE_SCHAR:
1161                         {
1162                           int arg = a.arg[dp->arg_index].a.a_schar;
1163                           SNPRINTF_BUF (arg);
1164                         }
1165                         break;
1166                       case TYPE_UCHAR:
1167                         {
1168                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
1169                           SNPRINTF_BUF (arg);
1170                         }
1171                         break;
1172                       case TYPE_SHORT:
1173                         {
1174                           int arg = a.arg[dp->arg_index].a.a_short;
1175                           SNPRINTF_BUF (arg);
1176                         }
1177                         break;
1178                       case TYPE_USHORT:
1179                         {
1180                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
1181                           SNPRINTF_BUF (arg);
1182                         }
1183                         break;
1184                       case TYPE_INT:
1185                         {
1186                           int arg = a.arg[dp->arg_index].a.a_int;
1187                           SNPRINTF_BUF (arg);
1188                         }
1189                         break;
1190                       case TYPE_UINT:
1191                         {
1192                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
1193                           SNPRINTF_BUF (arg);
1194                         }
1195                         break;
1196                       case TYPE_LONGINT:
1197                         {
1198                           long int arg = a.arg[dp->arg_index].a.a_longint;
1199                           SNPRINTF_BUF (arg);
1200                         }
1201                         break;
1202                       case TYPE_ULONGINT:
1203                         {
1204                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
1205                           SNPRINTF_BUF (arg);
1206                         }
1207                         break;
1208 #if HAVE_LONG_LONG_INT
1209                       case TYPE_LONGLONGINT:
1210                         {
1211                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
1212                           SNPRINTF_BUF (arg);
1213                         }
1214                         break;
1215                       case TYPE_ULONGLONGINT:
1216                         {
1217                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
1218                           SNPRINTF_BUF (arg);
1219                         }
1220                         break;
1221 #endif
1222                       case TYPE_DOUBLE:
1223                         {
1224                           double arg = a.arg[dp->arg_index].a.a_double;
1225                           SNPRINTF_BUF (arg);
1226                         }
1227                         break;
1228                       case TYPE_LONGDOUBLE:
1229                         {
1230                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
1231                           SNPRINTF_BUF (arg);
1232                         }
1233                         break;
1234                       case TYPE_CHAR:
1235                         {
1236                           int arg = a.arg[dp->arg_index].a.a_char;
1237                           SNPRINTF_BUF (arg);
1238                         }
1239                         break;
1240 #if HAVE_WINT_T
1241                       case TYPE_WIDE_CHAR:
1242                         {
1243                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
1244                           SNPRINTF_BUF (arg);
1245                         }
1246                         break;
1247 #endif
1248                       case TYPE_STRING:
1249                         {
1250                           const char *arg = a.arg[dp->arg_index].a.a_string;
1251                           SNPRINTF_BUF (arg);
1252                         }
1253                         break;
1254 #if HAVE_WCHAR_T
1255                       case TYPE_WIDE_STRING:
1256                         {
1257                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
1258                           SNPRINTF_BUF (arg);
1259                         }
1260                         break;
1261 #endif
1262                       case TYPE_POINTER:
1263                         {
1264                           void *arg = a.arg[dp->arg_index].a.a_pointer;
1265                           SNPRINTF_BUF (arg);
1266                         }
1267                         break;
1268                       default:
1269                         abort ();
1270                       }
1271
1272 #if USE_SNPRINTF
1273                     /* Portability: Not all implementations of snprintf()
1274                        are ISO C 99 compliant.  Determine the number of
1275                        bytes that snprintf() has produced or would have
1276                        produced.  */
1277                     if (count >= 0)
1278                       {
1279                         /* Verify that snprintf() has NUL-terminated its
1280                            result.  */
1281                         if (count < maxlen && result[length + count] != '\0')
1282                           abort ();
1283                         /* Portability hack.  */
1284                         if (retcount > count)
1285                           count = retcount;
1286                       }
1287                     else
1288                       {
1289                         /* snprintf() doesn't understand the '%n'
1290                            directive.  */
1291                         if (p[1] != '\0')
1292                           {
1293                             /* Don't use the '%n' directive; instead, look
1294                                at the snprintf() return value.  */
1295                             p[1] = '\0';
1296                             continue;
1297                           }
1298                         else
1299                           {
1300                             /* Look at the snprintf() return value.  */
1301                             if (retcount < 0)
1302                               {
1303                                 /* HP-UX 10.20 snprintf() is doubly deficient:
1304                                    It doesn't understand the '%n' directive,
1305                                    *and* it returns -1 (rather than the length
1306                                    that would have been required) when the
1307                                    buffer is too small.  */
1308                                 size_t bigger_need =
1309                                   xsum (xtimes (allocated, 2), 12);
1310                                 ENSURE_ALLOCATION (bigger_need);
1311                                 continue;
1312                               }
1313                             else
1314                               count = retcount;
1315                           }
1316                       }
1317 #endif
1318
1319                     /* Attempt to handle failure.  */
1320                     if (count < 0)
1321                       {
1322                         if (!(result == resultbuf || result == NULL))
1323                           free (result);
1324                         if (buf_malloced != NULL)
1325                           free (buf_malloced);
1326                         CLEANUP ();
1327                         errno = EINVAL;
1328                         return NULL;
1329                       }
1330
1331 #if !USE_SNPRINTF
1332                     if (count >= tmp_length)
1333                       /* tmp_length was incorrectly calculated - fix the
1334                          code above!  */
1335                       abort ();
1336 #endif
1337
1338                     /* Make room for the result.  */
1339                     if (count >= maxlen)
1340                       {
1341                         /* Need at least count bytes.  But allocate
1342                            proportionally, to avoid looping eternally if
1343                            snprintf() reports a too small count.  */
1344                         size_t n =
1345                           xmax (xsum (length, count), xtimes (allocated, 2));
1346
1347                         ENSURE_ALLOCATION (n);
1348 #if USE_SNPRINTF
1349                         continue;
1350 #endif
1351                       }
1352
1353 #if USE_SNPRINTF
1354                     /* The snprintf() result did fit.  */
1355 #else
1356                     /* Append the sprintf() result.  */
1357                     memcpy (result + length, tmp, count * sizeof (CHAR_T));
1358                     if (tmp != tmpbuf)
1359                       free (tmp);
1360 #endif
1361
1362 #if NEED_PRINTF_DIRECTIVE_F
1363                     if (dp->conversion == 'F')
1364                       {
1365                         /* Convert the %f result to upper case for %F.  */
1366                         CHAR_T *rp = result + length;
1367                         size_t rc;
1368                         for (rc = count; rc > 0; rc--, rp++)
1369                           if (*rp >= 'a' && *rp <= 'z')
1370                             *rp = *rp - 'a' + 'A';
1371                       }
1372 #endif
1373
1374                     length += count;
1375                     break;
1376                   }
1377               }
1378           }
1379       }
1380
1381     /* Add the final NUL.  */
1382     ENSURE_ALLOCATION (xsum (length, 1));
1383     result[length] = '\0';
1384
1385     if (result != resultbuf && length + 1 < allocated)
1386       {
1387         /* Shrink the allocated memory if possible.  */
1388         CHAR_T *memory;
1389
1390         memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
1391         if (memory != NULL)
1392           result = memory;
1393       }
1394
1395     if (buf_malloced != NULL)
1396       free (buf_malloced);
1397     CLEANUP ();
1398     *lengthp = length;
1399     /* Note that we can produce a big string of a length > INT_MAX.  POSIX
1400        says that snprintf() fails with errno = EOVERFLOW in this case, but
1401        that's only because snprintf() returns an 'int'.  This function does
1402        not have this limitation.  */
1403     return result;
1404
1405   overflow:
1406     if (!(result == resultbuf || result == NULL))
1407       free (result);
1408     if (buf_malloced != NULL)
1409       free (buf_malloced);
1410     CLEANUP ();
1411     errno = EOVERFLOW;
1412     return NULL;
1413
1414   out_of_memory:
1415     if (!(result == resultbuf || result == NULL))
1416       free (result);
1417     if (buf_malloced != NULL)
1418       free (buf_malloced);
1419   out_of_memory_1:
1420     CLEANUP ();
1421     errno = ENOMEM;
1422     return NULL;
1423   }
1424 }
1425
1426 #undef SNPRINTF
1427 #undef USE_SNPRINTF
1428 #undef PRINTF_PARSE
1429 #undef DIRECTIVES
1430 #undef DIRECTIVE
1431 #undef CHAR_T
1432 #undef VASNPRINTF