1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1999 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
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).
29 * Current restrictions:
30 * - Max 128 parameters
31 * - No 'long double' support.
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/
38 #include "curl_setup.h"
39 #include <curl/mprintf.h>
41 #include "curl_memory.h"
42 /* The last #include file should be: */
45 #ifndef SIZEOF_LONG_DOUBLE
46 #define SIZEOF_LONG_DOUBLE 0
50 * If SIZEOF_SIZE_T has not been defined, default to the size of long.
54 # define SIZEOF_SIZE_T CURL_SIZEOF_LONG
58 # define LONG_LONG_TYPE long long
59 # define HAVE_LONG_LONG_TYPE
61 # if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
62 # define LONG_LONG_TYPE __int64
63 # define HAVE_LONG_LONG_TYPE
65 # undef LONG_LONG_TYPE
66 # undef HAVE_LONG_LONG_TYPE
71 * Non-ANSI integer extensions
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
84 * Max integer data types that mprintf.c is capable
87 #ifdef HAVE_LONG_LONG_TYPE
88 # define mp_intmax_t LONG_LONG_TYPE
89 # define mp_uintmax_t unsigned LONG_LONG_TYPE
91 # define mp_intmax_t long
92 # define mp_uintmax_t unsigned long
95 #define BUFFSIZE 256 /* buffer for long-to-str and float-to-str calcs */
96 #define MAX_PARAMETERS 128 /* lame static limit */
102 /* Lower-case digits. */
103 static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
105 /* Upper-case digits. */
106 static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
110 if(stream((unsigned char)(x), (FILE *)data) != -1) \
113 return done; /* return immediately on failure */ \
116 /* Data type to read from the arglist */
127 FORMAT_WIDTH /* For internal use */
130 /* conversion and display flags */
134 FLAGS_SHOWSIGN = 1<<1,
139 FLAGS_LONGLONG = 1<<6,
140 FLAGS_LONGDOUBLE = 1<<7,
141 FLAGS_PAD_NIL = 1<<8,
142 FLAGS_UNSIGNED = 1<<9,
146 FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
147 FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
148 FLAGS_PREC = 1<<15, /* precision was specified */
149 FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
150 FLAGS_CHAR = 1<<17, /* %c story */
151 FLAGS_FLOATE = 1<<18, /* %e or %E */
152 FLAGS_FLOATG = 1<<19 /* %g or %G */
158 long width; /* width OR width parameter number */
159 long precision; /* precision OR precision parameter number */
164 mp_intmax_t as_signed;
165 mp_uintmax_t as_unsigned;
178 char *buffer; /* allocated buffer */
179 size_t len; /* length of string */
180 size_t alloc; /* length of alloc */
181 int fail; /* (!= 0) if an alloc has failed and thus
182 the output is not the complete data */
185 static long dprintf_DollarString(char *input, char **end)
188 while(ISDIGIT(*input)) {
190 number += *input-'0';
193 if(number && ('$'==*input++)) {
200 static bool dprintf_IsQualifierNoDollar(const char *fmt)
202 #if defined(MP_HAVE_INT_EXTENSIONS)
203 if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
209 case '-': case '+': case ' ': case '#': case '.':
210 case '0': case '1': case '2': case '3': case '4':
211 case '5': case '6': case '7': case '8': case '9':
212 case 'h': case 'l': case 'L': case 'z': case 'q':
214 #if defined(MP_HAVE_INT_EXTENSIONS)
224 /******************************************************************
227 * Create an index with the type of each parameter entry and its
228 * value (may vary in size)
230 ******************************************************************/
232 static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
235 char *fmt = (char *)format;
248 continue; /* while */
253 /* Handle the positional case (N$) */
257 this_param = dprintf_DollarString(fmt, &fmt);
259 /* we got no positional, get the next counter */
260 this_param = param_num;
262 if(this_param > max_param)
263 max_param = this_param;
266 * The parameter with number 'i' should be used. Next, we need
267 * to get SIZE and TYPE of the parameter. Add the information
274 /* Handle the flags */
276 while(dprintf_IsQualifierNoDollar(fmt)) {
277 #if defined(MP_HAVE_INT_EXTENSIONS)
278 if(!strncmp(fmt, "I32", 3)) {
282 else if(!strncmp(fmt, "I64", 3)) {
283 flags |= FLAGS_LONGLONG;
291 flags |= FLAGS_SPACE;
294 flags |= FLAGS_SHOWSIGN;
298 flags &= ~FLAGS_PAD_NIL;
306 /* The precision is picked from a specified parameter */
308 flags |= FLAGS_PRECPARAM;
312 i = dprintf_DollarString(fmt, &fmt);
316 precision = param_num;
318 if(precision > max_param)
319 max_param = precision;
323 precision = strtol(fmt, &fmt, 10);
327 flags |= FLAGS_SHORT;
329 #if defined(MP_HAVE_INT_EXTENSIONS)
331 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
332 flags |= FLAGS_LONGLONG;
339 if(flags & FLAGS_LONG)
340 flags |= FLAGS_LONGLONG;
345 flags |= FLAGS_LONGDOUBLE;
348 flags |= FLAGS_LONGLONG;
351 /* the code below generates a warning if -Wunreachable-code is
353 #if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
354 flags |= FLAGS_LONGLONG;
360 #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
361 flags |= FLAGS_LONGLONG;
367 if(!(flags & FLAGS_LEFT))
368 flags |= FLAGS_PAD_NIL;
370 case '1': case '2': case '3': case '4':
371 case '5': case '6': case '7': case '8': case '9':
372 flags |= FLAGS_WIDTH;
373 width = strtol(fmt-1, &fmt, 10);
375 case '*': /* Special case */
376 flags |= FLAGS_WIDTHPARAM;
379 i = dprintf_DollarString(fmt, &fmt);
384 if(width > max_param)
392 /* Handle the specifier */
401 vto[i].type = FORMAT_STRING;
404 vto[i].type = FORMAT_INTPTR;
407 vto[i].type = FORMAT_PTR;
410 vto[i].type = FORMAT_INT;
413 vto[i].type = FORMAT_INT;
414 flags |= FLAGS_UNSIGNED;
417 vto[i].type = FORMAT_INT;
418 flags |= FLAGS_OCTAL;
421 vto[i].type = FORMAT_INT;
422 flags |= FLAGS_HEX|FLAGS_UNSIGNED;
425 vto[i].type = FORMAT_INT;
426 flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
429 vto[i].type = FORMAT_INT;
433 vto[i].type = FORMAT_DOUBLE;
436 vto[i].type = FORMAT_DOUBLE;
437 flags |= FLAGS_FLOATE;
440 vto[i].type = FORMAT_DOUBLE;
441 flags |= FLAGS_FLOATE|FLAGS_UPPER;
444 vto[i].type = FORMAT_DOUBLE;
445 flags |= FLAGS_FLOATG;
448 vto[i].type = FORMAT_DOUBLE;
449 flags |= FLAGS_FLOATG|FLAGS_UPPER;
452 vto[i].type = FORMAT_UNKNOWN;
456 vto[i].flags = flags;
457 vto[i].width = width;
458 vto[i].precision = precision;
460 if(flags & FLAGS_WIDTHPARAM) {
461 /* we have the width specified from a parameter, so we make that
462 parameter's info setup properly */
465 vto[k].type = FORMAT_WIDTH;
466 vto[k].flags = FLAGS_NEW;
467 /* can't use width or precision of width! */
469 vto[k].precision = 0;
471 if(flags & FLAGS_PRECPARAM) {
472 /* we have the precision specified from a parameter, so we make that
473 parameter's info setup properly */
474 long k = precision - 1;
475 vto[i].precision = k;
476 vto[k].type = FORMAT_WIDTH;
477 vto[k].flags = FLAGS_NEW;
478 /* can't use width or precision of width! */
480 vto[k].precision = 0;
482 *endpos++ = fmt + 1; /* end of this sequence */
486 /* Read the arg list parameters into our data list */
487 for(i=0; i<max_param; i++) {
488 /* Width/precision arguments must be read before the main argument
489 they are attached to */
490 if(vto[i].flags & FLAGS_WIDTHPARAM) {
491 vto[vto[i].width].data.num.as_signed =
492 (mp_intmax_t)va_arg(arglist, int);
494 if(vto[i].flags & FLAGS_PRECPARAM) {
495 vto[vto[i].precision].data.num.as_signed =
496 (mp_intmax_t)va_arg(arglist, int);
499 switch (vto[i].type) {
501 vto[i].data.str = va_arg(arglist, char *);
507 vto[i].data.ptr = va_arg(arglist, void *);
511 #ifdef HAVE_LONG_LONG_TYPE
512 if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
513 vto[i].data.num.as_unsigned =
514 (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
515 else if(vto[i].flags & FLAGS_LONGLONG)
516 vto[i].data.num.as_signed =
517 (mp_intmax_t)va_arg(arglist, mp_intmax_t);
521 if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
522 vto[i].data.num.as_unsigned =
523 (mp_uintmax_t)va_arg(arglist, unsigned long);
524 else if(vto[i].flags & FLAGS_LONG)
525 vto[i].data.num.as_signed =
526 (mp_intmax_t)va_arg(arglist, long);
527 else if(vto[i].flags & FLAGS_UNSIGNED)
528 vto[i].data.num.as_unsigned =
529 (mp_uintmax_t)va_arg(arglist, unsigned int);
531 vto[i].data.num.as_signed =
532 (mp_intmax_t)va_arg(arglist, int);
537 vto[i].data.dnum = va_arg(arglist, double);
541 /* Argument has been read. Silently convert it into an integer
544 vto[i].type = FORMAT_INT;
556 static int dprintf_formatf(
557 void *data, /* untouched by format(), just sent to the stream() function in
558 the second argument */
559 /* function pointer called for each output character */
560 int (*stream)(int, FILE *),
561 const char *format, /* %-formatted string */
562 va_list ap_save) /* list of parameters */
564 /* Base-36 digits for numbers. */
565 const char *digits = lower_digits;
567 /* Pointer into the format string. */
570 /* Number of characters written. */
573 long param; /* current parameter to read */
574 long param_num=0; /* parameter counter */
576 va_stack_t vto[MAX_PARAMETERS];
577 char *endpos[MAX_PARAMETERS];
584 /* 'workend' points to the final buffer byte position, but with an extra
585 byte as margin to avoid the (false?) warning Coverity gives us
587 char *workend = &work[sizeof(work) - 2];
589 /* Do the actual %-code parsing */
590 dprintf_Pass1(format, vto, endpos, ap_save);
592 end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
597 /* Format spec modifiers. */
600 /* Width of a field. */
603 /* Precision of a field. */
606 /* Decimal integer is negative. */
609 /* Base of a number to be written. */
612 /* Integral values to be written. */
615 /* Used to convert negative in positive. */
616 mp_intmax_t signed_num;
621 /* This isn't a format spec, so write everything out until the next one
622 OR end of string is reached. */
625 } while(*++f && ('%' != *f));
631 /* Check for "%%". Note that although the ANSI standard lists
632 '%' as a conversion specifier, it says "The complete format
633 specification shall be `%%'," so we can avoid all the width
634 and precision processing. */
641 /* If this is a positional parameter, the position must follow immediately
642 after the %, thus create a %<num>$ sequence */
643 param=dprintf_DollarString(f, &f);
650 param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
651 third %s will pick the 3rd argument */
655 /* pick up the specified width */
656 if(p->flags & FLAGS_WIDTHPARAM) {
657 width = (long)vto[p->width].data.num.as_signed;
658 param_num++; /* since the width is extracted from a parameter, we
659 must skip that to get to the next one properly */
661 /* "A negative field width is taken as a '-' flag followed by a
662 positive field width." */
664 p->flags |= FLAGS_LEFT;
665 p->flags &= ~FLAGS_PAD_NIL;
671 /* pick up the specified precision */
672 if(p->flags & FLAGS_PRECPARAM) {
673 prec = (long)vto[p->precision].data.num.as_signed;
674 param_num++; /* since the precision is extracted from a parameter, we
675 must skip that to get to the next one properly */
677 /* "A negative precision is taken as if the precision were
681 else if(p->flags & FLAGS_PREC)
686 is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
690 num = p->data.num.as_unsigned;
691 if(p->flags & FLAGS_CHAR) {
693 if(!(p->flags & FLAGS_LEFT))
697 if(p->flags & FLAGS_LEFT)
702 if(p->flags & FLAGS_OCTAL) {
703 /* Octal unsigned integer. */
705 goto unsigned_number;
707 else if(p->flags & FLAGS_HEX) {
708 /* Hexadecimal unsigned integer. */
710 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
712 goto unsigned_number;
714 else if(p->flags & FLAGS_UNSIGNED) {
715 /* Decimal unsigned integer. */
717 goto unsigned_number;
720 /* Decimal integer. */
723 is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
725 /* signed_num might fail to hold absolute negative minimum by 1 */
726 signed_num = p->data.num.as_signed + (mp_intmax_t)1;
727 signed_num = -signed_num;
728 num = (mp_uintmax_t)signed_num;
729 num += (mp_uintmax_t)1;
735 /* Unsigned number of base BASE. */
739 /* Number of base BASE. */
741 /* Supply a default precision if none was given. */
745 /* Put the number in WORK. */
748 *w-- = digits[num % base];
751 width -= (long)(workend - w);
752 prec -= (long)(workend - w);
754 if(is_alt && base == 8 && prec <= 0) {
765 if(is_alt && base == 16)
768 if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
771 if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
777 else if(p->flags & FLAGS_SHOWSIGN)
779 else if(p->flags & FLAGS_SPACE)
782 if(is_alt && base == 16) {
784 if(p->flags & FLAGS_UPPER)
790 if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
794 /* Write the number. */
795 while(++w <= workend) {
799 if(p->flags & FLAGS_LEFT)
807 static const char null[] = "(nil)";
811 str = (char *) p->data.str;
813 /* Write null[] if there's space. */
814 if(prec == -1 || prec >= (long) sizeof(null) - 1) {
816 len = sizeof(null) - 1;
817 /* Disable quotes around (nil) */
818 p->flags &= (~FLAGS_ALT);
830 width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
832 if(p->flags & FLAGS_ALT)
835 if(!(p->flags&FLAGS_LEFT))
839 while((len-- > 0) && *str)
841 if(p->flags&FLAGS_LEFT)
845 if(p->flags & FLAGS_ALT)
851 /* Generic pointer. */
854 ptr = (void *) p->data.ptr;
856 /* If the pointer is not NULL, write it as a %#x spec. */
858 digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
865 /* Write "(nil)" for a nil pointer. */
866 static const char strnil[] = "(nil)";
869 width -= (long)(sizeof(strnil) - 1);
870 if(p->flags & FLAGS_LEFT)
873 for(point = strnil; *point != '\0'; ++point)
875 if(! (p->flags & FLAGS_LEFT))
884 char formatbuf[32]="%";
885 char *fptr = &formatbuf[1];
886 size_t left = sizeof(formatbuf)-strlen(formatbuf);
890 if(p->flags & FLAGS_WIDTH)
892 else if(p->flags & FLAGS_WIDTHPARAM)
893 width = (long)vto[p->width].data.num.as_signed;
896 if(p->flags & FLAGS_PREC)
898 else if(p->flags & FLAGS_PRECPARAM)
899 prec = (long)vto[p->precision].data.num.as_signed;
901 if(p->flags & FLAGS_LEFT)
903 if(p->flags & FLAGS_SHOWSIGN)
905 if(p->flags & FLAGS_SPACE)
907 if(p->flags & FLAGS_ALT)
913 /* RECURSIVE USAGE */
914 len = curl_msnprintf(fptr, left, "%ld", width);
919 /* RECURSIVE USAGE */
920 len = curl_msnprintf(fptr, left, ".%ld", prec);
923 if(p->flags & FLAGS_LONG)
926 if(p->flags & FLAGS_FLOATE)
927 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
928 else if(p->flags & FLAGS_FLOATG)
929 *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
933 *fptr = 0; /* and a final zero termination */
935 /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
937 (sprintf)(work, formatbuf, p->data.dnum);
939 for(fptr=work; *fptr; fptr++)
945 /* Answer the count of characters written. */
946 #ifdef HAVE_LONG_LONG_TYPE
947 if(p->flags & FLAGS_LONGLONG)
948 *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
951 if(p->flags & FLAGS_LONG)
952 *(long *) p->data.ptr = (long)done;
953 else if(!(p->flags & FLAGS_SHORT))
954 *(int *) p->data.ptr = (int)done;
956 *(short *) p->data.ptr = (short)done;
962 f = *end++; /* goto end of %-code */
968 /* fputc() look-alike */
969 static int addbyter(int output, FILE *data)
971 struct nsprintf *infop=(struct nsprintf *)data;
972 unsigned char outc = (unsigned char)output;
974 if(infop->length < infop->max) {
975 /* only do this if we haven't reached max length yet */
976 infop->buffer[0] = outc; /* store */
977 infop->buffer++; /* increase pointer */
978 infop->length++; /* we are now one byte larger */
979 return outc; /* fputc() returns like this on success */
984 int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
988 struct nsprintf info;
990 info.buffer = buffer;
992 info.max = maxlength;
994 retcode = dprintf_formatf(&info, addbyter, format, ap_save);
996 /* we terminate this with a zero byte */
997 if(info.max == info.length)
998 /* we're at maximum, scrap the last letter */
1006 int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
1009 va_list ap_save; /* argument pointer */
1010 va_start(ap_save, format);
1011 retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
1016 /* fputc() look-alike */
1017 static int alloc_addbyter(int output, FILE *data)
1019 struct asprintf *infop=(struct asprintf *)data;
1020 unsigned char outc = (unsigned char)output;
1022 if(!infop->buffer) {
1023 infop->buffer = malloc(32);
1024 if(!infop->buffer) {
1026 return -1; /* fail */
1031 else if(infop->len+1 >= infop->alloc) {
1034 newptr = realloc(infop->buffer, infop->alloc*2);
1038 return -1; /* fail */
1040 infop->buffer = newptr;
1044 infop->buffer[ infop->len ] = outc;
1048 return outc; /* fputc() returns like this on success */
1051 char *curl_maprintf(const char *format, ...)
1053 va_list ap_save; /* argument pointer */
1055 struct asprintf info;
1062 va_start(ap_save, format);
1063 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1065 if((-1 == retcode) || info.fail) {
1071 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1078 char *curl_mvaprintf(const char *format, va_list ap_save)
1081 struct asprintf info;
1088 retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
1089 if((-1 == retcode) || info.fail) {
1096 info.buffer[info.len] = 0; /* we terminate this with a zero byte */
1103 static int storebuffer(int output, FILE *data)
1105 char **buffer = (char **)data;
1106 unsigned char outc = (unsigned char)output;
1109 return outc; /* act like fputc() ! */
1112 int curl_msprintf(char *buffer, const char *format, ...)
1114 va_list ap_save; /* argument pointer */
1116 va_start(ap_save, format);
1117 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1119 *buffer=0; /* we terminate this with a zero byte */
1123 int curl_mprintf(const char *format, ...)
1126 va_list ap_save; /* argument pointer */
1127 va_start(ap_save, format);
1129 retcode = dprintf_formatf(stdout, fputc, format, ap_save);
1134 int curl_mfprintf(FILE *whereto, const char *format, ...)
1137 va_list ap_save; /* argument pointer */
1138 va_start(ap_save, format);
1139 retcode = dprintf_formatf(whereto, fputc, format, ap_save);
1144 int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
1147 retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
1148 *buffer=0; /* we terminate this with a zero byte */
1152 int curl_mvprintf(const char *format, va_list ap_save)
1154 return dprintf_formatf(stdout, fputc, format, ap_save);
1157 int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
1159 return dprintf_formatf(whereto, fputc, format, ap_save);