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, formated 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
104 # define VA_COPY(dest, src) va_copy(dest, src)
106 # ifdef HAVE___VA_COPY
107 # define VA_COPY(dest, src) __va_copy(dest, src)
109 # define VA_COPY(dest, src) (dest) = (src)
114 #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF)
123 #ifdef HAVE_LONG_DOUBLE
124 # define LDOUBLE long double
126 # define LDOUBLE double
129 #ifdef HAVE_LONG_LONG
130 # define LLONG long long
136 * dopr(): poor man's version of doprintf
139 /* format read states */
140 #define DP_S_DEFAULT 0
149 /* format flags - Bits */
150 #define DP_F_MINUS (1 << 0)
151 #define DP_F_PLUS (1 << 1)
152 #define DP_F_SPACE (1 << 2)
153 #define DP_F_NUM (1 << 3)
154 #define DP_F_ZERO (1 << 4)
155 #define DP_F_UP (1 << 5)
156 #define DP_F_UNSIGNED (1 << 6)
158 /* Conversion Flags */
161 #define DP_C_LDOUBLE 3
164 #define DP_C_INTMAX 6
166 #define char_to_int(p) ((p)- '0')
168 # define MAX(p,q) (((p) >= (q)) ? (p) : (q))
171 #define DOPR_OUTCH(buf, pos, buflen, thechar) \
173 if (pos + 1 >= INT_MAX) { \
178 buf[pos] = thechar; \
182 static int dopr(char *buffer, size_t maxlen, const char *format,
184 static int fmtstr(char *buffer, size_t *currlen, size_t maxlen,
185 char *value, int flags, int min, int max);
186 static int fmtint(char *buffer, size_t *currlen, size_t maxlen,
187 intmax_t value, int base, int min, int max, int flags);
188 static int fmtfp(char *buffer, size_t *currlen, size_t maxlen,
189 LDOUBLE fvalue, int min, int max, int flags);
192 dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
206 VA_COPY(args, args_in);
208 state = DP_S_DEFAULT;
209 currlen = flags = cflags = min = 0;
213 while (state != DP_S_DONE) {
222 DOPR_OUTCH(buffer, currlen, maxlen, ch);
253 if (isdigit((unsigned char)ch)) {
254 min = 10*min + char_to_int (ch);
256 } else if (ch == '*') {
257 min = va_arg (args, int);
273 if (isdigit((unsigned char)ch)) {
276 max = 10*max + char_to_int (ch);
278 } else if (ch == '*') {
279 max = va_arg (args, int);
293 cflags = DP_C_INTMAX;
299 if (ch == 'l') { /* It's a long long */
305 cflags = DP_C_LDOUBLE;
321 if (cflags == DP_C_SHORT)
322 value = va_arg (args, int);
323 else if (cflags == DP_C_LONG)
324 value = va_arg (args, long int);
325 else if (cflags == DP_C_LLONG)
326 value = va_arg (args, LLONG);
327 else if (cflags == DP_C_SIZE)
328 value = va_arg (args, ssize_t);
329 else if (cflags == DP_C_INTMAX)
330 value = va_arg (args, intmax_t);
332 value = va_arg (args, int);
333 if (fmtint(buffer, &currlen, maxlen,
334 value, 10, min, max, flags) == -1)
338 flags |= DP_F_UNSIGNED;
339 if (cflags == DP_C_SHORT)
340 value = va_arg (args, unsigned int);
341 else if (cflags == DP_C_LONG)
342 value = (long)va_arg (args, unsigned long int);
343 else if (cflags == DP_C_LLONG)
344 value = (long)va_arg (args, unsigned LLONG);
345 else if (cflags == DP_C_SIZE)
346 value = va_arg (args, size_t);
348 else if (cflags == DP_C_INTMAX)
349 value = va_arg (args, uintmax_t);
352 value = (long)va_arg (args, unsigned int);
353 if (fmtint(buffer, &currlen, maxlen, value,
354 8, min, max, flags) == -1)
358 flags |= DP_F_UNSIGNED;
359 if (cflags == DP_C_SHORT)
360 value = va_arg (args, unsigned int);
361 else if (cflags == DP_C_LONG)
362 value = (long)va_arg (args, unsigned long int);
363 else if (cflags == DP_C_LLONG)
364 value = (LLONG)va_arg (args, unsigned LLONG);
365 else if (cflags == DP_C_SIZE)
366 value = va_arg (args, size_t);
368 else if (cflags == DP_C_INTMAX)
369 value = va_arg (args, uintmax_t);
372 value = (long)va_arg (args, unsigned int);
373 if (fmtint(buffer, &currlen, maxlen, value,
374 10, min, max, flags) == -1)
380 flags |= DP_F_UNSIGNED;
381 if (cflags == DP_C_SHORT)
382 value = va_arg (args, unsigned int);
383 else if (cflags == DP_C_LONG)
384 value = (long)va_arg (args, unsigned long int);
385 else if (cflags == DP_C_LLONG)
386 value = (LLONG)va_arg (args, unsigned LLONG);
387 else if (cflags == DP_C_SIZE)
388 value = va_arg (args, size_t);
390 else if (cflags == DP_C_INTMAX)
391 value = va_arg (args, uintmax_t);
394 value = (long)va_arg (args, unsigned int);
395 if (fmtint(buffer, &currlen, maxlen, value,
396 16, min, max, flags) == -1)
400 if (cflags == DP_C_LDOUBLE)
401 fvalue = va_arg (args, LDOUBLE);
403 fvalue = va_arg (args, double);
404 if (fmtfp(buffer, &currlen, maxlen, fvalue,
405 min, max, flags) == -1)
411 if (cflags == DP_C_LDOUBLE)
412 fvalue = va_arg (args, LDOUBLE);
414 fvalue = va_arg (args, double);
415 if (fmtfp(buffer, &currlen, maxlen, fvalue,
416 min, max, flags) == -1)
422 if (cflags == DP_C_LDOUBLE)
423 fvalue = va_arg (args, LDOUBLE);
425 fvalue = va_arg (args, double);
426 if (fmtfp(buffer, &currlen, maxlen, fvalue,
427 min, max, flags) == -1)
431 DOPR_OUTCH(buffer, currlen, maxlen,
435 strvalue = va_arg (args, char *);
436 if (!strvalue) strvalue = "(NULL)";
438 max = strlen(strvalue);
440 if (min > 0 && max >= 0 && min > max) max = min;
441 if (fmtstr(buffer, &currlen, maxlen,
442 strvalue, flags, min, max) == -1)
446 strvalue = va_arg (args, void *);
447 if (fmtint(buffer, &currlen, maxlen,
448 (long) strvalue, 16, min, max, flags) == -1)
451 #if we_dont_want_this_in_openssh
453 if (cflags == DP_C_SHORT) {
455 num = va_arg (args, short int *);
457 } else if (cflags == DP_C_LONG) {
459 num = va_arg (args, long int *);
460 *num = (long int)currlen;
461 } else if (cflags == DP_C_LLONG) {
463 num = va_arg (args, LLONG *);
464 *num = (LLONG)currlen;
465 } else if (cflags == DP_C_SIZE) {
467 num = va_arg (args, ssize_t *);
468 *num = (ssize_t)currlen;
469 } else if (cflags == DP_C_INTMAX) {
471 num = va_arg (args, intmax_t *);
472 *num = (intmax_t)currlen;
475 num = va_arg (args, int *);
481 DOPR_OUTCH(buffer, currlen, maxlen, ch);
484 /* not supported yet, treat as next char */
492 state = DP_S_DEFAULT;
493 flags = cflags = min = 0;
500 break; /* some picky compilers need this */
504 if (currlen < maxlen - 1)
505 buffer[currlen] = '\0';
507 buffer[maxlen - 1] = '\0';
510 return currlen < INT_MAX ? (int)currlen : -1;
514 fmtstr(char *buffer, size_t *currlen, size_t maxlen,
515 char *value, int flags, int min, int max)
517 int padlen, strln; /* amount to pad */
520 #ifdef DEBUG_SNPRINTF
521 printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
527 for (strln = 0; strln < max && value[strln]; ++strln); /* strlen */
528 padlen = min - strln;
531 if (flags & DP_F_MINUS)
532 padlen = -padlen; /* Left Justify */
534 while ((padlen > 0) && (cnt < max)) {
535 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
539 while (*value && (cnt < max)) {
540 DOPR_OUTCH(buffer, *currlen, maxlen, *value);
544 while ((padlen < 0) && (cnt < max)) {
545 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
552 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
555 fmtint(char *buffer, size_t *currlen, size_t maxlen,
556 LLONG value, int base, int min, int max, int flags)
559 unsigned LLONG uvalue;
562 int spadlen = 0; /* amount to space pad */
563 int zpadlen = 0; /* amount to zero pad */
571 if(!(flags & DP_F_UNSIGNED)) {
576 if (flags & DP_F_PLUS) /* Do a sign (+/i) */
578 else if (flags & DP_F_SPACE)
583 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
587 (caps? "0123456789ABCDEF":"0123456789abcdef")
588 [uvalue % (unsigned)base ];
589 uvalue = (uvalue / (unsigned)base );
590 } while(uvalue && (place < 20));
591 if (place == 20) place--;
594 zpadlen = max - place;
595 spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
596 if (zpadlen < 0) zpadlen = 0;
597 if (spadlen < 0) spadlen = 0;
598 if (flags & DP_F_ZERO) {
599 zpadlen = MAX(zpadlen, spadlen);
602 if (flags & DP_F_MINUS)
603 spadlen = -spadlen; /* Left Justifty */
605 #ifdef DEBUG_SNPRINTF
606 printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
607 zpadlen, spadlen, min, max, place);
611 while (spadlen > 0) {
612 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
618 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
622 while (zpadlen > 0) {
623 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
631 DOPR_OUTCH(buffer, *currlen, maxlen, convert[place]);
634 /* Left Justified spaces */
635 while (spadlen < 0) {
636 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
642 static LDOUBLE abs_val(LDOUBLE value)
644 LDOUBLE result = value;
652 static LDOUBLE POW10(int val)
664 static LLONG ROUND(LDOUBLE value)
668 intpart = (LLONG)value;
669 value = value - intpart;
670 if (value >= 0.5) intpart++;
675 /* a replacement for modf that doesn't need the math library. Should
676 be portable, but slow */
677 static double my_modf(double x0, double *iptr)
684 for (i=0;i<100;i++) {
686 if (l <= (x+1) && l >= (x-1)) break;
693 * yikes! the number is beyond what we can handle.
704 ret = my_modf(x0-l*f, &i2);
715 fmtfp (char *buffer, size_t *currlen, size_t maxlen,
716 LDOUBLE fvalue, int min, int max, int flags)
724 int padlen = 0; /* amount to pad */
733 * AIX manpage says the default is 0, but Solaris says the default
734 * is 6, and sprintf on AIX defaults to 6
739 ufvalue = abs_val (fvalue);
744 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
747 if (flags & DP_F_SPACE)
753 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
757 if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
761 * Sorry, we only support 16 digits past the decimal because of our
767 /* We "cheat" by converting the fractional part to integer by
768 * multiplying by a factor of 10
772 my_modf(temp, &intpart);
774 fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
776 if (fracpart >= POW10(max)) {
778 fracpart -= POW10(max);
781 /* Convert integer part */
784 my_modf(temp, &intpart);
785 idx = (int) ((temp -intpart +0.05)* 10.0);
786 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
787 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
789 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
790 } while (intpart && (iplace < 311));
791 if (iplace == 311) iplace--;
792 iconvert[iplace] = 0;
794 /* Convert fractional part */
799 my_modf(temp, &fracpart);
800 idx = (int) ((temp -fracpart +0.05)* 10.0);
801 /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
802 /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
804 (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
805 } while(fracpart && (fplace < 311));
806 if (fplace == 311) fplace--;
808 fconvert[fplace] = 0;
810 /* -1 for decimal point, another -1 if we are printing a sign */
811 padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
812 zpadlen = max - fplace;
813 if (zpadlen < 0) zpadlen = 0;
816 if (flags & DP_F_MINUS)
817 padlen = -padlen; /* Left Justifty */
819 if ((flags & DP_F_ZERO) && (padlen > 0)) {
821 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
826 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
831 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
835 DOPR_OUTCH(buffer, *currlen, maxlen, signvalue);
839 DOPR_OUTCH(buffer, *currlen, maxlen, iconvert[iplace]);
842 #ifdef DEBUG_SNPRINTF
843 printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
847 * Decimal point. This should probably use locale to find the correct
851 DOPR_OUTCH(buffer, *currlen, maxlen, '.');
853 while (zpadlen > 0) {
854 DOPR_OUTCH(buffer, *currlen, maxlen, '0');
860 DOPR_OUTCH(buffer, *currlen, maxlen, fconvert[fplace]);
865 DOPR_OUTCH(buffer, *currlen, maxlen, ' ');
870 #endif /* !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) */
872 #if !defined(HAVE_VSNPRINTF)
874 vsnprintf (char *str, size_t count, const char *fmt, va_list args)
876 return dopr(str, count, fmt, args);
880 #if !defined(HAVE_SNPRINTF)
882 snprintf(char *str, size_t count, SNPRINTF_CONST char *fmt, ...)
888 ret = vsnprintf(str, count, fmt, ap);