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