e4270abe836a97934e06d21dadf6854845a003c0
[platform/upstream/curl.git] / lib / mprintf.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1999 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  *
22  * Purpose:
23  *  A merge of Bjorn Reese's format() function and Daniel's dsprintf()
24  *  1.0. A full blooded printf() clone with full support for <num>$
25  *  everywhere (parameters, widths and precisions) including variabled
26  *  sized parameters (like doubles, long longs, long doubles and even
27  *  void * in 64-bit architectures).
28  *
29  * Current restrictions:
30  * - Max 128 parameters
31  * - No 'long double' support.
32  *
33  * If you ever want truly portable and good *printf() clones, the project that
34  * took on from here is named 'Trio' and you find more details on the trio web
35  * page at https://daniel.haxx.se/projects/trio/
36  */
37
38 #include "curl_setup.h"
39 #include <curl/mprintf.h>
40
41 #include "curl_memory.h"
42 /* The last #include file should be: */
43 #include "memdebug.h"
44
45 #ifndef SIZEOF_LONG_DOUBLE
46 #define SIZEOF_LONG_DOUBLE 0
47 #endif
48
49 /*
50  * If SIZEOF_SIZE_T has not been defined, default to the size of long.
51  */
52
53 #ifndef SIZEOF_SIZE_T
54 #  define SIZEOF_SIZE_T CURL_SIZEOF_LONG
55 #endif
56
57 #ifdef HAVE_LONGLONG
58 #  define LONG_LONG_TYPE long long
59 #  define HAVE_LONG_LONG_TYPE
60 #else
61 #  if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
62 #    define LONG_LONG_TYPE __int64
63 #    define HAVE_LONG_LONG_TYPE
64 #  else
65 #    undef LONG_LONG_TYPE
66 #    undef HAVE_LONG_LONG_TYPE
67 #  endif
68 #endif
69
70 /*
71  * Non-ANSI integer extensions
72  */
73
74 #if (defined(__BORLANDC__) && (__BORLANDC__ >= 0x520)) || \
75     (defined(__WATCOMC__) && defined(__386__)) || \
76     (defined(__POCC__) && defined(_MSC_VER)) || \
77     (defined(_WIN32_WCE)) || \
78     (defined(__MINGW32__)) || \
79     (defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64))
80 #  define MP_HAVE_INT_EXTENSIONS
81 #endif
82
83 /*
84  * Max integer data types that mprintf.c is capable
85  */
86
87 #ifdef HAVE_LONG_LONG_TYPE
88 #  define mp_intmax_t LONG_LONG_TYPE
89 #  define mp_uintmax_t unsigned LONG_LONG_TYPE
90 #else
91 #  define mp_intmax_t long
92 #  define mp_uintmax_t unsigned long
93 #endif
94
95 #define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should
96                         fit negative DBL_MAX (317 letters) */
97 #define MAX_PARAMETERS 128 /* lame static limit */
98
99 #ifdef __AMIGA__
100 # undef FORMAT_INT
101 #endif
102
103 /* Lower-case digits.  */
104 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
105
106 /* Upper-case digits.  */
107 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
108
109 #define OUTCHAR(x) \
110   do{ \
111     if(stream((unsigned char)(x), (FILE *)data) != -1) \
112       done++; \
113     else \
114      return done; /* return immediately on failure */ \
115   } WHILE_FALSE
116
117 /* Data type to read from the arglist */
118 typedef enum  {
119   FORMAT_UNKNOWN = 0,
120   FORMAT_STRING,
121   FORMAT_PTR,
122   FORMAT_INT,
123   FORMAT_INTPTR,
124   FORMAT_LONG,
125   FORMAT_LONGLONG,
126   FORMAT_DOUBLE,
127   FORMAT_LONGDOUBLE,
128   FORMAT_WIDTH /* For internal use */
129 } FormatType;
130
131 /* conversion and display flags */
132 enum {
133   FLAGS_NEW        = 0,
134   FLAGS_SPACE      = 1<<0,
135   FLAGS_SHOWSIGN   = 1<<1,
136   FLAGS_LEFT       = 1<<2,
137   FLAGS_ALT        = 1<<3,
138   FLAGS_SHORT      = 1<<4,
139   FLAGS_LONG       = 1<<5,
140   FLAGS_LONGLONG   = 1<<6,
141   FLAGS_LONGDOUBLE = 1<<7,
142   FLAGS_PAD_NIL    = 1<<8,
143   FLAGS_UNSIGNED   = 1<<9,
144   FLAGS_OCTAL      = 1<<10,
145   FLAGS_HEX        = 1<<11,
146   FLAGS_UPPER      = 1<<12,
147   FLAGS_WIDTH      = 1<<13, /* '*' or '*<num>$' used */
148   FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
149   FLAGS_PREC       = 1<<15, /* precision was specified */
150   FLAGS_PRECPARAM  = 1<<16, /* precision PARAMETER was specified */
151   FLAGS_CHAR       = 1<<17, /* %c story */
152   FLAGS_FLOATE     = 1<<18, /* %e or %E */
153   FLAGS_FLOATG     = 1<<19  /* %g or %G */
154 };
155
156 typedef struct {
157   FormatType type;
158   int flags;
159   long width;     /* width OR width parameter number */
160   long precision; /* precision OR precision parameter number */
161   union {
162     char *str;
163     void *ptr;
164     union {
165       mp_intmax_t as_signed;
166       mp_uintmax_t as_unsigned;
167     } num;
168     double dnum;
169   } data;
170 } va_stack_t;
171
172 struct nsprintf {
173   char *buffer;
174   size_t length;
175   size_t max;
176 };
177
178 struct asprintf {
179   char *buffer; /* allocated buffer */
180   size_t len;   /* length of string */
181   size_t alloc; /* length of alloc */
182   int fail;     /* (!= 0) if an alloc has failed and thus
183                    the output is not the complete data */
184 };
185
186 static long dprintf_DollarString(char *input, char **end)
187 {
188   int number=0;
189   while(ISDIGIT(*input)) {
190     number *= 10;
191     number += *input-'0';
192     input++;
193   }
194   if(number && ('$'==*input++)) {
195     *end = input;
196     return number;
197   }
198   return 0;
199 }
200
201 static bool dprintf_IsQualifierNoDollar(const char *fmt)
202 {
203 #if defined(MP_HAVE_INT_EXTENSIONS)
204   if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
205     return TRUE;
206   }
207 #endif
208
209   switch(*fmt) {
210   case '-': case '+': case ' ': case '#': case '.':
211   case '0': case '1': case '2': case '3': case '4':
212   case '5': case '6': case '7': case '8': case '9':
213   case 'h': case 'l': case 'L': case 'z': case 'q':
214   case '*': case 'O':
215 #if defined(MP_HAVE_INT_EXTENSIONS)
216   case 'I':
217 #endif
218     return TRUE;
219
220   default:
221     return FALSE;
222   }
223 }
224
225 /******************************************************************
226  *
227  * Pass 1:
228  * Create an index with the type of each parameter entry and its
229  * value (may vary in size)
230  *
231  * Returns zero on success.
232  *
233  ******************************************************************/
234
235 static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
236                          va_list arglist)
237 {
238   char *fmt = (char *)format;
239   int param_num = 0;
240   long this_param;
241   long width;
242   long precision;
243   int flags;
244   long max_param=0;
245   long i;
246
247   while(*fmt) {
248     if(*fmt++ == '%') {
249       if(*fmt == '%') {
250         fmt++;
251         continue; /* while */
252       }
253
254       flags = FLAGS_NEW;
255
256       /* Handle the positional case (N$) */
257
258       param_num++;
259
260       this_param = dprintf_DollarString(fmt, &fmt);
261       if(0 == this_param)
262         /* we got no positional, get the next counter */
263         this_param = param_num;
264
265       if(this_param > max_param)
266         max_param = this_param;
267
268       /*
269        * The parameter with number 'i' should be used. Next, we need
270        * to get SIZE and TYPE of the parameter. Add the information
271        * to our array.
272        */
273
274       width = 0;
275       precision = 0;
276
277       /* Handle the flags */
278
279       while(dprintf_IsQualifierNoDollar(fmt)) {
280 #if defined(MP_HAVE_INT_EXTENSIONS)
281         if(!strncmp(fmt, "I32", 3)) {
282           flags |= FLAGS_LONG;
283           fmt += 3;
284         }
285         else if(!strncmp(fmt, "I64", 3)) {
286           flags |= FLAGS_LONGLONG;
287           fmt += 3;
288         }
289         else
290 #endif
291
292         switch(*fmt++) {
293         case ' ':
294           flags |= FLAGS_SPACE;
295           break;
296         case '+':
297           flags |= FLAGS_SHOWSIGN;
298           break;
299         case '-':
300           flags |= FLAGS_LEFT;
301           flags &= ~FLAGS_PAD_NIL;
302           break;
303         case '#':
304           flags |= FLAGS_ALT;
305           break;
306         case '.':
307           if('*' == *fmt) {
308             /* The precision is picked from a specified parameter */
309
310             flags |= FLAGS_PRECPARAM;
311             fmt++;
312             param_num++;
313
314             i = dprintf_DollarString(fmt, &fmt);
315             if(i)
316               precision = i;
317             else
318               precision = param_num;
319
320             if(precision > max_param)
321               max_param = precision;
322           }
323           else {
324             flags |= FLAGS_PREC;
325             precision = strtol(fmt, &fmt, 10);
326           }
327           break;
328         case 'h':
329           flags |= FLAGS_SHORT;
330           break;
331 #if defined(MP_HAVE_INT_EXTENSIONS)
332         case 'I':
333 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
334           flags |= FLAGS_LONGLONG;
335 #else
336           flags |= FLAGS_LONG;
337 #endif
338           break;
339 #endif
340         case 'l':
341           if(flags & FLAGS_LONG)
342             flags |= FLAGS_LONGLONG;
343           else
344             flags |= FLAGS_LONG;
345           break;
346         case 'L':
347           flags |= FLAGS_LONGDOUBLE;
348           break;
349         case 'q':
350           flags |= FLAGS_LONGLONG;
351           break;
352         case 'z':
353           /* the code below generates a warning if -Wunreachable-code is
354              used */
355 #if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
356           flags |= FLAGS_LONGLONG;
357 #else
358           flags |= FLAGS_LONG;
359 #endif
360           break;
361         case 'O':
362 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
363           flags |= FLAGS_LONGLONG;
364 #else
365           flags |= FLAGS_LONG;
366 #endif
367           break;
368         case '0':
369           if(!(flags & FLAGS_LEFT))
370             flags |= FLAGS_PAD_NIL;
371           /* FALLTHROUGH */
372         case '1': case '2': case '3': case '4':
373         case '5': case '6': case '7': case '8': case '9':
374           flags |= FLAGS_WIDTH;
375           width = strtol(fmt-1, &fmt, 10);
376           break;
377         case '*':  /* Special case */
378           flags |= FLAGS_WIDTHPARAM;
379           param_num++;
380
381           i = dprintf_DollarString(fmt, &fmt);
382           if(i)
383             width = i;
384           else
385             width = param_num;
386           if(width > max_param)
387             max_param=width;
388           break;
389         default:
390           break;
391         }
392       } /* switch */
393
394       /* Handle the specifier */
395
396       i = this_param - 1;
397
398       if((i < 0) || (i >= MAX_PARAMETERS))
399         /* out of allowed range */
400         return 1;
401
402       switch (*fmt) {
403       case 'S':
404         flags |= FLAGS_ALT;
405         /* FALLTHROUGH */
406       case 's':
407         vto[i].type = FORMAT_STRING;
408         break;
409       case 'n':
410         vto[i].type = FORMAT_INTPTR;
411         break;
412       case 'p':
413         vto[i].type = FORMAT_PTR;
414         break;
415       case 'd': case 'i':
416         vto[i].type = FORMAT_INT;
417         break;
418       case 'u':
419         vto[i].type = FORMAT_INT;
420         flags |= FLAGS_UNSIGNED;
421         break;
422       case 'o':
423         vto[i].type = FORMAT_INT;
424         flags |= FLAGS_OCTAL;
425         break;
426       case 'x':
427         vto[i].type = FORMAT_INT;
428         flags |= FLAGS_HEX|FLAGS_UNSIGNED;
429         break;
430       case 'X':
431         vto[i].type = FORMAT_INT;
432         flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
433         break;
434       case 'c':
435         vto[i].type = FORMAT_INT;
436         flags |= FLAGS_CHAR;
437         break;
438       case 'f':
439         vto[i].type = FORMAT_DOUBLE;
440         break;
441       case 'e':
442         vto[i].type = FORMAT_DOUBLE;
443         flags |= FLAGS_FLOATE;
444         break;
445       case 'E':
446         vto[i].type = FORMAT_DOUBLE;
447         flags |= FLAGS_FLOATE|FLAGS_UPPER;
448         break;
449       case 'g':
450         vto[i].type = FORMAT_DOUBLE;
451         flags |= FLAGS_FLOATG;
452         break;
453       case 'G':
454         vto[i].type = FORMAT_DOUBLE;
455         flags |= FLAGS_FLOATG|FLAGS_UPPER;
456         break;
457       default:
458         vto[i].type = FORMAT_UNKNOWN;
459         break;
460       } /* switch */
461
462       vto[i].flags = flags;
463       vto[i].width = width;
464       vto[i].precision = precision;
465
466       if(flags & FLAGS_WIDTHPARAM) {
467         /* we have the width specified from a parameter, so we make that
468            parameter's info setup properly */
469         long k = width - 1;
470         vto[i].width = k;
471         vto[k].type = FORMAT_WIDTH;
472         vto[k].flags = FLAGS_NEW;
473         /* can't use width or precision of width! */
474         vto[k].width = 0;
475         vto[k].precision = 0;
476       }
477       if(flags & FLAGS_PRECPARAM) {
478         /* we have the precision specified from a parameter, so we make that
479            parameter's info setup properly */
480         long k = precision - 1;
481         vto[i].precision = k;
482         vto[k].type = FORMAT_WIDTH;
483         vto[k].flags = FLAGS_NEW;
484         /* can't use width or precision of width! */
485         vto[k].width = 0;
486         vto[k].precision = 0;
487       }
488       *endpos++ = fmt + 1; /* end of this sequence */
489     }
490   }
491
492   /* Read the arg list parameters into our data list */
493   for(i=0; i<max_param; i++) {
494     /* Width/precision arguments must be read before the main argument
495        they are attached to */
496     if(vto[i].flags & FLAGS_WIDTHPARAM) {
497       vto[vto[i].width].data.num.as_signed =
498         (mp_intmax_t)va_arg(arglist, int);
499     }
500     if(vto[i].flags & FLAGS_PRECPARAM) {
501       vto[vto[i].precision].data.num.as_signed =
502         (mp_intmax_t)va_arg(arglist, int);
503     }
504
505     switch(vto[i].type) {
506     case FORMAT_STRING:
507       vto[i].data.str = va_arg(arglist, char *);
508       break;
509
510     case FORMAT_INTPTR:
511     case FORMAT_UNKNOWN:
512     case FORMAT_PTR:
513       vto[i].data.ptr = va_arg(arglist, void *);
514       break;
515
516     case FORMAT_INT:
517 #ifdef HAVE_LONG_LONG_TYPE
518       if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
519         vto[i].data.num.as_unsigned =
520           (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
521       else if(vto[i].flags & FLAGS_LONGLONG)
522         vto[i].data.num.as_signed =
523           (mp_intmax_t)va_arg(arglist, mp_intmax_t);
524       else
525 #endif
526       {
527         if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
528           vto[i].data.num.as_unsigned =
529             (mp_uintmax_t)va_arg(arglist, unsigned long);
530         else if(vto[i].flags & FLAGS_LONG)
531           vto[i].data.num.as_signed =
532             (mp_intmax_t)va_arg(arglist, long);
533         else if(vto[i].flags & FLAGS_UNSIGNED)
534           vto[i].data.num.as_unsigned =
535             (mp_uintmax_t)va_arg(arglist, unsigned int);
536         else
537           vto[i].data.num.as_signed =
538             (mp_intmax_t)va_arg(arglist, int);
539       }
540       break;
541
542     case FORMAT_DOUBLE:
543       vto[i].data.dnum = va_arg(arglist, double);
544       break;
545
546     case FORMAT_WIDTH:
547       /* Argument has been read. Silently convert it into an integer
548        * for later use
549        */
550       vto[i].type = FORMAT_INT;
551       break;
552
553     default:
554       break;
555     }
556   }
557
558   return 0;
559
560 }
561
562 static int dprintf_formatf(
563   void *data, /* untouched by format(), just sent to the stream() function in
564                  the second argument */
565   /* function pointer called for each output character */
566   int (*stream)(int, FILE *),
567   const char *format,    /* %-formatted string */
568   va_list ap_save) /* list of parameters */
569 {
570   /* Base-36 digits for numbers.  */
571   const char *digits = lower_digits;
572
573   /* Pointer into the format string.  */
574   char *f;
575
576   /* Number of characters written.  */
577   int done = 0;
578
579   long param; /* current parameter to read */
580   long param_num=0; /* parameter counter */
581
582   va_stack_t vto[MAX_PARAMETERS];
583   char *endpos[MAX_PARAMETERS];
584   char **end;
585
586   char work[BUFFSIZE];
587
588   va_stack_t *p;
589
590   /* 'workend' points to the final buffer byte position, but with an extra
591      byte as margin to avoid the (false?) warning Coverity gives us
592      otherwise */
593   char *workend = &work[sizeof(work) - 2];
594
595   /* Do the actual %-code parsing */
596   if(dprintf_Pass1(format, vto, endpos, ap_save))
597     return -1;
598
599   end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
600                        created for us */
601
602   f = (char *)format;
603   while(*f != '\0') {
604     /* Format spec modifiers.  */
605     int is_alt;
606
607     /* Width of a field.  */
608     long width;
609
610     /* Precision of a field.  */
611     long prec;
612
613     /* Decimal integer is negative.  */
614     int is_neg;
615
616     /* Base of a number to be written.  */
617     long base;
618
619     /* Integral values to be written.  */
620     mp_uintmax_t num;
621
622     /* Used to convert negative in positive.  */
623     mp_intmax_t signed_num;
624
625     char *w;
626
627     if(*f != '%') {
628       /* This isn't a format spec, so write everything out until the next one
629          OR end of string is reached.  */
630       do {
631         OUTCHAR(*f);
632       } while(*++f && ('%' != *f));
633       continue;
634     }
635
636     ++f;
637
638     /* Check for "%%".  Note that although the ANSI standard lists
639        '%' as a conversion specifier, it says "The complete format
640        specification shall be `%%'," so we can avoid all the width
641        and precision processing.  */
642     if(*f == '%') {
643       ++f;
644       OUTCHAR('%');
645       continue;
646     }
647
648     /* If this is a positional parameter, the position must follow immediately
649        after the %, thus create a %<num>$ sequence */
650     param=dprintf_DollarString(f, &f);
651
652     if(!param)
653       param = param_num;
654     else
655       --param;
656
657     param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
658                     third %s will pick the 3rd argument */
659
660     p = &vto[param];
661
662     /* pick up the specified width */
663     if(p->flags & FLAGS_WIDTHPARAM) {
664       width = (long)vto[p->width].data.num.as_signed;
665       param_num++; /* since the width is extracted from a parameter, we
666                       must skip that to get to the next one properly */
667       if(width < 0) {
668         /* "A negative field width is taken as a '-' flag followed by a
669            positive field width." */
670         width = -width;
671         p->flags |= FLAGS_LEFT;
672         p->flags &= ~FLAGS_PAD_NIL;
673       }
674     }
675     else
676       width = p->width;
677
678     /* pick up the specified precision */
679     if(p->flags & FLAGS_PRECPARAM) {
680       prec = (long)vto[p->precision].data.num.as_signed;
681       param_num++; /* since the precision is extracted from a parameter, we
682                       must skip that to get to the next one properly */
683       if(prec < 0)
684         /* "A negative precision is taken as if the precision were
685            omitted." */
686         prec = -1;
687     }
688     else if(p->flags & FLAGS_PREC)
689       prec = p->precision;
690     else
691       prec = -1;
692
693     is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
694
695     switch(p->type) {
696     case FORMAT_INT:
697       num = p->data.num.as_unsigned;
698       if(p->flags & FLAGS_CHAR) {
699         /* Character.  */
700         if(!(p->flags & FLAGS_LEFT))
701           while(--width > 0)
702             OUTCHAR(' ');
703         OUTCHAR((char) num);
704         if(p->flags & FLAGS_LEFT)
705           while(--width > 0)
706             OUTCHAR(' ');
707         break;
708       }
709       if(p->flags & FLAGS_OCTAL) {
710         /* Octal unsigned integer.  */
711         base = 8;
712         goto unsigned_number;
713       }
714       else if(p->flags & FLAGS_HEX) {
715         /* Hexadecimal unsigned integer.  */
716
717         digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
718         base = 16;
719         goto unsigned_number;
720       }
721       else if(p->flags & FLAGS_UNSIGNED) {
722         /* Decimal unsigned integer.  */
723         base = 10;
724         goto unsigned_number;
725       }
726
727       /* Decimal integer.  */
728       base = 10;
729
730       is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
731       if(is_neg) {
732         /* signed_num might fail to hold absolute negative minimum by 1 */
733         signed_num = p->data.num.as_signed + (mp_intmax_t)1;
734         signed_num = -signed_num;
735         num = (mp_uintmax_t)signed_num;
736         num += (mp_uintmax_t)1;
737       }
738
739       goto number;
740
741       unsigned_number:
742       /* Unsigned number of base BASE.  */
743       is_neg = 0;
744
745       number:
746       /* Number of base BASE.  */
747
748       /* Supply a default precision if none was given.  */
749       if(prec == -1)
750         prec = 1;
751
752       /* Put the number in WORK.  */
753       w = workend;
754       while(num > 0) {
755         *w-- = digits[num % base];
756         num /= base;
757       }
758       width -= (long)(workend - w);
759       prec -= (long)(workend - w);
760
761       if(is_alt && base == 8 && prec <= 0) {
762         *w-- = '0';
763         --width;
764       }
765
766       if(prec > 0) {
767         width -= prec;
768         while(prec-- > 0)
769           *w-- = '0';
770       }
771
772       if(is_alt && base == 16)
773         width -= 2;
774
775       if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
776         --width;
777
778       if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
779         while(width-- > 0)
780           OUTCHAR(' ');
781
782       if(is_neg)
783         OUTCHAR('-');
784       else if(p->flags & FLAGS_SHOWSIGN)
785         OUTCHAR('+');
786       else if(p->flags & FLAGS_SPACE)
787         OUTCHAR(' ');
788
789       if(is_alt && base == 16) {
790         OUTCHAR('0');
791         if(p->flags & FLAGS_UPPER)
792           OUTCHAR('X');
793         else
794           OUTCHAR('x');
795       }
796
797       if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
798         while(width-- > 0)
799           OUTCHAR('0');
800
801       /* Write the number.  */
802       while(++w <= workend) {
803         OUTCHAR(*w);
804       }
805
806       if(p->flags & FLAGS_LEFT)
807         while(width-- > 0)
808           OUTCHAR(' ');
809       break;
810
811     case FORMAT_STRING:
812             /* String.  */
813       {
814         static const char null[] = "(nil)";
815         const char *str;
816         size_t len;
817
818         str = (char *) p->data.str;
819         if(str == NULL) {
820           /* Write null[] if there's space.  */
821           if(prec == -1 || prec >= (long) sizeof(null) - 1) {
822             str = null;
823             len = sizeof(null) - 1;
824             /* Disable quotes around (nil) */
825             p->flags &= (~FLAGS_ALT);
826           }
827           else {
828             str = "";
829             len = 0;
830           }
831         }
832         else if(prec != -1)
833           len = (size_t)prec;
834         else
835           len = strlen(str);
836
837         width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
838
839         if(p->flags & FLAGS_ALT)
840           OUTCHAR('"');
841
842         if(!(p->flags&FLAGS_LEFT))
843           while(width-- > 0)
844             OUTCHAR(' ');
845
846         while((len-- > 0) && *str)
847           OUTCHAR(*str++);
848         if(p->flags&FLAGS_LEFT)
849           while(width-- > 0)
850             OUTCHAR(' ');
851
852         if(p->flags & FLAGS_ALT)
853           OUTCHAR('"');
854       }
855       break;
856
857     case FORMAT_PTR:
858       /* Generic pointer.  */
859       {
860         void *ptr;
861         ptr = (void *) p->data.ptr;
862         if(ptr != NULL) {
863           /* If the pointer is not NULL, write it as a %#x spec.  */
864           base = 16;
865           digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
866           is_alt = 1;
867           num = (size_t) ptr;
868           is_neg = 0;
869           goto number;
870         }
871         else {
872           /* Write "(nil)" for a nil pointer.  */
873           static const char strnil[] = "(nil)";
874           const char *point;
875
876           width -= (long)(sizeof(strnil) - 1);
877           if(p->flags & FLAGS_LEFT)
878             while(width-- > 0)
879               OUTCHAR(' ');
880           for(point = strnil; *point != '\0'; ++point)
881             OUTCHAR(*point);
882           if(! (p->flags & FLAGS_LEFT))
883             while(width-- > 0)
884               OUTCHAR(' ');
885         }
886       }
887       break;
888
889     case FORMAT_DOUBLE:
890       {
891         char formatbuf[32]="%";
892         char *fptr = &formatbuf[1];
893         size_t left = sizeof(formatbuf)-strlen(formatbuf);
894         int len;
895
896         width = -1;
897         if(p->flags & FLAGS_WIDTH)
898           width = p->width;
899         else if(p->flags & FLAGS_WIDTHPARAM)
900           width = (long)vto[p->width].data.num.as_signed;
901
902         prec = -1;
903         if(p->flags & FLAGS_PREC)
904           prec = p->precision;
905         else if(p->flags & FLAGS_PRECPARAM)
906           prec = (long)vto[p->precision].data.num.as_signed;
907
908         if(p->flags & FLAGS_LEFT)
909           *fptr++ = '-';
910         if(p->flags & FLAGS_SHOWSIGN)
911           *fptr++ = '+';
912         if(p->flags & FLAGS_SPACE)
913           *fptr++ = ' ';
914         if(p->flags & FLAGS_ALT)
915           *fptr++ = '#';
916
917         *fptr = 0;
918
919         if(width >= 0) {
920           if(width >= (long)sizeof(work))
921             width = sizeof(work)-1;
922           /* RECURSIVE USAGE */
923           len = curl_msnprintf(fptr, left, "%ld", width);
924           fptr += len;
925           left -= len;
926         }
927         if(prec >= 0) {
928           /* for each digit in the integer part, we can have one less
929              precision */
930           size_t maxprec = sizeof(work) - 2;
931           double val = p->data.dnum;
932           while(val >= 10.0) {
933             val /= 10;
934             maxprec--;
935           }
936
937           if(prec > (long)maxprec)
938             prec = (long)maxprec-1;
939           /* RECURSIVE USAGE */
940           len = curl_msnprintf(fptr, left, ".%ld", prec);
941           fptr += len;
942         }
943         if(p->flags & FLAGS_LONG)
944           *fptr++ = 'l';
945
946         if(p->flags & FLAGS_FLOATE)
947           *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
948         else if(p->flags & FLAGS_FLOATG)
949           *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
950         else
951           *fptr++ = 'f';
952
953         *fptr = 0; /* and a final zero termination */
954
955         /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
956            output characters */
957         (sprintf)(work, formatbuf, p->data.dnum);
958 #ifdef CURLDEBUG
959         assert(strlen(work) <= sizeof(work));
960 #endif
961         for(fptr=work; *fptr; fptr++)
962           OUTCHAR(*fptr);
963       }
964       break;
965
966     case FORMAT_INTPTR:
967       /* Answer the count of characters written.  */
968 #ifdef HAVE_LONG_LONG_TYPE
969       if(p->flags & FLAGS_LONGLONG)
970         *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
971       else
972 #endif
973         if(p->flags & FLAGS_LONG)
974           *(long *) p->data.ptr = (long)done;
975       else if(!(p->flags & FLAGS_SHORT))
976         *(int *) p->data.ptr = (int)done;
977       else
978         *(short *) p->data.ptr = (short)done;
979       break;
980
981     default:
982       break;
983     }
984     f = *end++; /* goto end of %-code */
985
986   }
987   return done;
988 }
989
990 /* fputc() look-alike */
991 static int addbyter(int output, FILE *data)
992 {
993   struct nsprintf *infop=(struct nsprintf *)data;
994   unsigned char outc = (unsigned char)output;
995
996   if(infop->length < infop->max) {
997     /* only do this if we haven't reached max length yet */
998     infop->buffer[0] = outc; /* store */
999     infop->buffer++; /* increase pointer */
1000     infop->length++; /* we are now one byte larger */
1001     return outc;     /* fputc() returns like this on success */
1002   }
1003   return -1;
1004 }
1005
1006 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
1007                     va_list ap_save)
1008 {
1009   int retcode;
1010   struct nsprintf info;
1011
1012   info.buffer = buffer;
1013   info.length = 0;
1014   info.max = maxlength;
1015
1016   retcode = dprintf_formatf(&info, addbyter, format, ap_save);
1017   if((retcode != -1) && info.max) {
1018     /* we terminate this with a zero byte */
1019     if(info.max == info.length)
1020       /* we're at maximum, scrap the last letter */
1021       info.buffer[-1] = 0;
1022     else
1023       info.buffer[0] = 0;
1024   }
1025   return retcode;
1026 }
1027
1028 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1029 {
1030   int retcode;
1031   va_list ap_save; /* argument pointer */
1032   va_start(ap_save, format);
1033   retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1034   va_end(ap_save);
1035   return retcode;
1036 }
1037
1038 /* fputc() look-alike */
1039 static int alloc_addbyter(int output, FILE *data)
1040 {
1041   struct asprintf *infop=(struct asprintf *)data;
1042   unsigned char outc = (unsigned char)output;
1043
1044   if(!infop->buffer) {
1045     infop->buffer = malloc(32);
1046     if(!infop->buffer) {
1047       infop->fail = 1;
1048       return -1; /* fail */
1049     }
1050     infop->alloc = 32;
1051     infop->len =0;
1052   }
1053   else if(infop->len+1 >= infop->alloc) {
1054     char *newptr = NULL;
1055     size_t newsize = infop->alloc*2;
1056
1057     /* detect wrap-around or other overflow problems */
1058     if(newsize > infop->alloc)
1059       newptr = realloc(infop->buffer, newsize);
1060
1061     if(!newptr) {
1062       infop->fail = 1;
1063       return -1; /* fail */
1064     }
1065     infop->buffer = newptr;
1066     infop->alloc = newsize;
1067   }
1068
1069   infop->buffer[ infop->len ] = outc;
1070
1071   infop->len++;
1072
1073   return outc; /* fputc() returns like this on success */
1074 }
1075
1076 char *curl_maprintf(const char *format, ...)
1077 {
1078   va_list ap_save; /* argument pointer */
1079   int retcode;
1080   struct asprintf info;
1081
1082   info.buffer = NULL;
1083   info.len = 0;
1084   info.alloc = 0;
1085   info.fail = 0;
1086
1087   va_start(ap_save, format);
1088   retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1089   va_end(ap_save);
1090   if((-1 == retcode) || info.fail) {
1091     if(info.alloc)
1092       free(info.buffer);
1093     return NULL;
1094   }
1095   if(info.alloc) {
1096     info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1097     return info.buffer;
1098   }
1099   else
1100     return strdup("");
1101 }
1102
1103 char *curl_mvaprintf(const char *format, va_list ap_save)
1104 {
1105   int retcode;
1106   struct asprintf info;
1107
1108   info.buffer = NULL;
1109   info.len = 0;
1110   info.alloc = 0;
1111   info.fail = 0;
1112
1113   retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1114   if((-1 == retcode) || info.fail) {
1115     if(info.alloc)
1116       free(info.buffer);
1117     return NULL;
1118   }
1119
1120   if(info.alloc) {
1121     info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1122     return info.buffer;
1123   }
1124   else
1125     return strdup("");
1126 }
1127
1128 static int storebuffer(int output, FILE *data)
1129 {
1130   char **buffer = (char **)data;
1131   unsigned char outc = (unsigned char)output;
1132   **buffer = outc;
1133   (*buffer)++;
1134   return outc; /* act like fputc() ! */
1135 }
1136
1137 int curl_msprintf(char *buffer, const char *format, ...)
1138 {
1139   va_list ap_save; /* argument pointer */
1140   int retcode;
1141   va_start(ap_save, format);
1142   retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1143   va_end(ap_save);
1144   *buffer=0; /* we terminate this with a zero byte */
1145   return retcode;
1146 }
1147
1148 int curl_mprintf(const char *format, ...)
1149 {
1150   int retcode;
1151   va_list ap_save; /* argument pointer */
1152   va_start(ap_save, format);
1153
1154   retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1155   va_end(ap_save);
1156   return retcode;
1157 }
1158
1159 int curl_mfprintf(FILE *whereto, const char *format, ...)
1160 {
1161   int retcode;
1162   va_list ap_save; /* argument pointer */
1163   va_start(ap_save, format);
1164   retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1165   va_end(ap_save);
1166   return retcode;
1167 }
1168
1169 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1170 {
1171   int retcode;
1172   retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1173   *buffer=0; /* we terminate this with a zero byte */
1174   return retcode;
1175 }
1176
1177 int curl_mvprintf(const char *format, va_list ap_save)
1178 {
1179   return dprintf_formatf(stdout, fputc, format, ap_save);
1180 }
1181
1182 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1183 {
1184   return dprintf_formatf(whereto, fputc, format, ap_save);
1185 }