2 +----------------------------------------------------------------------+
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
6 | Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) |
7 +----------------------------------------------------------------------+
8 | This source file is subject to version 2.00 of the Zend license, |
9 | that is bundled with this package in the file LICENSE, and is |
10 | available through the world-wide-web at the following url: |
11 | http://www.zend.com/license/2_00.txt. |
12 | If you did not receive a copy of the Zend license and are unable to |
13 | obtain it through the world-wide-web, please send a note to |
14 | license@zend.com so we can mail you a copy immediately. |
15 +----------------------------------------------------------------------+
18 #include "hphp/zend/zend-printf.h"
20 #include "hphp/util/exception.h"
21 #include "hphp/zend/zend-string.h"
22 #include "hphp/zend/zend-strtod.h"
33 /* These definitions are copied from the Zend formatted output conversion
34 files so that we only need to make minimal changes to the Zend formatted
35 output conversion functions that are incorporated here.
53 #define NUM(c) (c - '0')
55 #define STR_TO_DEC(str, num) do { \
57 while (isdigit((int)*str)) { \
60 if (num >= INT_MAX / 10) { \
61 while (isdigit((int)*str++)) \
69 * This macro does zero padding so that the precision
70 * requirement is satisfied. The padding is done by
71 * adding '0's to the left of the string that is going
74 #define FIX_PRECISION(adjust, precision, s, s_len) do { \
76 while (s_len < precision) { \
82 typedef int64_t wide_int
;
83 typedef uint64_t u_wide_int
;
88 #define INT_NULL ((int *)0)
90 static const char* s_null
= "(null)";
93 #define FLOAT_DIGITS 6
94 #define EXPONENT_LENGTH 10
96 #define HAVE_LOCALE_H 1
104 #define LCONV_DECIMAL_POINT (*lconv->decimal_point)
106 #define LCONV_DECIMAL_POINT '.'
109 ///////////////////////////////////////////////////////////////////////////////
111 * Copyright (c) 2002, 2006 Todd C. Miller <Todd.Miller@courtesan.com>
113 * Permission to use, copy, modify, and distribute this software for any
114 * purpose with or without fee is hereby granted, provided that the above
115 * copyright notice and this permission notice appear in all copies.
117 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
118 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
119 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
120 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
121 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
122 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
123 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
125 * Sponsored in part by the Defense Advanced Research Projects
126 * Agency (DARPA) and Air Force Research Laboratory, Air Force
127 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
130 static char * __cvt(double value
, int ndigit
, int *decpt
, int *sign
,
131 int fmode
, int pad
) {
132 register char *s
= nullptr;
142 /* __dtoa() doesn't allocate space for 0 so we do it by hand */
144 *decpt
= 1 - fmode
; /* 1 for 'e', 0 for 'f' */
146 if ((rve
= s
= (char *)malloc(ndigit
?siz
:2)) == nullptr) {
155 p
= zend_dtoa(value
, fmode
+ 2, ndigit
, decpt
, sign
, &rve
);
156 if (*decpt
== 9999) {
157 /* Infinity or Nan, convert to inf or nan like printf */
161 return strdup(c
== 'I' ? "INF" : "NAN");
163 /* Make a local copy and adjust rve to be in terms of s */
167 if ((s
= (char *)malloc(siz
+1)) == nullptr) {
171 (void)string_copy(s
, p
, siz
);
176 /* Add trailing zeros */
188 static inline char *php_ecvt(double value
, int ndigit
, int *decpt
, int *sign
) {
189 return(__cvt(value
, ndigit
, decpt
, sign
, 0, 1));
192 static inline char *php_fcvt(double value
, int ndigit
, int *decpt
, int *sign
) {
193 return(__cvt(value
, ndigit
, decpt
, sign
, 1, 1));
196 char *php_gcvt(double value
, int ndigit
, char dec_point
,
197 char exponent
, char *buf
) {
198 char *digits
, *dst
, *src
;
201 digits
= zend_dtoa(value
, 2, ndigit
, &decpt
, &sign
, nullptr);
204 * Infinity or NaN, convert to inf or nan with sign.
205 * We assume the buffer is at least ndigit long.
207 snprintf(buf
, ndigit
+ 1, "%s%s", (sign
&& *digits
== 'I') ? "-" : "",
208 *digits
== 'I' ? "INF" : "NAN");
209 zend_freedtoa(digits
);
218 if ((decpt
>= 0 && decpt
> ndigit
) || decpt
< -3) { /* use E-style */
219 /* exponential format (e.g. 1.2345e+13) */
234 } while (*src
!= '\0');
243 *dst
++ = '0' + decpt
;
247 for (sign
= decpt
, i
= 0; (sign
/= 10) != 0; i
++)
251 dst
[i
--] = '0' + decpt
% 10;
255 } else if (decpt
< 0) {
256 /* standard format 0. */
257 *dst
++ = '0'; /* zero before decimal point */
261 } while (++decpt
< 0);
263 while (*src
!= '\0') {
268 /* standard format */
269 for (i
= 0, src
= digits
; i
< decpt
; i
++) {
278 *dst
++ = '0'; /* zero before decimal point */
281 for (i
= decpt
; digits
[i
] != '\0'; i
++) {
287 zend_freedtoa(digits
);
291 ///////////////////////////////////////////////////////////////////////////////
294 /* ====================================================================
295 * Copyright (c) 1995-1998 The Apache Group. All rights reserved.
297 * Redistribution and use in source and binary forms, with or without
298 * modification, are permitted provided that the following conditions
301 * 1. Redistributions of source code must retain the above copyright
302 * notice, this list of conditions and the following disclaimer.
304 * 2. Redistributions in binary form must reproduce the above copyright
305 * notice, this list of conditions and the following disclaimer in
306 * the documentation and/or other materials provided with the
309 * 3. All advertising materials mentioning features or use of this
310 * software must display the following acknowledgment:
311 * "This product includes software developed by the Apache Group
312 * for use in the Apache HTTP server project (http://www.apache.org/)."
314 * 4. The names "Apache Server" and "Apache Group" must not be used to
315 * endorse or promote products derived from this software without
316 * prior written permission.
318 * 5. Redistributions of any form whatsoever must retain the following
320 * "This product includes software developed by the Apache Group
321 * for use in the Apache HTTP server project (http://www.apache.org/)."
323 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
324 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
325 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
326 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
327 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
328 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
329 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
330 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
331 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
332 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
333 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
334 * OF THE POSSIBILITY OF SUCH DAMAGE.
335 * ====================================================================
337 * This software consists of voluntary contributions made by many
338 * individuals on behalf of the Apache Group and was originally based
339 * on public domain software written at the National Center for
340 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
341 * For more information on the Apache Group and the Apache HTTP server
342 * project, please see <http://www.apache.org/>.
344 * This code is based on, and used with the permission of, the
345 * SIO stdio-replacement strx_* functions by Panos Tsirigotis
346 * <panos@alumni.cs.colorado.edu> for xinetd.
350 * Convert num to a base X number where X is a power of 2. nbits determines X.
351 * For example, if nbits is 3, we do base 8 conversion
353 * a pointer to a string containing the number
355 * The caller provides a buffer for the string: that is the buf_end argument
356 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
357 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
359 char * ap_php_conv_p2(register uint64_t num
, register int nbits
,
360 char format
, char *buf_end
, register int *len
)
362 register int mask
= (1 << nbits
) - 1;
363 register char *p
= buf_end
;
364 static char low_digits
[] = "0123456789abcdef";
365 static char upper_digits
[] = "0123456789ABCDEF";
366 register char *digits
= (format
== 'X') ? upper_digits
: low_digits
;
369 *--p
= digits
[num
& mask
];
379 * Convert num to its decimal format.
381 * - a pointer to a string containing the number (no sign)
382 * - len contains the length of the string
383 * - is_negative is set to TRUE or FALSE depending on the sign
384 * of the number (always set to FALSE if is_unsigned is TRUE)
386 * The caller provides a buffer for the string: that is the buf_end argument
387 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
388 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
390 char * ap_php_conv_10(register int64_t num
, register bool is_unsigned
,
391 register int * is_negative
, char *buf_end
,
393 register char *p
= buf_end
;
394 register uint64_t magnitude
;
397 magnitude
= (uint64_t) num
;
400 *is_negative
= (num
< 0);
403 * On a 2's complement machine, negating the most negative integer
404 * results in a number that cannot be represented as a signed integer.
405 * Here is what we do to obtain the number's magnitude:
406 * a. add 1 to the number
407 * b. negate it (becomes positive)
408 * c. convert it to unsigned
413 magnitude
= ((uint64_t) - t
) + 1;
415 magnitude
= (uint64_t) num
;
420 * We use a do-while loop so that we write at least 1 digit
423 register uint64_t new_magnitude
= magnitude
/ 10;
425 *--p
= (char)(magnitude
- new_magnitude
* 10 + '0');
426 magnitude
= new_magnitude
;
434 ///////////////////////////////////////////////////////////////////////////////
436 * Convert a floating point number to a string formats 'f', 'e' or 'E'.
437 * The result is placed in buf, and len denotes the length of the string
438 * The sign is returned in the is_negative argument (and is not placed
441 char * php_conv_fp(register char format
, register double num
,
442 bool add_dp
, int precision
, char dec_point
,
443 int *is_negative
, char *buf
, int *len
) {
444 register char *s
= buf
;
445 register char *p
, *p_orig
;
448 if (precision
>= NDIG
- 1) {
449 precision
= NDIG
- 2;
453 p_orig
= p
= php_fcvt(num
, precision
, &decimal_point
, is_negative
);
454 } else { // either e or E format
455 p_orig
= p
= php_ecvt(num
, precision
+ 1, &decimal_point
, is_negative
);
458 // Check for Infinity and NaN
459 if (isalpha((int)*p
)) {
461 memcpy(buf
, p
, *len
+ 1);
467 if (decimal_point
<= 0) {
468 if (num
!= 0 || precision
> 0) {
472 while (decimal_point
++ < 0) {
480 int addz
= decimal_point
>= NDIG
? decimal_point
- NDIG
+ 1 : 0;
481 decimal_point
-= addz
;
482 while (decimal_point
-- > 0) {
488 if (precision
> 0 || add_dp
) {
494 if (precision
> 0 || add_dp
) {
499 // copy the rest of p, the NUL is NOT copied
505 char temp
[EXPONENT_LENGTH
]; // for exponent conversion
507 int exponent_is_negative
;
509 *s
++ = format
; // either e or E
511 if (decimal_point
!= 0) {
512 p
= ap_php_conv_10((int64_t) decimal_point
, false,
513 &exponent_is_negative
, &temp
[EXPONENT_LENGTH
],
515 *s
++ = exponent_is_negative
? '-' : '+';
517 // Make sure the exponent has at least 2 digits
531 ///////////////////////////////////////////////////////////////////////////////
533 inline static void appendchar(char **buffer
, int *pos
, int *size
, char add
) {
534 if ((*pos
+ 1) >= *size
) {
536 *buffer
= (char*)realloc(*buffer
, *size
);
538 (*buffer
)[(*pos
)++] = add
;
541 inline static void appendsimplestring(char **buffer
, int *pos
, int *size
,
542 const char *add
, int len
) {
543 int req_size
= *pos
+ len
;
545 if (req_size
> *size
) {
546 while (req_size
> *size
) {
549 *buffer
= (char *)realloc(*buffer
, *size
);
551 memcpy(&(*buffer
)[*pos
], add
, len
);
556 * Do format conversion placing the output in buffer
558 static int xbuf_format_converter(char **outbuf
, const char *fmt
, va_list ap
)
560 register char *s
= nullptr;
564 register int min_width
= 0;
573 wide_int i_num
= (wide_int
) 0;
576 char num_buf
[NUM_BUF_SIZE
];
577 char char_buf
[2]; /* for printing %% and %<unknown> */
580 struct lconv
*lconv
= nullptr;
586 length_modifier_e modifier
;
587 boolean_e alternate_form
;
588 boolean_e print_sign
;
589 boolean_e print_blank
;
590 boolean_e adjust_precision
;
591 boolean_e adjust_width
;
595 char *result
= (char *)malloc(size
);
600 appendchar(&result
, &outpos
, &size
, *fmt
);
603 * Default variable settings
606 alternate_form
= print_sign
= print_blank
= NO
;
613 * Try to avoid checking for flags, width or precision
615 if (isascii((int)*fmt
) && !islower((int)*fmt
)) {
617 * Recognize flags: -, #, BLANK, +
622 else if (*fmt
== '+')
624 else if (*fmt
== '#')
625 alternate_form
= YES
;
626 else if (*fmt
== ' ')
628 else if (*fmt
== '0')
635 * Check if a width was specified
637 if (isdigit((int)*fmt
)) {
638 STR_TO_DEC(fmt
, min_width
);
640 } else if (*fmt
== '*') {
641 min_width
= va_arg(ap
, int);
646 min_width
= -min_width
;
652 * Check if a precision was specified
654 * XXX: an unreasonable amount of precision may be specified
655 * resulting in overflow of num_buf. Currently we
656 * ignore this possibility.
659 adjust_precision
= YES
;
661 if (isdigit((int)*fmt
)) {
662 STR_TO_DEC(fmt
, precision
);
663 } else if (*fmt
== '*') {
664 precision
= va_arg(ap
, int);
671 adjust_precision
= NO
;
673 adjust_precision
= adjust_width
= NO
;
681 modifier
= LM_LONG_DOUBLE
;
686 if (*fmt
== '6' && *(fmt
+1) == '4') {
688 modifier
= LM_LONG_LONG
;
691 if (*fmt
== '3' && *(fmt
+1) == '2') {
696 modifier
= LM_LONG_LONG
;
707 modifier
= LM_LONG_LONG
;
714 modifier
= LM_SIZE_T
;
719 modifier
= LM_INTMAX_T
;
721 modifier
= LM_SIZE_T
;
727 modifier
= LM_PTRDIFF_T
;
729 modifier
= LM_SIZE_T
;
737 /* these are promoted to int, so no break */
744 * Argument extraction and printing.
745 * First we determine the argument type.
746 * Then, we convert the argument to a string.
747 * On exit from the switch, s points to the string that
748 * must be printed, s_len has the length of the string
749 * The precision requirements, if any, are reflected in s_len.
751 * NOTE: pad_char may be set to '0' because of the 0 flag.
752 * It is reset to ' ' by non-numeric formats
758 i_num
= (wide_int
) va_arg(ap
, unsigned int);
763 i_num
= (wide_int
) va_arg(ap
, unsigned long int);
766 i_num
= (wide_int
) va_arg(ap
, size_t);
770 i_num
= (wide_int
) va_arg(ap
, u_wide_int
);
775 i_num
= (wide_int
) va_arg(ap
, uintmax_t);
780 i_num
= (wide_int
) va_arg(ap
, ptrdiff_t);
785 * The rest also applies to other integer formats, so fall
791 * Get the arg if we haven't already.
796 i_num
= (wide_int
) va_arg(ap
, int);
801 i_num
= (wide_int
) va_arg(ap
, long int);
805 i_num
= (wide_int
) va_arg(ap
, ssize_t
);
807 i_num
= (wide_int
) va_arg(ap
, size_t);
812 i_num
= (wide_int
) va_arg(ap
, wide_int
);
817 i_num
= (wide_int
) va_arg(ap
, intmax_t);
822 i_num
= (wide_int
) va_arg(ap
, ptrdiff_t);
827 s
= ap_php_conv_10(i_num
, (*fmt
) == 'u', &is_negative
,
828 &num_buf
[NUM_BUF_SIZE
], &s_len
);
829 FIX_PRECISION(adjust_precision
, precision
, s
, s_len
);
836 else if (print_blank
)
845 ui_num
= (u_wide_int
) va_arg(ap
, unsigned int);
850 ui_num
= (u_wide_int
) va_arg(ap
, unsigned long int);
853 ui_num
= (u_wide_int
) va_arg(ap
, size_t);
857 ui_num
= (u_wide_int
) va_arg(ap
, u_wide_int
);
862 ui_num
= (u_wide_int
) va_arg(ap
, uintmax_t);
867 ui_num
= (u_wide_int
) va_arg(ap
, ptrdiff_t);
871 s
= ap_php_conv_p2(ui_num
, 3, *fmt
,
872 &num_buf
[NUM_BUF_SIZE
], &s_len
);
873 FIX_PRECISION(adjust_precision
, precision
, s
, s_len
);
874 if (alternate_form
&& *s
!= '0') {
885 ui_num
= (u_wide_int
) va_arg(ap
, unsigned int);
890 ui_num
= (u_wide_int
) va_arg(ap
, unsigned long int);
893 ui_num
= (u_wide_int
) va_arg(ap
, size_t);
897 ui_num
= (u_wide_int
) va_arg(ap
, u_wide_int
);
902 ui_num
= (u_wide_int
) va_arg(ap
, uintmax_t);
907 ui_num
= (u_wide_int
) va_arg(ap
, ptrdiff_t);
911 s
= ap_php_conv_p2(ui_num
, 4, *fmt
,
912 &num_buf
[NUM_BUF_SIZE
], &s_len
);
913 FIX_PRECISION(adjust_precision
, precision
, s
, s_len
);
914 if (alternate_form
&& i_num
!= 0) {
915 *--s
= *fmt
; /* 'x' or 'X' */
924 s
= va_arg(ap
, char *);
927 if (adjust_precision
&& precision
< s_len
)
930 s
= const_cast<char*>(s_null
);
943 fp_num
= (double) va_arg(ap
, long double);
946 fp_num
= va_arg(ap
, double);
952 if (std::isnan(fp_num
)) {
953 s
= const_cast<char*>("nan");
955 } else if (std::isinf(fp_num
)) {
956 s
= const_cast<char*>("inf");
961 lconv
= localeconv();
964 s
= php_conv_fp((*fmt
== 'f')?'F':*fmt
, fp_num
, alternate_form
,
965 (adjust_precision
== NO
) ? FLOAT_DIGITS
: precision
,
966 (*fmt
== 'f')?LCONV_DECIMAL_POINT
:'.',
967 &is_negative
, &num_buf
[1], &s_len
);
972 else if (print_blank
)
984 fp_num
= (double) va_arg(ap
, long double);
987 fp_num
= va_arg(ap
, double);
993 if (std::isnan(fp_num
)) {
994 s
= const_cast<char*>("NAN");
997 } else if (std::isinf(fp_num
)) {
999 s
= const_cast<char*>("INF");
1002 s
= const_cast<char*>("-INF");
1008 if (adjust_precision
== NO
)
1009 precision
= FLOAT_DIGITS
;
1010 else if (precision
== 0)
1013 * * We use &num_buf[ 1 ], so that we have room for the sign
1015 #ifdef HAVE_LOCALE_H
1017 lconv
= localeconv();
1020 s
= php_gcvt(fp_num
, precision
,
1021 (*fmt
=='H' || *fmt
== 'k') ? '.' : LCONV_DECIMAL_POINT
,
1022 (*fmt
== 'G' || *fmt
== 'H')?'E':'e', &num_buf
[1]);
1025 else if (print_sign
)
1027 else if (print_blank
)
1032 if (alternate_form
&& (q
= strchr(s
, '.')) == nullptr)
1038 char_buf
[0] = (char) (va_arg(ap
, int));
1054 *(va_arg(ap
, int *)) = outpos
;
1058 * Always extract the argument as a "char *" pointer. We
1059 * should be using "void *" but there are still machines
1060 * that don't understand it.
1061 * If the pointer size is equal to the size of an unsigned
1062 * integer we convert the pointer to a hex number, otherwise
1063 * we print "%p" to indicate that we don't handle "%p".
1066 if (sizeof(char *) <= sizeof(u_wide_int
)) {
1067 ui_num
= (u_wide_int
)((size_t) va_arg(ap
, char *));
1068 s
= ap_php_conv_p2(ui_num
, 4, 'x',
1069 &num_buf
[NUM_BUF_SIZE
], &s_len
);
1076 s
= const_cast<char*>("%p");
1085 * The last character of the format string was %.
1092 throw Exception("Illegal length modifier specified '%c'", *fmt
);
1095 * The default case is for unrecognized %'s.
1096 * We print %<char> to help the user identify what
1097 * option is not understood.
1098 * This is also useful in case the user wants to pass
1099 * the output of format_converter to another function
1100 * that understands some other %<char> (like syslog).
1101 * Note that we can't point s inside fmt because the
1102 * unknown <char> could be preceded by width etc.
1113 if (prefix_char
!= NUL
) {
1117 if (adjust_width
&& adjust
== RIGHT
&& min_width
> s_len
) {
1118 if (pad_char
== '0' && prefix_char
!= NUL
) {
1119 appendchar(&result
, &outpos
, &size
, *s
);
1124 for (int i
= 0; i
< min_width
- s_len
; i
++) {
1125 appendchar(&result
, &outpos
, &size
, pad_char
);
1129 * Print the (for now) non-null terminated string s.
1131 appendsimplestring(&result
, &outpos
, &size
, s
, s_len
);
1133 if (adjust_width
&& adjust
== LEFT
&& min_width
> s_len
) {
1134 for (int i
= 0; i
< min_width
- s_len
; i
++) {
1135 appendchar(&result
, &outpos
, &size
, pad_char
);
1143 * Add the terminating null here since it wasn't added incrementally above
1144 * once the whole string has been composed.
1146 appendchar(&result
, &outpos
, &size
, NUL
);
1152 * This is the general purpose conversion function.
1154 int vspprintf(char** pbuf
, size_t /*max_len*/, const char* format
, ...) {
1157 va_start(ap
, format
);
1158 len
= xbuf_format_converter(pbuf
, format
, ap
);
1164 * Same as vspprintf but taking an va_list
1166 int vspprintf_ap(char** pbuf
, size_t /*max_len*/, const char* format
,
1169 len
= xbuf_format_converter(pbuf
, format
, ap
);
1173 int spprintf(char **pbuf
, size_t max_len
, const char *format
, ...)
1178 va_start(ap
, format
);
1179 cc
= vspprintf(pbuf
, max_len
, format
, ap
);
1184 ///////////////////////////////////////////////////////////////////////////////