2 * Copyright Patrick Powell 1995
3 * This code is based on code written by Patrick Powell (papowell@astart.com)
4 * It may be used for any purpose as long as this notice remains intact
5 * on all source code distributions
8 /**************************************************************
10 * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
11 * A bombproof version of doprnt (dopr) included.
12 * Sigh. This sort of thing is always nasty do deal with. Note that
13 * the version here does not include floating point...
15 * snprintf() is used instead of sprintf() as it does limit checks
16 * for string length. This covers a nasty loophole.
18 * The other functions are there to prevent NULL pointers from
19 * causing nast effects.
22 * Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
23 * This was ugly. It is still ugly. I opted out of floating point
24 * numbers, but the formatter understands just about everything
25 * from the normal C string format, at least as far as I can tell from
26 * the Solaris 2.5 printf(3S) man page.
28 * Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
29 * Ok, added some minimal floating point support, which means this
30 * probably requires libm on most operating systems. Don't yet
31 * support the exponent (e,E) and sigfig (g,G). Also, fmtint()
32 * was pretty badly broken, it just wasn't being exercised in ways
33 * which showed it, so that's been fixed. Also, formatted the code
34 * to mutt conventions, and removed dead code left over from the
35 * original. Also, there is now a builtin-test, just compile with:
36 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
37 * and run snprintf for results.
39 * Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
40 * The PGP code was using unsigned hexadecimal formats.
41 * Unfortunately, unsigned formats simply didn't work.
43 * Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
44 * The original code assumed that both snprintf() and vsnprintf() were
45 * missing. Some systems only have snprintf() but not vsnprintf(), so
46 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
48 * Andrew Tridgell (tridge@samba.org) Oct 1998
49 * fixed handling of %.0f
50 * added test for HAVE_LONG_DOUBLE
52 * tridge@samba.org, idra@samba.org, April 2001
53 * got rid of fcvt code (twas buggy and made testing harder)
56 * date: 2002/12/19 19:56:31; author: herb; state: Exp; lines: +2 -0
57 * actually print args for %g and %e
59 * date: 2002/06/03 13:37:52; author: jmcd; state: Exp; lines: +8 -0
60 * Since includes.h isn't included here, VA_COPY has to be defined here. I don't
61 * see any include file that is guaranteed to be here, so I'm defining it
62 * locally. Fixes AIX and Solaris builds.
64 * date: 2002/06/03 03:07:24; author: tridge; state: Exp; lines: +5 -13
65 * put the ifdef for HAVE_VA_COPY in one place rather than in lots of
68 * date: 2002/05/17 14:51:22; author: jmcd; state: Exp; lines: +21 -4
69 * Fix usage of va_list passed as an arg. Use __va_copy before using it
72 * date: 2002/04/16 22:38:04; author: idra; state: Exp; lines: +20 -14
73 * Fix incorrect zpadlen handling in fmtfp.
74 * Thanks to Ollie Oldham <ollie.oldham@metro-optix.com> for spotting it.
75 * few mods to make it easier to compile the tests.
76 * addedd the "Ollie" test to the floating point ones.
78 * Martin Pool (mbp@samba.org) April 2003
79 * Remove NO_CONFIG_H so that the test case can be built within a source
80 * tree with less trouble.
81 * Remove unnecessary SAFE_FREE() definition.
83 * Martin Pool (mbp@samba.org) May 2003
84 * Put in a prototype for dummy_snprintf() to quiet compiler warnings.
86 * Move #endif to make sure VA_COPY, LDOUBLE, etc are defined even
87 * if the C library has some snprintf functions already.
89 * Damien Miller (djm@mindrot.org) Jan 2007
90 * Fix integer overflows in return value.
91 * Make formatting quite a bit faster by inlining dopr_outch()
93 **************************************************************/
97 #if defined(BROKEN_SNPRINTF) /* For those with broken snprintf() */
99 # undef HAVE_VSNPRINTF
102 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
111 #ifdef HAVE_LONG_DOUBLE
112 # define LDOUBLE long double
114 # define LDOUBLE double
117 #ifdef HAVE_LONG_LONG
118 # define LLONG long long
124 * dopr(): poor man's version of doprintf
127 /* format read states */
128 #define DP_S_DEFAULT 0
137 /* format flags - Bits */
138 #define DP_F_MINUS (1 << 0)
139 #define DP_F_PLUS (1 << 1)
140 #define DP_F_SPACE (1 << 2)
141 #define DP_F_NUM (1 << 3)
142 #define DP_F_ZERO (1 << 4)
143 #define DP_F_UP (1 << 5)
144 #define DP_F_UNSIGNED (1 << 6)
146 /* Conversion Flags */
149 #define DP_C_LDOUBLE 3
152 #define DP_C_INTMAX 6
154 #define char_to_int(p) ((p)- '0')
156 # define MAX(p,q) (((p) >= (q)) ? (p) : (q))
159 #define DOPR_OUTCH(buf, pos, buflen, thechar) \
161 if (pos + 1 >= INT_MAX) { \
166 buf[pos] = thechar; \
170 static int dopr(char *buffer, size_t maxlen, const char *format,
172 static int fmtstr(char *buffer, size_t *currlen, size_t maxlen,
173 char *value, int flags, int min, int max);
174 static int fmtint(char *buffer, size_t *currlen, size_t maxlen,
175 intmax_t value, int base, int min, int max, int flags);
176 static int fmtfp(char *buffer, size_t *currlen, size_t maxlen,
177 LDOUBLE fvalue, int min, int max, int flags);
180 dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
194 VA_COPY(args, args_in);
196 state = DP_S_DEFAULT;
197 currlen = flags = cflags = min = 0;
201 while (state != DP_S_DONE) {
210 DOPR_OUTCH(buffer, currlen, maxlen, ch);
241 if (isdigit((unsigned char)ch)) {
242 min = 10*min + char_to_int (ch);
244 } else if (ch == '*') {
245 min = va_arg (args, int);
261 if (isdigit((unsigned char)ch)) {
264 max = 10*max + char_to_int (ch);
266 } else if (ch == '*') {
267 max = va_arg (args, int);
281 cflags = DP_C_INTMAX;
287 if (ch == 'l') { /* It's a long long */
293 cflags = DP_C_LDOUBLE;
309 if (cflags == DP_C_SHORT)
310 value = va_arg (args, int);
311 else if (cflags == DP_C_LONG)
312 value = va_arg (args, long int);
313 else if (cflags == DP_C_LLONG)
314 value = va_arg (args, LLONG);
315 else if (cflags == DP_C_SIZE)
316 value = va_arg (args, ssize_t);
317 else if (cflags == DP_C_INTMAX)
318 value = va_arg (args, intmax_t);
320 value = va_arg (args, int);
321 if (fmtint(buffer, &currlen, maxlen,
322 value, 10, min, max, flags) == -1)
326 flags |= DP_F_UNSIGNED;
327 if (cflags == DP_C_SHORT)
328 value = va_arg (args, unsigned int);
329 else if (cflags == DP_C_LONG)
330 value = (long)va_arg (args, unsigned long int);
331 else if (cflags == DP_C_LLONG)
332 value = (long)va_arg (args, unsigned LLONG);
333 else if (cflags == DP_C_SIZE)
334 value = va_arg (args, size_t);
336 else if (cflags == DP_C_INTMAX)
337 value = va_arg (args, uintmax_t);
340 value = (long)va_arg (args, unsigned int);
341 if (fmtint(buffer, &currlen, maxlen, value,
342 8, min, max, flags) == -1)
346 flags |= DP_F_UNSIGNED;
347 if (cflags == DP_C_SHORT)
348 value = va_arg (args, unsigned int);
349 else if (cflags == DP_C_LONG)
350 value = (long)va_arg (args, unsigned long int);
351 else if (cflags == DP_C_LLONG)
352 value = (LLONG)va_arg (args, unsigned LLONG);
353 else if (cflags == DP_C_SIZE)
354 value = va_arg (args, size_t);
356 else if (cflags == DP_C_INTMAX)
357 value = va_arg (args, uintmax_t);
360 value = (long)va_arg (args, unsigned int);
361 if (fmtint(buffer, &currlen, maxlen, value,
362 10, min, max, flags) == -1)
368 flags |= DP_F_UNSIGNED;
369 if (cflags == DP_C_SHORT)
370 value = va_arg (args, unsigned int);
371 else if (cflags == DP_C_LONG)
372 value = (long)va_arg (args, unsigned long int);
373 else if (cflags == DP_C_LLONG)
374 value = (LLONG)va_arg (args, unsigned LLONG);
375 else if (cflags == DP_C_SIZE)
376 value = va_arg (args, size_t);
378 else if (cflags == DP_C_INTMAX)
379 value = va_arg (args, uintmax_t);
382 value = (long)va_arg (args, unsigned int);
383 if (fmtint(buffer, &currlen, maxlen, value,
384 16, min, max, flags) == -1)
388 if (cflags == DP_C_LDOUBLE)
389 fvalue = va_arg (args, LDOUBLE);
391 fvalue = va_arg (args, double);
392 if (fmtfp(buffer, &currlen, maxlen, fvalue,
393 min, max, flags) == -1)
399 if (cflags == DP_C_LDOUBLE)
400 fvalue = va_arg (args, LDOUBLE);
402 fvalue = va_arg (args, double);
403 if (fmtfp(buffer, &currlen, maxlen, fvalue,
404 min, max, flags) == -1)
410 if (cflags == DP_C_LDOUBLE)
411 fvalue = va_arg (args, LDOUBLE);
413 fvalue = va_arg (args, double);
414 if (fmtfp(buffer, &currlen, maxlen, fvalue,
415 min, max, flags) == -1)
419 DOPR_OUTCH(buffer, currlen, maxlen,
423 strvalue = va_arg (args, char *);
424 if (!strvalue) strvalue = "(NULL)";
426 max = strlen(strvalue);
428 if (min > 0 && max >= 0 && min > max) max = min;
429 if (fmtstr(buffer, &currlen, maxlen,
430 strvalue, flags, min, max) == -1)
434 strvalue = va_arg (args, void *);
435 if (fmtint(buffer, &currlen, maxlen,
436 (long) strvalue, 16, min, max, flags) == -1)
439 #if we_dont_want_this_in_openssh
441 if (cflags == DP_C_SHORT) {
443 num = va_arg (args, short int *);
445 } else if (cflags == DP_C_LONG) {
447 num = va_arg (args, long int *);
448 *num = (long int)currlen;
449 } else if (cflags == DP_C_LLONG) {
451 num = va_arg (args, LLONG *);
452 *num = (LLONG)currlen;
453 } else if (cflags == DP_C_SIZE) {
455 num = va_arg (args, ssize_t *);
456 *num = (ssize_t)currlen;
457 } else if (cflags == DP_C_INTMAX) {
459 num = va_arg (args, intmax_t *);
460 *num = (intmax_t)currlen;
463 num = va_arg (args, int *);
469 DOPR_OUTCH(buffer, currlen, maxlen, ch);
472 /* not supported yet, treat as next char */
480 state = DP_S_DEFAULT;
481 flags = cflags = min = 0;
488 break; /* some picky compilers need this */
492 if (currlen < maxlen - 1)
493 buffer[currlen] = '\0';
495 buffer[maxlen - 1] = '\0';
498 return currlen < INT_MAX ? (int)currlen : -1;
502 fmtstr(char *buffer, size_t *currlen, size_t maxlen,
503 char *value, int flags, int min, int max)
505 int padlen, strln; /* amount to pad */
508 #ifdef DEBUG_SNPRINTF
509 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
515 for (strln = 0; strln < max && value[strln]; ++strln); /* strlen */
516 padlen = min - strln;
519 if (flags & DP_F_MINUS)
520 padlen = -padlen; /* Left Justify */
522 while ((padlen > 0) && (cnt < max)) {
523 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
527 while (*value && (cnt < max)) {
528 DOPR_OUTCH(buffer, *currlen, maxlen, *value);
532 while ((padlen < 0) && (cnt < max)) {
533 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
540 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
543 fmtint(char *buffer, size_t *currlen, size_t maxlen,
544 intmax_t value, int base, int min, int max, int flags)
547 unsigned LLONG uvalue;
550 int spadlen = 0; /* amount to space pad */
551 int zpadlen = 0; /* amount to zero pad */
559 if(!(flags & DP_F_UNSIGNED)) {
564 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
566 else if (flags & DP_F_SPACE)
571 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
575 (caps? "0123456789ABCDEF":"0123456789abcdef")
576 [uvalue % (unsigned)base ];
577 uvalue = (uvalue / (unsigned)base );
578 } while(uvalue && (place < 20));
579 if (place == 20) place--;
582 zpadlen = max - place;
583 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
584 if (zpadlen < 0) zpadlen = 0;
585 if (spadlen < 0) spadlen = 0;
586 if (flags & DP_F_ZERO) {
587 zpadlen = MAX(zpadlen, spadlen);
590 if (flags & DP_F_MINUS)
591 spadlen = -spadlen; /* Left Justifty */
593 #ifdef DEBUG_SNPRINTF
594 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
595 zpadlen, spadlen, min, max, place);
599 while (spadlen > 0) {
600 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
606 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
610 while (zpadlen > 0) {
611 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
619 DOPR_OUTCH(buffer, *currlen, maxlen, convert[place]);
622 /* Left Justified spaces */
623 while (spadlen < 0) {
624 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
630 static LDOUBLE abs_val(LDOUBLE value)
632 LDOUBLE result = value;
640 static LDOUBLE POW10(int val)
652 static LLONG ROUND(LDOUBLE value)
656 intpart = (LLONG)value;
657 value = value - intpart;
658 if (value >= 0.5) intpart++;
663 /* a replacement for modf that doesn't need the math library. Should
664 be portable, but slow */
665 static double my_modf(double x0, double *iptr)
672 for (i=0;i<100;i++) {
674 if (l <= (x+1) && l >= (x-1)) break;
681 * yikes! the number is beyond what we can handle.
692 ret = my_modf(x0-l*f, &i2);
703 fmtfp (char *buffer, size_t *currlen, size_t maxlen,
704 LDOUBLE fvalue, int min, int max, int flags)
712 int padlen = 0; /* amount to pad */
721 * AIX manpage says the default is 0, but Solaris says the default
722 * is 6, and sprintf on AIX defaults to 6
727 ufvalue = abs_val (fvalue);
732 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
735 if (flags & DP_F_SPACE)
741 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
745 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
749 * Sorry, we only support 16 digits past the decimal because of our
755 /* We "cheat" by converting the fractional part to integer by
756 * multiplying by a factor of 10
760 my_modf(temp, &intpart);
762 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
764 if (fracpart >= POW10(max)) {
766 fracpart -= POW10(max);
769 /* Convert integer part */
772 my_modf(temp, &intpart);
773 idx = (int) ((temp -intpart +0.05)* 10.0);
774 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
775 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
777 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
778 } while (intpart && (iplace < 311));
779 if (iplace == 311) iplace--;
780 iconvert[iplace] = 0;
782 /* Convert fractional part */
787 my_modf(temp, &fracpart);
788 idx = (int) ((temp -fracpart +0.05)* 10.0);
789 /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
790 /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
792 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
793 } while(fracpart && (fplace < 311));
794 if (fplace == 311) fplace--;
796 fconvert[fplace] = 0;
798 /* -1 for decimal point, another -1 if we are printing a sign */
799 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
800 zpadlen = max - fplace;
801 if (zpadlen < 0) zpadlen = 0;
804 if (flags & DP_F_MINUS)
805 padlen = -padlen; /* Left Justifty */
807 if ((flags & DP_F_ZERO) && (padlen > 0)) {
809 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
814 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
819 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
823 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
827 DOPR_OUTCH(buffer, *currlen, maxlen, iconvert[iplace]);
830 #ifdef DEBUG_SNPRINTF
831 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
835 * Decimal point. This should probably use locale to find the correct
839 DOPR_OUTCH(buffer, *currlen, maxlen, '.');
841 while (zpadlen > 0) {
842 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
848 DOPR_OUTCH(buffer, *currlen, maxlen, fconvert[fplace]);
853 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
858 #endif /* !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) */
860 #if !defined(HAVE_VSNPRINTF)
862 vsnprintf (char *str, size_t count, const char *fmt, va_list args)
864 return dopr(str, count, fmt, args);
868 #if !defined(HAVE_SNPRINTF)
870 snprintf(char *str, size_t count, SNPRINTF_CONST char *fmt, ...)
876 ret = vsnprintf(str, count, fmt, ap);