2 * Copyright (c) 1999-2005, 2008 Todd C. Miller <Todd.Miller@courtesan.com>
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)vfprintf.c 8.1 (Berkeley) 6/4/93
37 * v?snprintf/v?asprintf based on 4.4BSD stdio.
38 * NOTE: does not support floating point.
43 #include <sys/types.h>
44 #include <sys/param.h>
54 #endif /* STDC_HEADERS */
59 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
64 # ifdef HAVE_STRINGS_H
67 #endif /* HAVE_STRING_H */
68 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
70 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
82 __unused static const char rcsid[] = "$Sudo: snprintf.c,v 1.22 2008/11/09 14:13:12 millert Exp $";
85 static int xxxprintf __P((char **, size_t, int, const char *, va_list));
88 * Some systems may not have these defined in <limits.h>
91 # define ULONG_MAX ((unsigned long)-1)
94 # define LONG_MAX (ULONG_MAX / 2)
99 # define ULLONG_MAX UQUAD_MAX
101 # define ULLONG_MAX ((unsigned long long)-1)
106 # define LLONG_MAX QUAD_MAX
108 # define LLONG_MAX (ULLONG_MAX / 2)
111 #endif /* HAVE_LONG_LONG */
114 * Macros for converting digits to letters and vice versa
116 #define to_digit(c) ((c) - '0')
117 #define is_digit(c) ((unsigned int)to_digit(c) <= 9)
118 #define to_char(n) ((n) + '0')
121 * Flags used during conversion.
123 #define ALT 0x001 /* alternate form */
124 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
125 #define LADJUST 0x004 /* left adjustment */
126 #define LONGDBL 0x008 /* long double; unimplemented */
127 #define LONGINT 0x010 /* long integer */
128 #define QUADINT 0x020 /* quad integer */
129 #define SHORTINT 0x040 /* short integer */
130 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
142 const unsigned char *p = s;
146 return ((void *)(p - 1));
151 #endif /* !HAVE_MEMCHR */
154 * Convert an unsigned long to ASCII for printf purposes, returning
155 * a pointer to the first character of the string representation.
156 * Octal numbers can be forced to have a leading zero; hex numbers
157 * use the given digits.
160 __ultoa(val, endp, base, octzero, xdigs)
170 * Handle the three cases separately, in the hope of getting
171 * better/faster code.
175 if (val < 10) { /* many numbers are 1 digit */
176 *--cp = to_char(val);
180 * On many machines, unsigned arithmetic is harder than
181 * signed arithmetic, so we do at most one unsigned mod and
182 * divide; this is sufficient to reduce the range of
183 * the incoming value to where signed arithmetic works.
185 if (val > LONG_MAX) {
186 *--cp = to_char(val % 10);
191 *--cp = to_char(sval % 10);
198 *--cp = to_char(val & 7);
201 if (octzero && *cp != '0')
207 *--cp = xdigs[val & 15];
218 /* Identical to __ultoa, but for quads. */
219 #ifdef HAVE_LONG_LONG
221 # define __uqtoa(v, e, b, o, x) __ultoa((unsigned long)(v), (e), (b), (o), (x))
224 __uqtoa(val, endp, base, octzero, xdigs)
225 unsigned long long val;
233 /* quick test for small values; __ultoa is typically much faster */
234 /* (perhaps instead we should run until small, then call __ultoa?) */
235 if (val <= (unsigned long long)ULONG_MAX)
236 return (__ultoa((unsigned long)val, endp, base, octzero, xdigs));
240 *--cp = to_char(val % 10);
243 if (val > LLONG_MAX) {
244 *--cp = to_char(val % 10);
249 *--cp = to_char(sval % 10);
256 *--cp = to_char(val & 7);
259 if (octzero && *cp != '0')
265 *--cp = xdigs[val & 15];
275 # endif /* !LONG_IS_QUAD */
276 #endif /* HAVE_LONG_LONG */
279 * Actual printf innards.
282 xxxprintf(strp, strsize, alloc, fmt0, ap)
289 char *fmt; /* format string */
290 int ch; /* character from fmt */
291 int n; /* handy integer (short term usage) */
292 char *cp; /* handy char pointer (short term usage) */
293 int flags; /* flags as above */
294 int ret; /* return value accumulator */
295 int width; /* width from format (%8d), or 0 */
296 int prec; /* precision from format (%.3d), or -1 */
297 char sign; /* sign prefix (' ', '+', '-', or \0) */
298 unsigned long ulval; /* integer arguments %[diouxX] */
299 #ifdef HAVE_LONG_LONG
300 unsigned long long uqval; /* %q (quad) integers */
302 int base; /* base for [diouxX] conversion */
303 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
304 int fieldsz; /* field size expanded by sign, etc */
305 int realsz; /* field size expanded by dprec */
306 int size; /* size of converted field or string */
307 char *xdigs; /* digits for [xX] conversion */
308 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
309 char ox[2]; /* space for 0x hex-prefix */
310 char *str; /* pointer to string to fill */
311 char *estr; /* pointer to last char in str */
314 * Choose PADSIZE to trade efficiency vs. size. If larger printf
315 * fields occur frequently, increase PADSIZE and make the initialisers
318 #define PADSIZE 16 /* pad chunk size */
319 static char blanks[PADSIZE] =
320 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
321 static char zeroes[PADSIZE] =
322 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
324 /* Print chars to "str", (allocate as needed if alloc is set). */
325 #define PRINT(ptr, len) do { \
326 const char *p = ptr; \
327 const char *endp = ptr + len; \
328 while (p < endp && (str < estr || alloc)) { \
329 if (alloc && str >= estr) { \
331 strsize = (strsize << 1) + 1; \
332 if (!(t = (char *)realloc(*strp, strsize))) { \
338 str = t + (str - *strp); \
339 estr = t + strsize - 1; \
346 /* BEWARE, PAD uses `n'. */
347 #define PAD(howmany, with) do { \
348 if ((n = (howmany)) > 0) { \
349 while (n > PADSIZE) { \
350 PRINT(with, PADSIZE); \
358 * To extend shorts properly, we need both signed and unsigned
359 * argument extraction methods.
362 (flags&LONGINT ? va_arg(ap, long) : \
363 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
364 (long)va_arg(ap, int))
366 (flags&LONGINT ? va_arg(ap, unsigned long) : \
367 flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(ap, int) : \
368 (unsigned long)va_arg(ap, unsigned int))
375 *strp = str = (char *)malloc(strsize);
384 estr = str + strsize - 1;
390 * Scan the format for conversions (`%' character).
393 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
395 if ((n = fmt - cp) != 0) {
401 fmt++; /* skip over '%' */
410 reswitch: switch (ch) {
413 * ``If the space and + flags both appear, the space
414 * flag will be ignored.''
425 * ``A negative field width argument is taken as a
426 * - flag followed by a positive field width.''
428 * They don't exclude field widths read from args.
430 if ((width = va_arg(ap, int)) >= 0)
441 if ((ch = *fmt++) == '*') {
443 prec = n < 0 ? -1 : n;
447 while (is_digit(ch)) {
448 n = 10 * n + to_digit(ch);
451 prec = n < 0 ? -1 : n;
455 * ``Note that 0 is taken as a flag, not as the
456 * beginning of a field width.''
461 case '1': case '2': case '3': case '4':
462 case '5': case '6': case '7': case '8': case '9':
465 n = 10 * n + to_digit(ch);
467 } while (is_digit(ch));
476 #ifdef HAVE_LONG_LONG
480 #endif /* HAVE_LONG_LONG */
482 *(cp = buf) = va_arg(ap, int);
491 #ifdef HAVE_LONG_LONG
492 if (flags & QUADINT) {
493 uqval = va_arg(ap, long long);
494 if ((long long)uqval < 0) {
500 #endif /* HAVE_LONG_LONG */
503 if ((long)ulval < 0) {
511 #ifdef HAVE_LONG_LONG
513 *va_arg(ap, long long *) = ret;
515 #endif /* HAVE_LONG_LONG */
517 *va_arg(ap, long *) = ret;
518 else if (flags & SHORTINT)
519 *va_arg(ap, short *) = ret;
521 *va_arg(ap, int *) = ret;
522 continue; /* no output */
527 #ifdef HAVE_LONG_LONG
529 uqval = va_arg(ap, unsigned long long);
531 #endif /* HAVE_LONG_LONG */
537 * ``The argument shall be a pointer to void. The
538 * value of the pointer is converted to a sequence
539 * of printable characters, in an implementation-
543 ulval = (unsigned long)va_arg(ap, void *);
545 xdigs = "0123456789abcdef";
546 flags = (flags & ~QUADINT) | HEXPREFIX;
550 if ((cp = va_arg(ap, char *)) == NULL)
554 * can't use strlen; can only look for the
555 * NUL in the first `prec' characters, and
556 * strlen() will go further.
558 char *p = memchr(cp, 0, prec);
574 #ifdef HAVE_LONG_LONG
576 uqval = va_arg(ap, unsigned long long);
578 #endif /* HAVE_LONG_LONG */
583 xdigs = "0123456789ABCDEF";
586 xdigs = "0123456789abcdef";
588 #ifdef HAVE_LONG_LONG
590 uqval = va_arg(ap, unsigned long long);
592 #endif /* HAVE_LONG_LONG */
595 /* leading 0x/X only if non-zero */
597 #ifdef HAVE_LONG_LONG
598 (flags & QUADINT ? uqval != 0 : ulval != 0))
601 #endif /* HAVE_LONG_LONG */
604 /* unsigned conversions */
607 * ``... diouXx conversions ... if a precision is
608 * specified, the 0 flag will be ignored.''
611 number: if ((dprec = prec) >= 0)
615 * ``The result of converting a zero value with an
616 * explicit precision of zero is no characters.''
620 #ifdef HAVE_LONG_LONG
621 if (flags & QUADINT) {
622 if (uqval != 0 || prec != 0)
623 cp = __uqtoa(uqval, cp, base,
627 #endif /* HAVE_LONG_LONG */
629 if (ulval != 0 || prec != 0)
630 cp = __ultoa(ulval, cp, base,
633 size = buf + BUF - cp;
635 default: /* "%?" prints ?, unless ? is NUL */
638 /* pretend it was %c with argument ch */
647 * All reasonable formats wind up here. At this point, `cp'
648 * points to a string which (if not flags&LADJUST) should be
649 * padded out to `width' places. If flags&ZEROPAD, it should
650 * first be prefixed by any sign or other prefix; otherwise,
651 * it should be blank padded before the prefix is emitted.
652 * After any left-hand padding and prefixing, emit zeroes
653 * required by a decimal [diouxX] precision, then print the
654 * string proper, then emit zeroes required by any leftover
655 * floating precision; finally, if LADJUST, pad with blanks.
657 * Compute actual size, so we know how much to pad.
658 * fieldsz excludes decimal prec; realsz includes it.
663 else if (flags & HEXPREFIX)
665 realsz = dprec > fieldsz ? dprec : fieldsz;
667 /* right-adjusting blank padding */
668 if ((flags & (LADJUST|ZEROPAD)) == 0)
669 PAD(width - realsz, blanks);
674 } else if (flags & HEXPREFIX) {
680 /* right-adjusting zero padding */
681 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
682 PAD(width - realsz, zeroes);
684 /* leading zeroes from decimal precision */
685 PAD(dprec - fieldsz, zeroes);
687 /* the string or number proper */
690 /* left-adjusting padding (always blank) */
692 PAD(width - realsz, blanks);
694 /* finally, adjust ret */
695 ret += width > realsz ? width : realsz;
704 #ifndef HAVE_VSNPRINTF
706 vsnprintf(str, n, fmt, ap)
713 return (xxxprintf(&str, n, 0, fmt, ap));
715 #endif /* HAVE_VSNPRINTF */
717 #ifndef HAVE_SNPRINTF
720 snprintf(char *str, size_t n, char const *fmt, ...)
722 snprintf(str, n, fmt, va_alist)
737 ret = xxxprintf(&str, n, 0, fmt, ap);
741 #endif /* HAVE_SNPRINTF */
743 #ifndef HAVE_VASPRINTF
745 vasprintf(str, fmt, ap)
751 return (xxxprintf(str, 0, 1, fmt, ap));
753 #endif /* HAVE_VASPRINTF */
755 #ifndef HAVE_ASPRINTF
758 asprintf(char **str, char const *fmt, ...)
760 asprintf(str, fmt, va_alist)
774 ret = xxxprintf(str, 0, 1, fmt, ap);
778 #endif /* HAVE_ASPRINTF */