2 * Copyright (c) 1999-2005 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 */
56 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
61 # ifdef HAVE_STRINGS_H
64 #endif /* HAVE_STRING_H */
65 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
67 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
79 __unused static const char rcsid[] = "$Sudo: snprintf.c,v 1.14.4.2 2007/06/12 01:28:42 millert Exp $";
82 static int xxxprintf __P((char **, size_t, int, const char *, va_list));
85 * Some systems may not have these defined in <limits.h>
88 # define ULONG_MAX ((unsigned long)-1)
91 # define LONG_MAX (ULONG_MAX / 2)
95 # ifdef ULONG_LONG_MAX
96 # define UQUAD_MAX ULONG_LONG_MAX
98 # define UQUAD_MAX ((unsigned long long)-1)
102 # ifdef LONG_LONG_MAX
103 # define QUAD_MAX LONG_LONG_MAX
105 # define QUAD_MAX (UQUAD_MAX / 2)
108 #endif /* HAVE_LONG_LONG */
111 * Macros for converting digits to letters and vice versa
113 #define to_digit(c) ((c) - '0')
114 #define is_digit(c) ((unsigned int)to_digit(c) <= 9)
115 #define to_char(n) ((n) + '0')
118 * Flags used during conversion.
120 #define ALT 0x001 /* alternate form */
121 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
122 #define LADJUST 0x004 /* left adjustment */
123 #define LONGDBL 0x008 /* long double; unimplemented */
124 #define LONGINT 0x010 /* long integer */
125 #define QUADINT 0x020 /* quad integer */
126 #define SHORTINT 0x040 /* short integer */
127 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
139 const unsigned char *p = s;
143 return ((VOID *)(p - 1));
148 #endif /* !HAVE_MEMCHR */
151 * Convert an unsigned long to ASCII for printf purposes, returning
152 * a pointer to the first character of the string representation.
153 * Octal numbers can be forced to have a leading zero; hex numbers
154 * use the given digits.
157 __ultoa(val, endp, base, octzero, xdigs)
167 * Handle the three cases separately, in the hope of getting
168 * better/faster code.
172 if (val < 10) { /* many numbers are 1 digit */
173 *--cp = to_char(val);
177 * On many machines, unsigned arithmetic is harder than
178 * signed arithmetic, so we do at most one unsigned mod and
179 * divide; this is sufficient to reduce the range of
180 * the incoming value to where signed arithmetic works.
182 if (val > LONG_MAX) {
183 *--cp = to_char(val % 10);
188 *--cp = to_char(sval % 10);
195 *--cp = to_char(val & 7);
198 if (octzero && *cp != '0')
204 *--cp = xdigs[val & 15];
215 /* Identical to __ultoa, but for quads. */
216 #ifdef HAVE_LONG_LONG
218 # define __uqtoa(v, e, b, o, x) __ultoa((unsigned long)(v), (e), (b), (o), (x))
221 __uqtoa(val, endp, base, octzero, xdigs)
222 unsigned long long val;
230 /* quick test for small values; __ultoa is typically much faster */
231 /* (perhaps instead we should run until small, then call __ultoa?) */
232 if (val <= (unsigned long long)ULONG_MAX)
233 return (__ultoa((unsigned long)val, endp, base, octzero, xdigs));
237 *--cp = to_char(val % 10);
240 if (val > QUAD_MAX) {
241 *--cp = to_char(val % 10);
246 *--cp = to_char(sval % 10);
253 *--cp = to_char(val & 7);
256 if (octzero && *cp != '0')
262 *--cp = xdigs[val & 15];
272 # endif /* !LONG_IS_QUAD */
273 #endif /* HAVE_LONG_LONG */
276 * Actual printf innards.
279 xxxprintf(strp, strsize, alloc, fmt0, ap)
286 char *fmt; /* format string */
287 int ch; /* character from fmt */
288 int n; /* handy integer (short term usage) */
289 char *cp; /* handy char pointer (short term usage) */
290 int flags; /* flags as above */
291 int ret; /* return value accumulator */
292 int width; /* width from format (%8d), or 0 */
293 int prec; /* precision from format (%.3d), or -1 */
294 char sign; /* sign prefix (' ', '+', '-', or \0) */
295 unsigned long ulval; /* integer arguments %[diouxX] */
296 #ifdef HAVE_LONG_LONG
297 unsigned long long uqval; /* %q (quad) integers */
299 int base; /* base for [diouxX] conversion */
300 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
301 int fieldsz; /* field size expanded by sign, etc */
302 int realsz; /* field size expanded by dprec */
303 int size; /* size of converted field or string */
304 char *xdigs; /* digits for [xX] conversion */
305 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
306 char ox[2]; /* space for 0x hex-prefix */
307 char *str; /* pointer to string to fill */
308 char *estr; /* pointer to last char in str */
311 * Choose PADSIZE to trade efficiency vs. size. If larger printf
312 * fields occur frequently, increase PADSIZE and make the initialisers
315 #define PADSIZE 16 /* pad chunk size */
316 static char blanks[PADSIZE] =
317 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
318 static char zeroes[PADSIZE] =
319 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
321 /* Print chars to "str", (allocate as needed if alloc is set). */
322 #define PRINT(ptr, len) do { \
323 const char *p = ptr; \
324 const char *endp = ptr + len; \
325 while (p < endp && (str < estr || alloc)) { \
326 if (alloc && str >= estr) { \
328 strsize = (strsize << 1) + 1; \
329 if (!(t = (char *)realloc(*strp, strsize))) { \
335 str = t + (str - *strp); \
336 estr = t + strsize - 1; \
343 /* BEWARE, PAD uses `n'. */
344 #define PAD(howmany, with) do { \
345 if ((n = (howmany)) > 0) { \
346 while (n > PADSIZE) { \
347 PRINT(with, PADSIZE); \
355 * To extend shorts properly, we need both signed and unsigned
356 * argument extraction methods.
359 (flags&LONGINT ? va_arg(ap, long) : \
360 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
361 (long)va_arg(ap, int))
363 (flags&LONGINT ? va_arg(ap, unsigned long) : \
364 flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(ap, int) : \
365 (unsigned long)va_arg(ap, unsigned int))
372 *strp = str = (char *)malloc(strsize);
381 estr = str + strsize - 1;
387 * Scan the format for conversions (`%' character).
390 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
392 if ((n = fmt - cp) != 0) {
398 fmt++; /* skip over '%' */
407 reswitch: switch (ch) {
410 * ``If the space and + flags both appear, the space
411 * flag will be ignored.''
422 * ``A negative field width argument is taken as a
423 * - flag followed by a positive field width.''
425 * They don't exclude field widths read from args.
427 if ((width = va_arg(ap, int)) >= 0)
438 if ((ch = *fmt++) == '*') {
440 prec = n < 0 ? -1 : n;
444 while (is_digit(ch)) {
445 n = 10 * n + to_digit(ch);
448 prec = n < 0 ? -1 : n;
452 * ``Note that 0 is taken as a flag, not as the
453 * beginning of a field width.''
458 case '1': case '2': case '3': case '4':
459 case '5': case '6': case '7': case '8': case '9':
462 n = 10 * n + to_digit(ch);
464 } while (is_digit(ch));
473 #ifdef HAVE_LONG_LONG
477 #endif /* HAVE_LONG_LONG */
479 *(cp = buf) = va_arg(ap, int);
488 #ifdef HAVE_LONG_LONG
489 if (flags & QUADINT) {
490 uqval = va_arg(ap, long long);
491 if ((long long)uqval < 0) {
497 #endif /* HAVE_LONG_LONG */
500 if ((long)ulval < 0) {
508 #ifdef HAVE_LONG_LONG
510 *va_arg(ap, long long *) = ret;
512 #endif /* HAVE_LONG_LONG */
514 *va_arg(ap, long *) = ret;
515 else if (flags & SHORTINT)
516 *va_arg(ap, short *) = ret;
518 *va_arg(ap, int *) = ret;
519 continue; /* no output */
524 #ifdef HAVE_LONG_LONG
526 uqval = va_arg(ap, unsigned long long);
528 #endif /* HAVE_LONG_LONG */
534 * ``The argument shall be a pointer to void. The
535 * value of the pointer is converted to a sequence
536 * of printable characters, in an implementation-
540 ulval = (unsigned long)va_arg(ap, VOID *);
542 xdigs = "0123456789abcdef";
543 flags = (flags & ~QUADINT) | HEXPREFIX;
547 if ((cp = va_arg(ap, char *)) == NULL)
551 * can't use strlen; can only look for the
552 * NUL in the first `prec' characters, and
553 * strlen() will go further.
555 char *p = memchr(cp, 0, prec);
571 #ifdef HAVE_LONG_LONG
573 uqval = va_arg(ap, unsigned long long);
575 #endif /* HAVE_LONG_LONG */
580 xdigs = "0123456789ABCDEF";
583 xdigs = "0123456789abcdef";
585 #ifdef HAVE_LONG_LONG
587 uqval = va_arg(ap, unsigned long long);
589 #endif /* HAVE_LONG_LONG */
592 /* leading 0x/X only if non-zero */
594 #ifdef HAVE_LONG_LONG
595 (flags & QUADINT ? uqval != 0 : ulval != 0))
598 #endif /* HAVE_LONG_LONG */
601 /* unsigned conversions */
604 * ``... diouXx conversions ... if a precision is
605 * specified, the 0 flag will be ignored.''
608 number: if ((dprec = prec) >= 0)
612 * ``The result of converting a zero value with an
613 * explicit precision of zero is no characters.''
617 #ifdef HAVE_LONG_LONG
618 if (flags & QUADINT) {
619 if (uqval != 0 || prec != 0)
620 cp = __uqtoa(uqval, cp, base,
624 #endif /* HAVE_LONG_LONG */
626 if (ulval != 0 || prec != 0)
627 cp = __ultoa(ulval, cp, base,
630 size = buf + BUF - cp;
632 default: /* "%?" prints ?, unless ? is NUL */
635 /* pretend it was %c with argument ch */
644 * All reasonable formats wind up here. At this point, `cp'
645 * points to a string which (if not flags&LADJUST) should be
646 * padded out to `width' places. If flags&ZEROPAD, it should
647 * first be prefixed by any sign or other prefix; otherwise,
648 * it should be blank padded before the prefix is emitted.
649 * After any left-hand padding and prefixing, emit zeroes
650 * required by a decimal [diouxX] precision, then print the
651 * string proper, then emit zeroes required by any leftover
652 * floating precision; finally, if LADJUST, pad with blanks.
654 * Compute actual size, so we know how much to pad.
655 * fieldsz excludes decimal prec; realsz includes it.
660 else if (flags & HEXPREFIX)
662 realsz = dprec > fieldsz ? dprec : fieldsz;
664 /* right-adjusting blank padding */
665 if ((flags & (LADJUST|ZEROPAD)) == 0)
666 PAD(width - realsz, blanks);
671 } else if (flags & HEXPREFIX) {
677 /* right-adjusting zero padding */
678 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
679 PAD(width - realsz, zeroes);
681 /* leading zeroes from decimal precision */
682 PAD(dprec - fieldsz, zeroes);
684 /* the string or number proper */
687 /* left-adjusting padding (always blank) */
689 PAD(width - realsz, blanks);
691 /* finally, adjust ret */
692 ret += width > realsz ? width : realsz;
701 #ifndef HAVE_VSNPRINTF
703 vsnprintf(str, n, fmt, ap)
710 return (xxxprintf(&str, n, 0, fmt, ap));
712 #endif /* HAVE_VSNPRINTF */
714 #ifndef HAVE_SNPRINTF
717 snprintf(char *str, size_t n, char const *fmt, ...)
719 snprintf(str, n, fmt, va_alist)
734 ret = xxxprintf(&str, n, 0, fmt, ap);
738 #endif /* HAVE_SNPRINTF */
740 #ifndef HAVE_VASPRINTF
742 vasprintf(str, fmt, ap)
748 return (xxxprintf(str, 0, 1, fmt, ap));
750 #endif /* HAVE_VASPRINTF */
752 #ifndef HAVE_ASPRINTF
755 asprintf(char **str, char const *fmt, ...)
757 asprintf(str, fmt, va_alist)
771 ret = xxxprintf(str, 0, 1, fmt, ap);
775 #endif /* HAVE_ASPRINTF */