2 * Copyright (c) 2000-2001, 2004 Sendmail, Inc. and its suppliers.
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * By using this file, you agree to the terms and conditions set
11 * forth in the LICENSE file which can be found at the top level of
12 * the sendmail distribution.
16 SM_IDSTR(id, "@(#)$Id: vfprintf.c,v 1.54 2005/05/16 03:52:00 ca Exp $")
20 ** Actual printing innards.
21 ** This code is large and complicated...
24 #include <sys/types.h>
28 #include <sm/config.h>
29 #include <sm/varargs.h>
36 static int sm_bprintf __P((SM_FILE_T *, const char *, va_list));
37 static void sm_find_arguments __P((const char *, va_list , va_list **));
38 static void sm_grow_type_table_x __P((unsigned char **, int *));
39 static int sm_print __P((SM_FILE_T *, int, struct sm_uio *));
42 ** SM_PRINT -- print/flush to the file
44 ** Flush out all the vectors defined by the given uio,
45 ** then reset it so that it can be reused.
49 ** timeout -- time to complete operation (milliseconds)
50 ** uio -- vector list of memory locations of data for printing
58 sm_print(fp, timeout, uio)
61 register struct sm_uio *uio;
65 if (uio->uio_resid == 0)
70 err = sm_fvwrite(fp, timeout, uio);
77 ** SM_BPRINTF -- allow formating to an unbuffered file.
79 ** Helper function for `fprintf to unbuffered unix file': creates a
80 ** temporary buffer (via a "fake" file pointer).
81 ** We only work on write-only files; this avoids
82 ** worries about ungetc buffers and so forth.
85 ** fp -- the file to send the o/p to
86 ** fmt -- format instructions for the o/p
87 ** ap -- vectors of data units used for formating
90 ** Failure: SM_IO_EOF and errno set
91 ** Success: number of data units used in the formating
94 ** formatted o/p can be SM_IO_BUFSIZ length maximum
98 sm_bprintf(fp, fmt, ap)
105 unsigned char buf[SM_IO_BUFSIZ];
106 extern const char SmFileMagic[];
108 /* copy the important variables */
109 fake.sm_magic = SmFileMagic;
110 fake.f_timeout = SM_TIME_FOREVER;
111 fake.f_timeoutstate = SM_TIME_BLOCK;
112 fake.f_flags = fp->f_flags & ~SMNBF;
113 fake.f_file = fp->f_file;
114 fake.f_cookie = fp->f_cookie;
115 fake.f_write = fp->f_write;
120 fake.f_setinfo = fake.f_getinfo = NULL;
121 fake.f_type = "sm_bprintf:fake";
123 /* set up the buffer */
124 fake.f_bf.smb_base = fake.f_p = buf;
125 fake.f_bf.smb_size = fake.f_w = sizeof(buf);
126 fake.f_lbfsize = 0; /* not actually used, but Just In Case */
128 /* do the work, then copy any error status */
129 ret = sm_io_vfprintf(&fake, SM_TIME_FOREVER, fmt, ap);
130 if (ret >= 0 && sm_io_flush(&fake, SM_TIME_FOREVER))
131 ret = SM_IO_EOF; /* errno set by sm_io_flush */
132 if (fake.f_flags & SMERR)
133 fp->f_flags |= SMERR;
140 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
143 /* Macros for converting digits to letters and vice versa */
144 #define to_digit(c) ((c) - '0')
145 #define is_digit(c) ((unsigned) to_digit(c) <= 9)
146 #define to_char(n) ((char) (n) + '0')
148 /* Flags used during conversion. */
149 #define ALT 0x001 /* alternate form */
150 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
151 #define LADJUST 0x004 /* left adjustment */
152 #define LONGINT 0x010 /* long integer */
153 #define QUADINT 0x020 /* quad integer */
154 #define SHORTINT 0x040 /* short integer */
155 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
156 #define FPT 0x100 /* Floating point number */
159 ** SM_IO_VPRINTF -- performs actual formating for o/p
162 ** fp -- file pointer for o/p
163 ** timeout -- time to complete the print
164 ** fmt0 -- formating directives
165 ** ap -- vectors with data units for formating
168 ** Success: number of data units used for formatting
169 ** Failure: SM_IO_EOF and sets errno
173 sm_io_vfprintf(fp, timeout, fmt0, ap)
179 register char *fmt; /* format string */
180 register int ch; /* character from fmt */
181 register int n, m, n2; /* handy integers (short term usage) */
182 register char *cp; /* handy char pointer (short term usage) */
183 register struct sm_iov *iovp;/* for PRINT macro */
184 register int flags; /* flags as above */
185 int ret; /* return value accumulator */
186 int width; /* width from format (%8d), or 0 */
187 int prec; /* precision from format (%.3d), or -1 */
188 char sign; /* sign prefix (' ', '+', '-', or \0) */
190 ULONGLONG_T _uquad; /* integer arguments %[diouxX] */
191 enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
192 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
193 int realsz; /* field size expanded by dprec */
194 int size; /* size of converted field or string */
195 char *xdigs="0123456789abcdef"; /* digits for [xX] conversion */
197 struct sm_uio uio; /* output information: summary */
198 struct sm_iov iov[NIOV];/* ... and individual io vectors */
199 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
200 char ox[2]; /* space for 0x hex-prefix */
201 va_list *argtable; /* args, built due to positional arg */
202 va_list statargtable[STATIC_ARG_TBL_SIZE];
203 int nextarg; /* 1-based argument index */
204 va_list orgap; /* original argument pointer */
207 ** Choose PADSIZE to trade efficiency vs. size. If larger printf
208 ** fields occur frequently, increase PADSIZE and make the initialisers
211 #define PADSIZE 16 /* pad chunk size */
212 static char blanks[PADSIZE] =
213 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
214 static char zeroes[PADSIZE] =
215 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
218 ** BEWARE, these `goto error' on error, and PAD uses `n'.
220 #define PRINT(ptr, len) do { \
221 iovp->iov_base = (ptr); \
222 iovp->iov_len = (len); \
223 uio.uio_resid += (len); \
225 if (++uio.uio_iovcnt >= NIOV) \
227 if (sm_print(fp, timeout, &uio)) \
232 #define PAD(howmany, with) do \
234 if ((n = (howmany)) > 0) \
236 while (n > PADSIZE) { \
237 PRINT(with, PADSIZE); \
245 if (uio.uio_resid && sm_print(fp, timeout, &uio)) \
247 uio.uio_iovcnt = 0; \
252 ** To extend shorts properly, we need both signed and unsigned
253 ** argument extraction methods.
256 (flags&QUADINT ? SM_VA_ARG(ap, LONGLONG_T) : \
257 flags&LONGINT ? GETARG(long) : \
258 flags&SHORTINT ? (long) (short) GETARG(int) : \
261 (flags&QUADINT ? SM_VA_ARG(ap, ULONGLONG_T) : \
262 flags&LONGINT ? GETARG(unsigned long) : \
263 flags&SHORTINT ? (unsigned long) (unsigned short) GETARG(int) : \
264 (unsigned long) GETARG(unsigned int))
267 ** Get * arguments, including the form *nn$. Preserve the nextarg
268 ** that the argument can be gotten once the type is determined.
270 #define GETASTER(val) \
273 while (is_digit(*cp)) \
275 n2 = 10 * n2 + to_digit(*cp); \
280 int hold = nextarg; \
281 if (argtable == NULL) \
283 argtable = statargtable; \
284 sm_find_arguments(fmt0, orgap, &argtable); \
297 ** Get the argument indexed by nextarg. If the argument table is
298 ** built, use it to get the argument. If its not, get the next
299 ** argument (and arguments must be gotten sequentially).
303 # define GETARG(type) \
304 (((argtable != NULL) ? (void) (ap = argtable[nextarg]) : (void) 0), \
305 nextarg++, SM_VA_ARG(ap, type))
306 #else /* SM_VA_STD */
307 # define GETARG(type) \
308 ((argtable != NULL) ? (*((type*)(argtable[nextarg++]))) : \
309 (nextarg++, SM_VA_ARG(ap, type)))
310 #endif /* SM_VA_STD */
312 /* sorry, fprintf(read_only_file, "") returns SM_IO_EOF, not 0 */
319 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
320 if ((fp->f_flags & (SMNBF|SMWR|SMRW)) == (SMNBF|SMWR) &&
322 return sm_bprintf(fp, fmt0, ap);
327 SM_VA_COPY(orgap, ap);
328 uio.uio_iov = iovp = iov;
333 /* Scan the format for conversions (`%' character). */
338 while ((wc = *fmt) != '\0')
347 if ((m = fmt - cp) != 0)
354 fmt++; /* skip over '%' */
363 reswitch: switch (ch)
368 ** ``If the space and + flags both appear, the space
369 ** flag will be ignored.''
382 ** ``A negative field width argument is taken as a
383 ** - flag followed by a positive field width.''
385 ** They don't exclude field widths read from args.
400 if ((ch = *fmt++) == '*')
403 prec = n < 0 ? -1 : n;
409 n = 10 * n + to_digit(ch);
415 if (argtable == NULL)
417 argtable = statargtable;
418 sm_find_arguments(fmt0, orgap,
423 prec = n < 0 ? -1 : n;
428 ** ``Note that 0 is taken as a flag, not as the
429 ** beginning of a field width.''
435 case '1': case '2': case '3': case '4':
436 case '5': case '6': case '7': case '8': case '9':
440 n = 10 * n + to_digit(ch);
442 } while (is_digit(ch));
446 if (argtable == NULL)
448 argtable = statargtable;
449 sm_find_arguments(fmt0, orgap,
474 *(cp = buf) = GETARG(int);
484 if ((LONGLONG_T) _uquad < 0)
486 _uquad = -(LONGLONG_T) _uquad;
504 ** This code implements floating point output
505 ** in the most portable manner possible,
506 ** relying only on 'sprintf' as defined by
507 ** the 1989 ANSI C standard.
508 ** We silently cap width and precision
509 ** at 120, to avoid buffer overflow.
512 val = GETARG(double);
539 snprintf(out, sizeof(out), fmt, width,
541 #else /* HASSNPRINTF */
542 sprintf(out, fmt, width, prec, val);
543 #endif /* HASSNPRINTF */
546 snprintf(out, sizeof(out), fmt, width,
548 #else /* HASSNPRINTF */
549 sprintf(out, fmt, width, val);
550 #endif /* HASSNPRINTF */
558 *GETARG(LONGLONG_T *) = ret;
559 else if (flags & LONGINT)
560 *GETARG(long *) = ret;
561 else if (flags & SHORTINT)
562 *GETARG(short *) = ret;
564 *GETARG(int *) = ret;
565 continue; /* no output */
576 ** ``The argument shall be a pointer to void. The
577 ** value of the pointer is converted to a sequence
578 ** of printable characters, in an implementation-
592 u.p = GETARG(void *);
593 if (sizeof(void *) == sizeof(ULONGLONG_T))
595 else if (sizeof(void *) == sizeof(long))
601 xdigs = "0123456789abcdef";
606 if ((cp = GETARG(char *)) == NULL)
611 ** can't use strlen; can only look for the
612 ** NUL in the first `prec' characters, and
613 ** strlen() will go further.
616 char *p = memchr(cp, 0, prec);
639 xdigs = "0123456789ABCDEF";
642 xdigs = "0123456789abcdef";
643 hex: _uquad = UARG();
645 /* leading 0x/X only if non-zero */
646 if (flags & ALT && _uquad != 0)
649 /* unsigned conversions */
653 ** ``... diouXx conversions ... if a precision is
654 ** specified, the 0 flag will be ignored.''
658 number: if ((dprec = prec) >= 0)
662 ** ``The result of converting a zero value with an
663 ** explicit precision of zero is no characters.''
668 if (_uquad != 0 || prec != 0)
671 ** Unsigned mod is hard, and unsigned mod
672 ** by a constant is easier than that by
673 ** a variable; hence this switch.
681 *--cp = to_char(_uquad & 7);
684 /* handle octal leading 0 */
685 if (flags & ALT && *cp != '0')
690 /* many numbers are 1 digit */
693 *--cp = to_char(_uquad % 10);
696 *--cp = to_char(_uquad);
702 *--cp = xdigs[_uquad & 15];
708 cp = "bug in sm_io_vfprintf: bad base";
713 size = buf + BUF - cp;
716 default: /* "%?" prints ?, unless ? is NUL */
719 /* pretend it was %c with argument ch */
728 ** All reasonable formats wind up here. At this point, `cp'
729 ** points to a string which (if not flags&LADJUST) should be
730 ** padded out to `width' places. If flags&ZEROPAD, it should
731 ** first be prefixed by any sign or other prefix; otherwise,
732 ** it should be blank padded before the prefix is emitted.
733 ** After any left-hand padding and prefixing, emit zeroes
734 ** required by a decimal [diouxX] precision, then print the
735 ** string proper, then emit zeroes required by any leftover
736 ** floating precision; finally, if LADJUST, pad with blanks.
738 ** Compute actual size, so we know how much to pad.
739 ** size excludes decimal prec; realsz includes it.
742 realsz = dprec > size ? dprec : size;
745 else if (flags & HEXPREFIX)
748 /* right-adjusting blank padding */
749 if ((flags & (LADJUST|ZEROPAD)) == 0)
750 PAD(width - realsz, blanks);
757 else if (flags & HEXPREFIX)
764 /* right-adjusting zero padding */
765 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
766 PAD(width - realsz, zeroes);
768 /* leading zeroes from decimal precision */
769 PAD(dprec - size, zeroes);
771 /* the string or number proper */
773 /* left-adjusting padding (always blank) */
775 PAD(width - realsz, blanks);
777 /* finally, adjust ret */
778 ret += width > realsz ? width : realsz;
780 FLUSH(); /* copy out the I/O vectors */
785 if ((argtable != NULL) && (argtable != statargtable))
787 return sm_error(fp) ? SM_IO_EOF : ret;
791 /* Type ids for argument type table. */
810 ** SM_FIND_ARGUMENTS -- find all args when a positional parameter is found.
812 ** Find all arguments when a positional parameter is encountered. Returns a
813 ** table, indexed by argument number, of pointers to each arguments. The
814 ** initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
815 ** It will be replaced with a malloc-ed one if it overflows.
818 ** fmt0 -- formating directives
819 ** ap -- vector list of data unit for formating consumption
820 ** argtable -- an indexable table (returned) of 'ap'
827 sm_find_arguments(fmt0, ap, argtable)
832 register char *fmt; /* format string */
833 register int ch; /* character from fmt */
834 register int n, n2; /* handy integer (short term usage) */
835 register char *cp; /* handy char pointer (short term usage) */
836 register int flags; /* flags as above */
837 unsigned char *typetable; /* table of types */
838 unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
839 int tablesize; /* current size of type table */
840 int tablemax; /* largest used index in table */
841 int nextarg; /* 1-based argument index */
843 /* Add an argument type to the table, expanding if necessary. */
844 #define ADDTYPE(type) \
845 ((nextarg >= tablesize) ? \
846 (sm_grow_type_table_x(&typetable, &tablesize), 0) : 0, \
847 typetable[nextarg++] = type, \
848 (nextarg > tablemax) ? tablemax = nextarg : 0)
851 ((flags & LONGINT) ? ADDTYPE(T_LONG) : \
852 ((flags & SHORTINT) ? ADDTYPE(T_SHORT) : ADDTYPE(T_INT)))
855 ((flags & LONGINT) ? ADDTYPE(T_U_LONG) : \
856 ((flags & SHORTINT) ? ADDTYPE(T_U_SHORT) : ADDTYPE(T_U_INT)))
858 /* Add * arguments to the type array. */
862 while (is_digit(*cp)) \
864 n2 = 10 * n2 + to_digit(*cp); \
869 int hold = nextarg; \
880 typetable = stattypetable;
881 tablesize = STATIC_ARG_TBL_SIZE;
884 (void) memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
886 /* Scan the format for conversions (`%' character). */
889 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
893 fmt++; /* skip over '%' */
898 reswitch: switch (ch)
910 if ((ch = *fmt++) == '*')
922 case '1': case '2': case '3': case '4':
923 case '5': case '6': case '7': case '8': case '9':
927 n = 10 * n + to_digit(ch);
929 } while (is_digit(ch));
972 else if (flags & LONGINT)
974 else if (flags & SHORTINT)
978 continue; /* no output */
1005 if (flags & QUADINT)
1010 default: /* "%?" prints ?, unless ? is NUL */
1017 /* Build the argument table. */
1018 if (tablemax >= STATIC_ARG_TBL_SIZE)
1020 *argtable = (va_list *)
1021 sm_malloc(sizeof(va_list) * (tablemax + 1));
1024 for (n = 1; n <= tablemax; n++)
1026 SM_VA_COPY((*argtable)[n], ap);
1027 switch (typetable [n])
1030 (void) SM_VA_ARG(ap, int);
1033 (void) SM_VA_ARG(ap, int);
1036 (void) SM_VA_ARG(ap, int);
1039 (void) SM_VA_ARG(ap, short *);
1042 (void) SM_VA_ARG(ap, int);
1045 (void) SM_VA_ARG(ap, unsigned int);
1048 (void) SM_VA_ARG(ap, int *);
1051 (void) SM_VA_ARG(ap, long);
1054 (void) SM_VA_ARG(ap, unsigned long);
1057 (void) SM_VA_ARG(ap, long *);
1060 (void) SM_VA_ARG(ap, LONGLONG_T);
1063 (void) SM_VA_ARG(ap, ULONGLONG_T);
1066 (void) SM_VA_ARG(ap, LONGLONG_T *);
1069 (void) SM_VA_ARG(ap, double);
1072 (void) SM_VA_ARG(ap, char *);
1075 (void) SM_VA_ARG(ap, void *);
1080 if ((typetable != NULL) && (typetable != stattypetable))
1085 ** SM_GROW_TYPE_TABLE -- Increase the size of the type table.
1088 ** tabletype -- type of table to grow
1089 ** tablesize -- requested new table size
1092 ** Raises an exception if can't allocate memory.
1096 sm_grow_type_table_x(typetable, tablesize)
1097 unsigned char **typetable;
1100 unsigned char *oldtable = *typetable;
1101 int newsize = *tablesize * 2;
1103 if (*tablesize == STATIC_ARG_TBL_SIZE)
1105 *typetable = (unsigned char *) sm_malloc_x(sizeof(unsigned char)
1107 (void) memmove(*typetable, oldtable, *tablesize);
1111 *typetable = (unsigned char *) sm_realloc_x(typetable,
1112 sizeof(unsigned char) * newsize);
1114 (void) memset(&typetable [*tablesize], T_UNUSED,
1115 (newsize - *tablesize));
1117 *tablesize = newsize;