Fix an incorrect estimation of the sprintf result size.
[gnulib.git] / lib / vasnprintf.c
1 /* vsprintf with automatic memory allocation.
2    Copyright (C) 1999, 2002-2006 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 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28 #ifndef IN_LIBINTL
29 # include <alloca.h>
30 #endif
31
32 /* Specification.  */
33 #if WIDE_CHAR_VERSION
34 # include "vasnwprintf.h"
35 #else
36 # include "vasnprintf.h"
37 #endif
38
39 #include <stdio.h>      /* snprintf(), sprintf() */
40 #include <stdlib.h>     /* abort(), malloc(), realloc(), free() */
41 #include <string.h>     /* memcpy(), strlen() */
42 #include <errno.h>      /* errno */
43 #include <limits.h>     /* CHAR_BIT, INT_MAX */
44 #include <float.h>      /* DBL_MAX_EXP, LDBL_MAX_EXP */
45 #if WIDE_CHAR_VERSION
46 # include "wprintf-parse.h"
47 #else
48 # include "printf-parse.h"
49 #endif
50
51 /* Checked size_t computations.  */
52 #include "xsize.h"
53
54 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW.  */
55 #ifndef EOVERFLOW
56 # define EOVERFLOW E2BIG
57 #endif
58
59 #ifdef HAVE_WCHAR_T
60 # ifdef HAVE_WCSLEN
61 #  define local_wcslen wcslen
62 # else
63    /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
64       a dependency towards this library, here is a local substitute.
65       Define this substitute only once, even if this file is included
66       twice in the same compilation unit.  */
67 #  ifndef local_wcslen_defined
68 #   define local_wcslen_defined 1
69 static size_t
70 local_wcslen (const wchar_t *s)
71 {
72   const wchar_t *ptr;
73
74   for (ptr = s; *ptr != (wchar_t) 0; ptr++)
75     ;
76   return ptr - s;
77 }
78 #  endif
79 # endif
80 #endif
81
82 #if WIDE_CHAR_VERSION
83 # define VASNPRINTF vasnwprintf
84 # define CHAR_T wchar_t
85 # define DIRECTIVE wchar_t_directive
86 # define DIRECTIVES wchar_t_directives
87 # define PRINTF_PARSE wprintf_parse
88 # define USE_SNPRINTF 1
89 # if HAVE_DECL__SNWPRINTF
90    /* On Windows, the function swprintf() has a different signature than
91       on Unix; we use the _snwprintf() function instead.  */
92 #  define SNPRINTF _snwprintf
93 # else
94    /* Unix.  */
95 #  define SNPRINTF swprintf
96 # endif
97 #else
98 # define VASNPRINTF vasnprintf
99 # define CHAR_T char
100 # define DIRECTIVE char_directive
101 # define DIRECTIVES char_directives
102 # define PRINTF_PARSE printf_parse
103 # define USE_SNPRINTF (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF)
104 # if HAVE_DECL__SNPRINTF
105    /* Windows.  */
106 #  define SNPRINTF _snprintf
107 # else
108    /* Unix.  */
109 #  define SNPRINTF snprintf
110 # endif
111 #endif
112
113 CHAR_T *
114 VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
115 {
116   DIRECTIVES d;
117   arguments a;
118
119   if (PRINTF_PARSE (format, &d, &a) < 0)
120     {
121       errno = EINVAL;
122       return NULL;
123     }
124
125 #define CLEANUP() \
126   free (d.dir);                                                         \
127   if (a.arg)                                                            \
128     free (a.arg);
129
130   if (printf_fetchargs (args, &a) < 0)
131     {
132       CLEANUP ();
133       errno = EINVAL;
134       return NULL;
135     }
136
137   {
138     size_t buf_neededlength;
139     CHAR_T *buf;
140     CHAR_T *buf_malloced;
141     const CHAR_T *cp;
142     size_t i;
143     DIRECTIVE *dp;
144     /* Output string accumulator.  */
145     CHAR_T *result;
146     size_t allocated;
147     size_t length;
148
149     /* Allocate a small buffer that will hold a directive passed to
150        sprintf or snprintf.  */
151     buf_neededlength =
152       xsum4 (7, d.max_width_length, d.max_precision_length, 6);
153 #if HAVE_ALLOCA
154     if (buf_neededlength < 4000 / sizeof (CHAR_T))
155       {
156         buf = (CHAR_T *) alloca (buf_neededlength * sizeof (CHAR_T));
157         buf_malloced = NULL;
158       }
159     else
160 #endif
161       {
162         size_t buf_memsize = xtimes (buf_neededlength, sizeof (CHAR_T));
163         if (size_overflow_p (buf_memsize))
164           goto out_of_memory_1;
165         buf = (CHAR_T *) malloc (buf_memsize);
166         if (buf == NULL)
167           goto out_of_memory_1;
168         buf_malloced = buf;
169       }
170
171     if (resultbuf != NULL)
172       {
173         result = resultbuf;
174         allocated = *lengthp;
175       }
176     else
177       {
178         result = NULL;
179         allocated = 0;
180       }
181     length = 0;
182     /* Invariants:
183        result is either == resultbuf or == NULL or malloc-allocated.
184        If length > 0, then result != NULL.  */
185
186     /* Ensures that allocated >= needed.  Aborts through a jump to
187        out_of_memory if needed is SIZE_MAX or otherwise too big.  */
188 #define ENSURE_ALLOCATION(needed) \
189     if ((needed) > allocated)                                                \
190       {                                                                      \
191         size_t memory_size;                                                  \
192         CHAR_T *memory;                                                      \
193                                                                              \
194         allocated = (allocated > 0 ? xtimes (allocated, 2) : 12);            \
195         if ((needed) > allocated)                                            \
196           allocated = (needed);                                              \
197         memory_size = xtimes (allocated, sizeof (CHAR_T));                   \
198         if (size_overflow_p (memory_size))                                   \
199           goto out_of_memory;                                                \
200         if (result == resultbuf || result == NULL)                           \
201           memory = (CHAR_T *) malloc (memory_size);                          \
202         else                                                                 \
203           memory = (CHAR_T *) realloc (result, memory_size);                 \
204         if (memory == NULL)                                                  \
205           goto out_of_memory;                                                \
206         if (result == resultbuf && length > 0)                               \
207           memcpy (memory, result, length * sizeof (CHAR_T));                 \
208         result = memory;                                                     \
209       }
210
211     for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
212       {
213         if (cp != dp->dir_start)
214           {
215             size_t n = dp->dir_start - cp;
216             size_t augmented_length = xsum (length, n);
217
218             ENSURE_ALLOCATION (augmented_length);
219             memcpy (result + length, cp, n * sizeof (CHAR_T));
220             length = augmented_length;
221           }
222         if (i == d.count)
223           break;
224
225         /* Execute a single directive.  */
226         if (dp->conversion == '%')
227           {
228             size_t augmented_length;
229
230             if (!(dp->arg_index == ARG_NONE))
231               abort ();
232             augmented_length = xsum (length, 1);
233             ENSURE_ALLOCATION (augmented_length);
234             result[length] = '%';
235             length = augmented_length;
236           }
237         else
238           {
239             if (!(dp->arg_index != ARG_NONE))
240               abort ();
241
242             if (dp->conversion == 'n')
243               {
244                 switch (a.arg[dp->arg_index].type)
245                   {
246                   case TYPE_COUNT_SCHAR_POINTER:
247                     *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
248                     break;
249                   case TYPE_COUNT_SHORT_POINTER:
250                     *a.arg[dp->arg_index].a.a_count_short_pointer = length;
251                     break;
252                   case TYPE_COUNT_INT_POINTER:
253                     *a.arg[dp->arg_index].a.a_count_int_pointer = length;
254                     break;
255                   case TYPE_COUNT_LONGINT_POINTER:
256                     *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
257                     break;
258 #ifdef HAVE_LONG_LONG
259                   case TYPE_COUNT_LONGLONGINT_POINTER:
260                     *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
261                     break;
262 #endif
263                   default:
264                     abort ();
265                   }
266               }
267             else
268               {
269                 arg_type type = a.arg[dp->arg_index].type;
270                 CHAR_T *p;
271                 unsigned int prefix_count;
272                 int prefixes[2];
273 #if !USE_SNPRINTF
274                 size_t tmp_length;
275                 CHAR_T tmpbuf[700];
276                 CHAR_T *tmp;
277
278                 /* Allocate a temporary buffer of sufficient size for calling
279                    sprintf.  */
280                 {
281                   size_t width;
282                   size_t precision;
283
284                   width = 0;
285                   if (dp->width_start != dp->width_end)
286                     {
287                       if (dp->width_arg_index != ARG_NONE)
288                         {
289                           int arg;
290
291                           if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
292                             abort ();
293                           arg = a.arg[dp->width_arg_index].a.a_int;
294                           width = (arg < 0 ? (unsigned int) (-arg) : arg);
295                         }
296                       else
297                         {
298                           const CHAR_T *digitp = dp->width_start;
299
300                           do
301                             width = xsum (xtimes (width, 10), *digitp++ - '0');
302                           while (digitp != dp->width_end);
303                         }
304                     }
305
306                   precision = 6;
307                   if (dp->precision_start != dp->precision_end)
308                     {
309                       if (dp->precision_arg_index != ARG_NONE)
310                         {
311                           int arg;
312
313                           if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
314                             abort ();
315                           arg = a.arg[dp->precision_arg_index].a.a_int;
316                           precision = (arg < 0 ? 0 : arg);
317                         }
318                       else
319                         {
320                           const CHAR_T *digitp = dp->precision_start + 1;
321
322                           precision = 0;
323                           while (digitp != dp->precision_end)
324                             precision = xsum (xtimes (precision, 10), *digitp++ - '0');
325                         }
326                     }
327
328                   switch (dp->conversion)
329                     {
330
331                     case 'd': case 'i': case 'u':
332 # ifdef HAVE_LONG_LONG
333                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
334                         tmp_length =
335                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
336                                           * 0.30103 /* binary -> decimal */
337                                          )
338                           + 1; /* turn floor into ceil */
339                       else
340 # endif
341                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
342                         tmp_length =
343                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
344                                           * 0.30103 /* binary -> decimal */
345                                          )
346                           + 1; /* turn floor into ceil */
347                       else
348                         tmp_length =
349                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
350                                           * 0.30103 /* binary -> decimal */
351                                          )
352                           + 1; /* turn floor into ceil */
353                       if (tmp_length < precision)
354                         tmp_length = precision;
355                       /* Multiply by 2, as an estimate for FLAG_GROUP.  */
356                       tmp_length = xsum (tmp_length, tmp_length);
357                       /* Add 1, to account for a leading sign.  */
358                       tmp_length = xsum (tmp_length, 1);
359                       break;
360
361                     case 'o':
362 # ifdef HAVE_LONG_LONG
363                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
364                         tmp_length =
365                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
366                                           * 0.333334 /* binary -> octal */
367                                          )
368                           + 1; /* turn floor into ceil */
369                       else
370 # endif
371                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
372                         tmp_length =
373                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
374                                           * 0.333334 /* binary -> octal */
375                                          )
376                           + 1; /* turn floor into ceil */
377                       else
378                         tmp_length =
379                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
380                                           * 0.333334 /* binary -> octal */
381                                          )
382                           + 1; /* turn floor into ceil */
383                       if (tmp_length < precision)
384                         tmp_length = precision;
385                       /* Add 1, to account for a leading sign.  */
386                       tmp_length = xsum (tmp_length, 1);
387                       break;
388
389                     case 'x': case 'X':
390 # ifdef HAVE_LONG_LONG
391                       if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
392                         tmp_length =
393                           (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
394                                           * 0.25 /* binary -> hexadecimal */
395                                          )
396                           + 1; /* turn floor into ceil */
397                       else
398 # endif
399                       if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
400                         tmp_length =
401                           (unsigned int) (sizeof (unsigned long) * CHAR_BIT
402                                           * 0.25 /* binary -> hexadecimal */
403                                          )
404                           + 1; /* turn floor into ceil */
405                       else
406                         tmp_length =
407                           (unsigned int) (sizeof (unsigned int) * CHAR_BIT
408                                           * 0.25 /* binary -> hexadecimal */
409                                          )
410                           + 1; /* turn floor into ceil */
411                       if (tmp_length < precision)
412                         tmp_length = precision;
413                       /* Add 2, to account for a leading sign or alternate form.  */
414                       tmp_length = xsum (tmp_length, 2);
415                       break;
416
417                     case 'f': case 'F':
418 # ifdef HAVE_LONG_DOUBLE
419                       if (type == TYPE_LONGDOUBLE)
420                         tmp_length =
421                           (unsigned int) (LDBL_MAX_EXP
422                                           * 0.30103 /* binary -> decimal */
423                                           * 2 /* estimate for FLAG_GROUP */
424                                          )
425                           + 1 /* turn floor into ceil */
426                           + 10; /* sign, decimal point etc. */
427                       else
428 # endif
429                         tmp_length =
430                           (unsigned int) (DBL_MAX_EXP
431                                           * 0.30103 /* binary -> decimal */
432                                           * 2 /* estimate for FLAG_GROUP */
433                                          )
434                           + 1 /* turn floor into ceil */
435                           + 10; /* sign, decimal point etc. */
436                       tmp_length = xsum (tmp_length, precision);
437                       break;
438
439                     case 'e': case 'E': case 'g': case 'G':
440                     case 'a': case 'A':
441                       tmp_length =
442                         12; /* sign, decimal point, exponent etc. */
443                       tmp_length = xsum (tmp_length, precision);
444                       break;
445
446                     case 'c':
447 # if defined HAVE_WINT_T && !WIDE_CHAR_VERSION
448                       if (type == TYPE_WIDE_CHAR)
449                         tmp_length = MB_CUR_MAX;
450                       else
451 # endif
452                         tmp_length = 1;
453                       break;
454
455                     case 's':
456 # ifdef HAVE_WCHAR_T
457                       if (type == TYPE_WIDE_STRING)
458                         {
459                           tmp_length =
460                             local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
461
462 #  if !WIDE_CHAR_VERSION
463                           tmp_length = xtimes (tmp_length, MB_CUR_MAX);
464 #  endif
465                         }
466                       else
467 # endif
468                         tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
469                       break;
470
471                     case 'p':
472                       tmp_length =
473                         (unsigned int) (sizeof (void *) * CHAR_BIT
474                                         * 0.25 /* binary -> hexadecimal */
475                                        )
476                           + 1 /* turn floor into ceil */
477                           + 2; /* account for leading 0x */
478                       break;
479
480                     default:
481                       abort ();
482                     }
483
484                   if (tmp_length < width)
485                     tmp_length = width;
486
487                   tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
488                 }
489
490                 if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
491                   tmp = tmpbuf;
492                 else
493                   {
494                     size_t tmp_memsize = xtimes (tmp_length, sizeof (CHAR_T));
495
496                     if (size_overflow_p (tmp_memsize))
497                       /* Overflow, would lead to out of memory.  */
498                       goto out_of_memory;
499                     tmp = (CHAR_T *) malloc (tmp_memsize);
500                     if (tmp == NULL)
501                       /* Out of memory.  */
502                       goto out_of_memory;
503                   }
504 #endif
505
506                 /* Construct the format string for calling snprintf or
507                    sprintf.  */
508                 p = buf;
509                 *p++ = '%';
510                 if (dp->flags & FLAG_GROUP)
511                   *p++ = '\'';
512                 if (dp->flags & FLAG_LEFT)
513                   *p++ = '-';
514                 if (dp->flags & FLAG_SHOWSIGN)
515                   *p++ = '+';
516                 if (dp->flags & FLAG_SPACE)
517                   *p++ = ' ';
518                 if (dp->flags & FLAG_ALT)
519                   *p++ = '#';
520                 if (dp->flags & FLAG_ZERO)
521                   *p++ = '0';
522                 if (dp->width_start != dp->width_end)
523                   {
524                     size_t n = dp->width_end - dp->width_start;
525                     memcpy (p, dp->width_start, n * sizeof (CHAR_T));
526                     p += n;
527                   }
528                 if (dp->precision_start != dp->precision_end)
529                   {
530                     size_t n = dp->precision_end - dp->precision_start;
531                     memcpy (p, dp->precision_start, n * sizeof (CHAR_T));
532                     p += n;
533                   }
534
535                 switch (type)
536                   {
537 #ifdef HAVE_LONG_LONG
538                   case TYPE_LONGLONGINT:
539                   case TYPE_ULONGLONGINT:
540                     *p++ = 'l';
541                     /*FALLTHROUGH*/
542 #endif
543                   case TYPE_LONGINT:
544                   case TYPE_ULONGINT:
545 #ifdef HAVE_WINT_T
546                   case TYPE_WIDE_CHAR:
547 #endif
548 #ifdef HAVE_WCHAR_T
549                   case TYPE_WIDE_STRING:
550 #endif
551                     *p++ = 'l';
552                     break;
553 #ifdef HAVE_LONG_DOUBLE
554                   case TYPE_LONGDOUBLE:
555                     *p++ = 'L';
556                     break;
557 #endif
558                   default:
559                     break;
560                   }
561                 *p = dp->conversion;
562 #if USE_SNPRINTF
563                 p[1] = '%';
564                 p[2] = 'n';
565                 p[3] = '\0';
566 #else
567                 p[1] = '\0';
568 #endif
569
570                 /* Construct the arguments for calling snprintf or sprintf.  */
571                 prefix_count = 0;
572                 if (dp->width_arg_index != ARG_NONE)
573                   {
574                     if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
575                       abort ();
576                     prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
577                   }
578                 if (dp->precision_arg_index != ARG_NONE)
579                   {
580                     if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
581                       abort ();
582                     prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
583                   }
584
585 #if USE_SNPRINTF
586                 /* Prepare checking whether snprintf returns the count
587                    via %n.  */
588                 ENSURE_ALLOCATION (xsum (length, 1));
589                 result[length] = '\0';
590 #endif
591
592                 for (;;)
593                   {
594                     size_t maxlen;
595                     int count;
596                     int retcount;
597
598                     maxlen = allocated - length;
599                     count = -1;
600                     retcount = 0;
601
602 #if USE_SNPRINTF
603 # define SNPRINTF_BUF(arg) \
604                     switch (prefix_count)                                   \
605                       {                                                     \
606                       case 0:                                               \
607                         retcount = SNPRINTF (result + length, maxlen, buf,  \
608                                              arg, &count);                  \
609                         break;                                              \
610                       case 1:                                               \
611                         retcount = SNPRINTF (result + length, maxlen, buf,  \
612                                              prefixes[0], arg, &count);     \
613                         break;                                              \
614                       case 2:                                               \
615                         retcount = SNPRINTF (result + length, maxlen, buf,  \
616                                              prefixes[0], prefixes[1], arg, \
617                                              &count);                       \
618                         break;                                              \
619                       default:                                              \
620                         abort ();                                           \
621                       }
622 #else
623 # define SNPRINTF_BUF(arg) \
624                     switch (prefix_count)                                   \
625                       {                                                     \
626                       case 0:                                               \
627                         count = sprintf (tmp, buf, arg);                    \
628                         break;                                              \
629                       case 1:                                               \
630                         count = sprintf (tmp, buf, prefixes[0], arg);       \
631                         break;                                              \
632                       case 2:                                               \
633                         count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
634                                          arg);                              \
635                         break;                                              \
636                       default:                                              \
637                         abort ();                                           \
638                       }
639 #endif
640
641                     switch (type)
642                       {
643                       case TYPE_SCHAR:
644                         {
645                           int arg = a.arg[dp->arg_index].a.a_schar;
646                           SNPRINTF_BUF (arg);
647                         }
648                         break;
649                       case TYPE_UCHAR:
650                         {
651                           unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
652                           SNPRINTF_BUF (arg);
653                         }
654                         break;
655                       case TYPE_SHORT:
656                         {
657                           int arg = a.arg[dp->arg_index].a.a_short;
658                           SNPRINTF_BUF (arg);
659                         }
660                         break;
661                       case TYPE_USHORT:
662                         {
663                           unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
664                           SNPRINTF_BUF (arg);
665                         }
666                         break;
667                       case TYPE_INT:
668                         {
669                           int arg = a.arg[dp->arg_index].a.a_int;
670                           SNPRINTF_BUF (arg);
671                         }
672                         break;
673                       case TYPE_UINT:
674                         {
675                           unsigned int arg = a.arg[dp->arg_index].a.a_uint;
676                           SNPRINTF_BUF (arg);
677                         }
678                         break;
679                       case TYPE_LONGINT:
680                         {
681                           long int arg = a.arg[dp->arg_index].a.a_longint;
682                           SNPRINTF_BUF (arg);
683                         }
684                         break;
685                       case TYPE_ULONGINT:
686                         {
687                           unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
688                           SNPRINTF_BUF (arg);
689                         }
690                         break;
691 #ifdef HAVE_LONG_LONG
692                       case TYPE_LONGLONGINT:
693                         {
694                           long long int arg = a.arg[dp->arg_index].a.a_longlongint;
695                           SNPRINTF_BUF (arg);
696                         }
697                         break;
698                       case TYPE_ULONGLONGINT:
699                         {
700                           unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
701                           SNPRINTF_BUF (arg);
702                         }
703                         break;
704 #endif
705                       case TYPE_DOUBLE:
706                         {
707                           double arg = a.arg[dp->arg_index].a.a_double;
708                           SNPRINTF_BUF (arg);
709                         }
710                         break;
711 #ifdef HAVE_LONG_DOUBLE
712                       case TYPE_LONGDOUBLE:
713                         {
714                           long double arg = a.arg[dp->arg_index].a.a_longdouble;
715                           SNPRINTF_BUF (arg);
716                         }
717                         break;
718 #endif
719                       case TYPE_CHAR:
720                         {
721                           int arg = a.arg[dp->arg_index].a.a_char;
722                           SNPRINTF_BUF (arg);
723                         }
724                         break;
725 #ifdef HAVE_WINT_T
726                       case TYPE_WIDE_CHAR:
727                         {
728                           wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
729                           SNPRINTF_BUF (arg);
730                         }
731                         break;
732 #endif
733                       case TYPE_STRING:
734                         {
735                           const char *arg = a.arg[dp->arg_index].a.a_string;
736                           SNPRINTF_BUF (arg);
737                         }
738                         break;
739 #ifdef HAVE_WCHAR_T
740                       case TYPE_WIDE_STRING:
741                         {
742                           const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
743                           SNPRINTF_BUF (arg);
744                         }
745                         break;
746 #endif
747                       case TYPE_POINTER:
748                         {
749                           void *arg = a.arg[dp->arg_index].a.a_pointer;
750                           SNPRINTF_BUF (arg);
751                         }
752                         break;
753                       default:
754                         abort ();
755                       }
756
757 #if USE_SNPRINTF
758                     /* Portability: Not all implementations of snprintf()
759                        are ISO C 99 compliant.  Determine the number of
760                        bytes that snprintf() has produced or would have
761                        produced.  */
762                     if (count >= 0)
763                       {
764                         /* Verify that snprintf() has NUL-terminated its
765                            result.  */
766                         if (count < maxlen && result[length + count] != '\0')
767                           abort ();
768                         /* Portability hack.  */
769                         if (retcount > count)
770                           count = retcount;
771                       }
772                     else
773                       {
774                         /* snprintf() doesn't understand the '%n'
775                            directive.  */
776                         if (p[1] != '\0')
777                           {
778                             /* Don't use the '%n' directive; instead, look
779                                at the snprintf() return value.  */
780                             p[1] = '\0';
781                             continue;
782                           }
783                         else
784                           {
785                             /* Look at the snprintf() return value.  */
786                             if (retcount < 0)
787                               {
788                                 /* HP-UX 10.20 snprintf() is doubly deficient:
789                                    It doesn't understand the '%n' directive,
790                                    *and* it returns -1 (rather than the length
791                                    that would have been required) when the
792                                    buffer is too small.  */
793                                 size_t bigger_need =
794                                   xsum (xtimes (allocated, 2), 12);
795                                 ENSURE_ALLOCATION (bigger_need);
796                                 continue;
797                               }
798                             else
799                               count = retcount;
800                           }
801                       }
802 #endif
803
804                     /* Attempt to handle failure.  */
805                     if (count < 0)
806                       {
807                         if (!(result == resultbuf || result == NULL))
808                           free (result);
809                         if (buf_malloced != NULL)
810                           free (buf_malloced);
811                         CLEANUP ();
812                         errno = EINVAL;
813                         return NULL;
814                       }
815
816 #if !USE_SNPRINTF
817                     if (count >= tmp_length)
818                       /* tmp_length was incorrectly calculated - fix the
819                          code above!  */
820                       abort ();
821 #endif
822
823                     /* Make room for the result.  */
824                     if (count >= maxlen)
825                       {
826                         /* Need at least count bytes.  But allocate
827                            proportionally, to avoid looping eternally if
828                            snprintf() reports a too small count.  */
829                         size_t n =
830                           xmax (xsum (length, count), xtimes (allocated, 2));
831
832                         ENSURE_ALLOCATION (n);
833 #if USE_SNPRINTF
834                         continue;
835 #endif
836                       }
837
838 #if USE_SNPRINTF
839                     /* The snprintf() result did fit.  */
840 #else
841                     /* Append the sprintf() result.  */
842                     memcpy (result + length, tmp, count * sizeof (CHAR_T));
843                     if (tmp != tmpbuf)
844                       free (tmp);
845 #endif
846
847                     length += count;
848                     break;
849                   }
850               }
851           }
852       }
853
854     /* Add the final NUL.  */
855     ENSURE_ALLOCATION (xsum (length, 1));
856     result[length] = '\0';
857
858     if (result != resultbuf && length + 1 < allocated)
859       {
860         /* Shrink the allocated memory if possible.  */
861         CHAR_T *memory;
862
863         memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
864         if (memory != NULL)
865           result = memory;
866       }
867
868     if (buf_malloced != NULL)
869       free (buf_malloced);
870     CLEANUP ();
871     *lengthp = length;
872     if (length > INT_MAX)
873       goto length_overflow;
874     return result;
875
876   length_overflow:
877     /* We could produce such a big string, but its length doesn't fit into
878        an 'int'.  POSIX says that snprintf() fails with errno = EOVERFLOW in
879        this case.  */
880     if (result != resultbuf)
881       free (result);
882     errno = EOVERFLOW;
883     return NULL;
884
885   out_of_memory:
886     if (!(result == resultbuf || result == NULL))
887       free (result);
888     if (buf_malloced != NULL)
889       free (buf_malloced);
890   out_of_memory_1:
891     CLEANUP ();
892     errno = ENOMEM;
893     return NULL;
894   }
895 }
896
897 #undef SNPRINTF
898 #undef USE_SNPRINTF
899 #undef PRINTF_PARSE
900 #undef DIRECTIVES
901 #undef DIRECTIVE
902 #undef CHAR_T
903 #undef VASNPRINTF