1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * This code is based on, and used with the permission of, the
19 * SIO stdio-replacement strx_* functions by Panos Tsirigotis
20 * <panos@alumni.cs.colorado.edu> for xinetd.
26 #include <sys/types.h>
31 #include <netinet/in.h>
43 #define API_EXPORT(type) type
44 #define API_EXPORT_NONSTD(type) type
46 #define ap_isalnum(c) (isalnum(((unsigned char)(c))))
47 #define ap_isalpha(c) (isalpha(((unsigned char)(c))))
48 #define ap_iscntrl(c) (iscntrl(((unsigned char)(c))))
49 #define ap_isdigit(c) (isdigit(((unsigned char)(c))))
50 #define ap_isgraph(c) (isgraph(((unsigned char)(c))))
51 #define ap_islower(c) (islower(((unsigned char)(c))))
52 #define ap_isprint(c) (isprint(((unsigned char)(c))))
53 #define ap_ispunct(c) (ispunct(((unsigned char)(c))))
54 #define ap_isspace(c) (isspace(((unsigned char)(c))))
55 #define ap_isupper(c) (isupper(((unsigned char)(c))))
56 #define ap_isxdigit(c) (isxdigit(((unsigned char)(c))))
57 #define ap_tolower(c) (tolower(((unsigned char)(c))))
58 #define ap_toupper(c) (toupper(((unsigned char)(c))))
71 #ifndef AP_LONGEST_LONG
72 #define AP_LONGEST_LONG long
76 #define WIDEST_INT AP_LONGEST_LONG
78 typedef WIDE_INT wide_int;
79 typedef unsigned WIDE_INT u_wide_int;
80 typedef WIDEST_INT widest_int;
82 /* Although Tandem supports "long long" there is no unsigned variant. */
83 typedef unsigned long u_widest_int;
85 typedef unsigned WIDEST_INT u_widest_int;
89 #define S_NULL "(null)"
92 #define FLOAT_DIGITS 6
93 #define EXPONENT_LENGTH 10
96 * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
98 * XXX: this is a magic number; do not decrease it
100 #define NUM_BUF_SIZE 512
103 * cvt.c - IEEE floating point formatting routines for FreeBSD
104 * from GNU libc-4.6.27. Modified to be thread safe.
108 * ap_ecvt converts to decimal
109 * the number of digits is specified by ndigit
110 * decpt is set to the position of the decimal point
111 * sign is set to 0 for positive, 1 for negative
116 /* buf must have at least NDIG bytes */
117 static char *ap_cvt(double arg, int ndigits, int *decpt, int *sign, int eflag, char *buf)
121 register char *p, *p1;
123 if (ndigits >= NDIG - 1)
132 arg = modf(arg, &fi);
139 while (p1 > &buf[0] && fi != 0) {
140 fj = modf(fi / 10, &fi);
141 *--p1 = (int) ((fj + .03) * 10) + '0';
144 while (p1 < &buf[NDIG])
148 while ((fj = arg * 10) < 1) {
161 while (p <= p1 && p < &buf[NDIG]) {
163 arg = modf(arg, &fj);
164 *p++ = (int) fj + '0';
166 if (p1 >= &buf[NDIG]) {
167 buf[NDIG - 1] = '\0';
190 static char *ap_ecvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
192 return (ap_cvt(arg, ndigits, decpt, sign, 1, buf));
195 static char *ap_fcvt(double arg, int ndigits, int *decpt, int *sign, char *buf)
197 return (ap_cvt(arg, ndigits, decpt, sign, 0, buf));
201 * ap_gcvt - Floating output conversion to
202 * minimal length string
205 static char *ap_gcvt(double number, int ndigit, char *buf, boolean_e altform)
208 register char *p1, *p2;
212 p1 = ap_ecvt(number, ndigit, &decpt, &sign, buf1);
216 for (i = ndigit - 1; i > 0 && p1[i] == '0'; i--)
218 if ((decpt >= 0 && decpt - ndigit > 4)
219 || (decpt < 0 && decpt < -3)) { /* use E-style */
223 for (i = 1; i < ndigit; i++)
233 *p2++ = decpt / 100 + '0';
235 *p2++ = (decpt % 100) / 10 + '0';
236 *p2++ = decpt % 10 + '0';
247 for (i = 1; i <= ndigit; i++) {
252 if (ndigit < decpt) {
253 while (ndigit++ < decpt)
258 if (p2[-1] == '.' && !altform)
265 * The INS_CHAR macro inserts a character in the buffer and writes
266 * the buffer back to disk if necessary
267 * It uses the char pointers sp and bep:
268 * sp points to the next available character in the buffer
269 * bep points to the end-of-buffer+1
270 * While using this macro, note that the nextb pointer is NOT updated.
272 * NOTE: Evaluation of the c argument should not have any side-effects
274 #define INS_CHAR(c, sp, bep, cc) \
277 vbuff->curpos = sp; \
278 if (flush_func(vbuff)) \
280 sp = vbuff->curpos; \
281 bep = vbuff->endpos; \
287 #define NUM( c ) ( c - '0' )
289 #define STR_TO_DEC( str, num ) \
290 num = NUM( *str++ ) ; \
291 while ( ap_isdigit( *str ) ) \
294 num += NUM( *str++ ) ; \
298 * This macro does zero padding so that the precision
299 * requirement is satisfied. The padding is done by
300 * adding '0's to the left of the string that is going
301 * to be printed. We don't allow precision to be large
302 * enough that we continue past the start of s.
304 * NOTE: this makes use of the magic info that s is
305 * always based on num_buf with a size of NUM_BUF_SIZE.
307 #define FIX_PRECISION( adjust, precision, s, s_len ) \
309 int p = precision < NUM_BUF_SIZE - 1 ? precision : NUM_BUF_SIZE - 1; \
310 while ( s_len < p ) \
318 * Macro that does padding. The padding is done by printing
321 #define PAD( width, len, ch ) do \
323 INS_CHAR( ch, sp, bep, cc ) ; \
326 while ( width > len )
329 * Prefix the character ch to the string str
331 * Set the has_prefix flag
333 #define PREFIX( str, length, ch ) *--str = ch ; length++ ; has_prefix = YES
337 * Convert num to its decimal format.
339 * - a pointer to a string containing the number (no sign)
340 * - len contains the length of the string
341 * - is_negative is set to TRUE or FALSE depending on the sign
342 * of the number (always set to FALSE if is_unsigned is TRUE)
344 * The caller provides a buffer for the string: that is the buf_end argument
345 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
346 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
348 * Note: we have 2 versions. One is used when we need to use quads
349 * (conv_10_quad), the other when we don't (conv_10). We're assuming the
352 static char *conv_10(register wide_int num, register bool_int is_unsigned,
353 register bool_int *is_negative, char *buf_end,
356 register char *p = buf_end;
357 register u_wide_int magnitude;
360 magnitude = (u_wide_int) num;
361 *is_negative = FALSE;
364 *is_negative = (num < 0);
367 * On a 2's complement machine, negating the most negative integer
368 * results in a number that cannot be represented as a signed integer.
369 * Here is what we do to obtain the number's magnitude:
370 * a. add 1 to the number
371 * b. negate it (becomes positive)
372 * c. convert it to unsigned
376 wide_int t = num + 1;
378 magnitude = ((u_wide_int) -t) + 1;
381 magnitude = (u_wide_int) num;
385 * We use a do-while loop so that we write at least 1 digit
388 register u_wide_int new_magnitude = magnitude / 10;
390 *--p = (char) (magnitude - new_magnitude * 10 + '0');
391 magnitude = new_magnitude;
399 static char *conv_10_quad(widest_int num, register bool_int is_unsigned,
400 register bool_int *is_negative, char *buf_end,
403 register char *p = buf_end;
404 u_widest_int magnitude;
407 * We see if we can use the faster non-quad version by checking the
408 * number against the largest long value it can be. If <=, we
409 * punt to the quicker version.
411 if ((num <= ULONG_MAX && is_unsigned) || (num <= LONG_MAX && !is_unsigned))
412 return(conv_10( (wide_int)num, is_unsigned, is_negative,
416 magnitude = (u_widest_int) num;
417 *is_negative = FALSE;
420 *is_negative = (num < 0);
423 * On a 2's complement machine, negating the most negative integer
424 * results in a number that cannot be represented as a signed integer.
425 * Here is what we do to obtain the number's magnitude:
426 * a. add 1 to the number
427 * b. negate it (becomes positive)
428 * c. convert it to unsigned
432 widest_int t = num + 1;
434 magnitude = ((u_widest_int) -t) + 1;
437 magnitude = (u_widest_int) num;
441 * We use a do-while loop so that we write at least 1 digit
444 u_widest_int new_magnitude = magnitude / 10;
446 *--p = (char) (magnitude - new_magnitude * 10 + '0');
447 magnitude = new_magnitude;
457 static char *conv_in_addr(struct in_addr *ia, char *buf_end, int *len)
459 unsigned addr = ntohl(ia->s_addr);
461 bool_int is_negative;
464 p = conv_10((addr & 0x000000FF) , TRUE, &is_negative, p, &sub_len);
466 p = conv_10((addr & 0x0000FF00) >> 8, TRUE, &is_negative, p, &sub_len);
468 p = conv_10((addr & 0x00FF0000) >> 16, TRUE, &is_negative, p, &sub_len);
470 p = conv_10((addr & 0xFF000000) >> 24, TRUE, &is_negative, p, &sub_len);
478 static char *conv_sockaddr_in(struct sockaddr_in *si, char *buf_end, int *len)
481 bool_int is_negative;
484 p = conv_10(ntohs(si->sin_port), TRUE, &is_negative, p, &sub_len);
486 p = conv_in_addr(&si->sin_addr, p, &sub_len);
495 * Convert a floating point number to a string formats 'f', 'e' or 'E'.
496 * The result is placed in buf, and len denotes the length of the string
497 * The sign is returned in the is_negative argument (and is not placed
500 static char *conv_fp(register char format, register double num,
501 boolean_e add_dp, int precision, bool_int *is_negative,
504 register char *s = buf;
510 p = ap_fcvt(num, precision, &decimal_point, is_negative, buf1);
511 else /* either e or E format */
512 p = ap_ecvt(num, precision + 1, &decimal_point, is_negative, buf1);
515 * Check for Infinity and NaN
517 if (ap_isalpha(*p)) {
518 *len = strlen(strcpy(buf, p));
519 *is_negative = FALSE;
524 if (decimal_point <= 0) {
528 while (decimal_point++ < 0)
535 while (decimal_point-- > 0)
537 if (precision > 0 || add_dp)
543 if (precision > 0 || add_dp)
548 * copy the rest of p, the NUL is NOT copied
554 char temp[EXPONENT_LENGTH]; /* for exponent conversion */
556 bool_int exponent_is_negative;
558 *s++ = format; /* either e or E */
560 if (decimal_point != 0) {
561 p = conv_10((wide_int) decimal_point, FALSE, &exponent_is_negative,
562 &temp[EXPONENT_LENGTH], &t_len);
563 *s++ = exponent_is_negative ? '-' : '+';
566 * Make sure the exponent has at least 2 digits
586 * Convert num to a base X number where X is a power of 2. nbits determines X.
587 * For example, if nbits is 3, we do base 8 conversion
589 * a pointer to a string containing the number
591 * The caller provides a buffer for the string: that is the buf_end argument
592 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
593 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
595 * As with conv_10, we have a faster version which is used when
596 * the number isn't quad size.
598 static char *conv_p2(register u_wide_int num, register int nbits,
599 char format, char *buf_end, register int *len)
601 register int mask = (1 << nbits) - 1;
602 register char *p = buf_end;
603 static const char low_digits[] = "0123456789abcdef";
604 static const char upper_digits[] = "0123456789ABCDEF";
605 register const char *digits = (format == 'X') ? upper_digits : low_digits;
608 *--p = digits[num & mask];
617 static char *conv_p2_quad(u_widest_int num, register int nbits,
618 char format, char *buf_end, register int *len)
620 register int mask = (1 << nbits) - 1;
621 register char *p = buf_end;
622 static const char low_digits[] = "0123456789abcdef";
623 static const char upper_digits[] = "0123456789ABCDEF";
624 register const char *digits = (format == 'X') ? upper_digits : low_digits;
626 if (num <= ULONG_MAX)
627 return(conv_p2( (u_wide_int)num, nbits, format, buf_end, len));
630 *--p = digits[num & mask];
641 * Do format conversion placing the output in buffer
643 API_EXPORT(int) ap_vformatter(int (*flush_func)(ap_vformatter_buff *),
644 ap_vformatter_buff *vbuff, const char *fmt, va_list ap)
651 register char *s = NULL;
655 register int min_width = 0;
664 widest_int i_quad = (widest_int) 0;
665 u_widest_int ui_quad;
666 wide_int i_num = (wide_int) 0;
669 char num_buf[NUM_BUF_SIZE];
670 char char_buf[2]; /* for printing %% and %<unknown> */
673 IS_QUAD, IS_LONG, IS_SHORT, IS_INT
675 enum var_type_enum var_type = IS_INT;
680 boolean_e alternate_form;
681 boolean_e print_sign;
682 boolean_e print_blank;
683 boolean_e adjust_precision;
684 boolean_e adjust_width;
685 bool_int is_negative;
692 INS_CHAR(*fmt, sp, bep, cc);
696 * Default variable settings
699 alternate_form = print_sign = print_blank = NO;
706 * Try to avoid checking for flags, width or precision
708 if (!ap_islower(*fmt)) {
710 * Recognize flags: -, #, BLANK, +
715 else if (*fmt == '+')
717 else if (*fmt == '#')
718 alternate_form = YES;
719 else if (*fmt == ' ')
721 else if (*fmt == '0')
728 * Check if a width was specified
730 if (ap_isdigit(*fmt)) {
731 STR_TO_DEC(fmt, min_width);
734 else if (*fmt == '*') {
735 min_width = va_arg(ap, int);
740 min_width = -min_width;
747 * Check if a precision was specified
750 adjust_precision = YES;
752 if (ap_isdigit(*fmt)) {
753 STR_TO_DEC(fmt, precision);
755 else if (*fmt == '*') {
756 precision = va_arg(ap, int);
765 adjust_precision = NO;
768 adjust_precision = adjust_width = NO;
777 else if (*fmt == 'l') {
781 else if (*fmt == 'h') {
790 * Argument extraction and printing.
791 * First we determine the argument type.
792 * Then, we convert the argument to a string.
793 * On exit from the switch, s points to the string that
794 * must be printed, s_len has the length of the string
795 * The precision requirements, if any, are reflected in s_len.
797 * NOTE: pad_char may be set to '0' because of the 0 flag.
798 * It is reset to ' ' by non-numeric formats
802 if (var_type == IS_QUAD) {
803 i_quad = va_arg(ap, u_widest_int);
804 s = conv_10_quad(i_quad, 1, &is_negative,
805 &num_buf[NUM_BUF_SIZE], &s_len);
808 if (var_type == IS_LONG)
809 i_num = (wide_int) va_arg(ap, u_wide_int);
810 else if (var_type == IS_SHORT)
811 i_num = (wide_int) (unsigned short) va_arg(ap, unsigned int);
813 i_num = (wide_int) va_arg(ap, unsigned int);
814 s = conv_10(i_num, 1, &is_negative,
815 &num_buf[NUM_BUF_SIZE], &s_len);
817 FIX_PRECISION(adjust_precision, precision, s, s_len);
822 if (var_type == IS_QUAD) {
823 i_quad = va_arg(ap, widest_int);
824 s = conv_10_quad(i_quad, 0, &is_negative,
825 &num_buf[NUM_BUF_SIZE], &s_len);
828 if (var_type == IS_LONG)
829 i_num = (wide_int) va_arg(ap, wide_int);
830 else if (var_type == IS_SHORT)
831 i_num = (wide_int) (short) va_arg(ap, int);
833 i_num = (wide_int) va_arg(ap, int);
834 s = conv_10(i_num, 0, &is_negative,
835 &num_buf[NUM_BUF_SIZE], &s_len);
837 FIX_PRECISION(adjust_precision, precision, s, s_len);
843 else if (print_blank)
849 if (var_type == IS_QUAD) {
850 ui_quad = va_arg(ap, u_widest_int);
851 s = conv_p2_quad(ui_quad, 3, *fmt,
852 &num_buf[NUM_BUF_SIZE], &s_len);
855 if (var_type == IS_LONG)
856 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
857 else if (var_type == IS_SHORT)
858 ui_num = (u_wide_int) (unsigned short) va_arg(ap, unsigned int);
860 ui_num = (u_wide_int) va_arg(ap, unsigned int);
861 s = conv_p2(ui_num, 3, *fmt,
862 &num_buf[NUM_BUF_SIZE], &s_len);
864 FIX_PRECISION(adjust_precision, precision, s, s_len);
865 if (alternate_form && *s != '0') {
874 if (var_type == IS_QUAD) {
875 ui_quad = va_arg(ap, u_widest_int);
876 s = conv_p2_quad(ui_quad, 4, *fmt,
877 &num_buf[NUM_BUF_SIZE], &s_len);
880 if (var_type == IS_LONG)
881 ui_num = (u_wide_int) va_arg(ap, u_wide_int);
882 else if (var_type == IS_SHORT)
883 ui_num = (u_wide_int) (unsigned short) va_arg(ap, unsigned int);
885 ui_num = (u_wide_int) va_arg(ap, unsigned int);
886 s = conv_p2(ui_num, 4, *fmt,
887 &num_buf[NUM_BUF_SIZE], &s_len);
889 FIX_PRECISION(adjust_precision, precision, s, s_len);
890 if (alternate_form && i_num != 0) {
891 *--s = *fmt; /* 'x' or 'X' */
899 s = va_arg(ap, char *);
902 if (adjust_precision && precision < s_len)
916 fp_num = va_arg(ap, double);
918 * * We use &num_buf[ 1 ], so that we have room for the sign
935 s = conv_fp(*fmt, fp_num, alternate_form,
936 (adjust_precision == NO) ? FLOAT_DIGITS : precision,
937 &is_negative, &num_buf[1], &s_len);
942 else if (print_blank)
950 if (adjust_precision == NO)
951 precision = FLOAT_DIGITS;
952 else if (precision == 0)
955 * * We use &num_buf[ 1 ], so that we have room for the sign
957 s = ap_gcvt(va_arg(ap, double), precision, &num_buf[1],
963 else if (print_blank)
968 if (alternate_form && (q = strchr(s, '.')) == NULL) {
970 s[s_len] = '\0'; /* delimit for following strchr() */
972 if (*fmt == 'G' && (q = strchr(s, 'e')) != NULL)
978 char_buf[0] = (char) (va_arg(ap, int));
994 if (var_type == IS_QUAD)
995 *(va_arg(ap, widest_int *)) = cc;
996 else if (var_type == IS_LONG)
997 *(va_arg(ap, long *)) = cc;
998 else if (var_type == IS_SHORT)
999 *(va_arg(ap, short *)) = cc;
1001 *(va_arg(ap, int *)) = cc;
1005 * This is where we extend the printf format, with a second
1011 * If the pointer size is equal to or smaller than the size
1012 * of the largest unsigned int, we convert the pointer to a
1013 * hex number, otherwise we print "%p" to indicate that we
1014 * don't handle "%p".
1017 #ifdef AP_VOID_P_IS_QUAD
1018 if (sizeof(void *) <= sizeof(u_widest_int)) {
1019 ui_quad = (u_widest_int) va_arg(ap, void *);
1020 s = conv_p2_quad(ui_quad, 4, 'x',
1021 &num_buf[NUM_BUF_SIZE], &s_len);
1024 if (sizeof(void *) <= sizeof(u_wide_int)) {
1025 ui_num = (u_wide_int) va_arg(ap, void *);
1026 s = conv_p2(ui_num, 4, 'x',
1027 &num_buf[NUM_BUF_SIZE], &s_len);
1038 /* print a struct sockaddr_in as a.b.c.d:port */
1041 struct sockaddr_in *si;
1043 si = va_arg(ap, struct sockaddr_in *);
1045 s = conv_sockaddr_in(si, &num_buf[NUM_BUF_SIZE], &s_len);
1046 if (adjust_precision && precision < s_len)
1057 /* print a struct in_addr as a.b.c.d */
1062 ia = va_arg(ap, struct in_addr *);
1064 s = conv_in_addr(ia, &num_buf[NUM_BUF_SIZE], &s_len);
1065 if (adjust_precision && precision < s_len)
1077 /* if %p ends the string, oh well ignore it */
1090 * The last character of the format string was %.
1097 * The default case is for unrecognized %'s.
1098 * We print %<char> to help the user identify what
1099 * option is not understood.
1100 * This is also useful in case the user wants to pass
1101 * the output of format_converter to another function
1102 * that understands some other %<char> (like syslog).
1103 * Note that we can't point s inside fmt because the
1104 * unknown <char> could be preceded by width etc.
1115 if (prefix_char != NUL && s != S_NULL && s != char_buf) {
1120 if (adjust_width && adjust == RIGHT && min_width > s_len) {
1121 if (pad_char == '0' && prefix_char != NUL) {
1122 INS_CHAR(*s, sp, bep, cc);
1127 PAD(min_width, s_len, pad_char);
1131 * Print the string s.
1133 for (i = s_len; i != 0; i--) {
1134 INS_CHAR(*s, sp, bep, cc);
1138 if (adjust_width && adjust == LEFT && min_width > s_len)
1139 PAD(min_width, s_len, pad_char);
1149 static int snprintf_flush(ap_vformatter_buff *vbuff)
1151 /* if the buffer fills we have to abort immediately, there is no way
1152 * to "flush" an ap_snprintf... there's nowhere to flush it to.
1158 API_EXPORT_NONSTD(int) ap_snprintf(char *buf, size_t len, const char *format,...)
1162 ap_vformatter_buff vbuff;
1167 /* save one byte for nul terminator */
1169 vbuff.endpos = buf + len - 1;
1170 va_start(ap, format);
1171 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1173 *vbuff.curpos = '\0';
1174 return (cc == -1) ? len : cc;
1178 API_EXPORT(int) ap_vsnprintf(char *buf, size_t len, const char *format,
1182 ap_vformatter_buff vbuff;
1187 /* save one byte for nul terminator */
1189 vbuff.endpos = buf + len - 1;
1190 cc = ap_vformatter(snprintf_flush, &vbuff, format, ap);
1191 *vbuff.curpos = '\0';
1192 return (cc == -1) ? len : cc;