2
+----------------------------------------------------------------------+
4
+----------------------------------------------------------------------+
5
| Copyright (c) 1997-2009 The PHP Group |
6
+----------------------------------------------------------------------+
7
| This source file is subject to version 3.01 of the PHP license, |
8
| that is bundled with this package in the file LICENSE, and is |
9
| available through the world-wide-web at the following url: |
10
| http://www.php.net/license/3_01.txt |
11
| If you did not receive a copy of the PHP license and are unable to |
12
| obtain it through the world-wide-web, please send a note to |
13
| license@php.net so we can mail you a copy immediately. |
14
+----------------------------------------------------------------------+
16
+----------------------------------------------------------------------+
19
/* $Id: snprintf.c,v 1.37.2.4.2.14.2.8 2008/12/31 11:15:48 sebastian Exp $ */
24
#include <zend_strtod.h>
29
#include <sys/types.h>
35
#ifdef HAVE_INTTYPES_H
41
#define LCONV_DECIMAL_POINT (*lconv->decimal_point)
43
#define LCONV_DECIMAL_POINT '.'
47
* Copyright (c) 2002, 2006 Todd C. Miller <Todd.Miller@courtesan.com>
49
* Permission to use, copy, modify, and distribute this software for any
50
* purpose with or without fee is hereby granted, provided that the above
51
* copyright notice and this permission notice appear in all copies.
53
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
54
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
55
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
56
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
57
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
58
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
59
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
61
* Sponsored in part by the Defense Advanced Research Projects
62
* Agency (DARPA) and Air Force Research Laboratory, Air Force
63
* Materiel Command, USAF, under agreement number F39502-99-1-0512.
66
static char * __cvt(double value, int ndigit, int *decpt, int *sign, int fmode, int pad) /* {{{ */
68
register char *s = NULL;
78
/* __dtoa() doesn't allocate space for 0 so we do it by hand */
80
*decpt = 1 - fmode; /* 1 for 'e', 0 for 'f' */
82
if ((rve = s = (char *)malloc(ndigit?siz:2)) == NULL) {
91
p = zend_dtoa(value, fmode + 2, ndigit, decpt, sign, &rve);
93
/* Infinity or Nan, convert to inf or nan like printf */
97
return(c == 'I' ? "INF" : "NAN");
99
/* Make a local copy and adjust rve to be in terms of s */
103
if ((s = (char *)malloc(siz+1)) == NULL) {
107
(void) strlcpy(s, p, siz);
112
/* Add trailing zeros */
125
static inline char *php_ecvt(double value, int ndigit, int *decpt, int *sign) /* {{{ */
127
return(__cvt(value, ndigit, decpt, sign, 0, 1));
131
static inline char *php_fcvt(double value, int ndigit, int *decpt, int *sign) /* {{{ */
133
return(__cvt(value, ndigit, decpt, sign, 1, 1));
137
PHPAPI char *php_gcvt(double value, int ndigit, char dec_point, char exponent, char *buf) /* {{{ */
139
char *digits, *dst, *src;
142
digits = zend_dtoa(value, 2, ndigit, &decpt, &sign, NULL);
145
* Infinity or NaN, convert to inf or nan with sign.
146
* We assume the buffer is at least ndigit long.
148
snprintf(buf, ndigit + 1, "%s%s", (sign && *digits == 'I') ? "-" : "", *digits == 'I' ? "INF" : "NAN");
149
zend_freedtoa(digits);
158
if ((decpt >= 0 && decpt > ndigit) || decpt < -3) { /* use E-style */
159
/* exponential format (e.g. 1.2345e+13) */
174
} while (*src != '\0');
183
*dst++ = '0' + decpt;
187
for (sign = decpt, i = 0; (sign /= 10) != 0; i++)
191
dst[i--] = '0' + decpt % 10;
195
} else if (decpt < 0) {
196
/* standard format 0. */
197
*dst++ = '0'; /* zero before decimal point */
201
} while (++decpt < 0);
203
while (*src != '\0') {
208
/* standard format */
209
for (i = 0, src = digits; i < decpt; i++) {
218
*dst++ = '0'; /* zero before decimal point */
221
for (i = decpt; digits[i] != '\0'; i++) {
227
zend_freedtoa(digits);
232
/* {{{ Apache license */
233
/* ====================================================================
234
* Copyright (c) 1995-1998 The Apache Group. All rights reserved.
236
* Redistribution and use in source and binary forms, with or without
237
* modification, are permitted provided that the following conditions
240
* 1. Redistributions of source code must retain the above copyright
241
* notice, this list of conditions and the following disclaimer.
243
* 2. Redistributions in binary form must reproduce the above copyright
244
* notice, this list of conditions and the following disclaimer in
245
* the documentation and/or other materials provided with the
248
* 3. All advertising materials mentioning features or use of this
249
* software must display the following acknowledgment:
250
* "This product includes software developed by the Apache Group
251
* for use in the Apache HTTP server project (http://www.apache.org/)."
253
* 4. The names "Apache Server" and "Apache Group" must not be used to
254
* endorse or promote products derived from this software without
255
* prior written permission.
257
* 5. Redistributions of any form whatsoever must retain the following
259
* "This product includes software developed by the Apache Group
260
* for use in the Apache HTTP server project (http://www.apache.org/)."
262
* THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
263
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
264
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
265
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
266
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
267
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
268
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
269
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
270
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
271
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
272
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
273
* OF THE POSSIBILITY OF SUCH DAMAGE.
274
* ====================================================================
276
* This software consists of voluntary contributions made by many
277
* individuals on behalf of the Apache Group and was originally based
278
* on public domain software written at the National Center for
279
* Supercomputing Applications, University of Illinois, Urbana-Champaign.
280
* For more information on the Apache Group and the Apache HTTP server
281
* project, please see <http://www.apache.org/>.
283
* This code is based on, and used with the permission of, the
284
* SIO stdio-replacement strx_* functions by Panos Tsirigotis
285
* <panos@alumni.cs.colorado.edu> for xinetd.
292
#define INT_NULL ((int *)0)
294
#define S_NULL "(null)"
297
#define FLOAT_DIGITS 6
298
#define EXPONENT_LENGTH 10
302
* Convert num to its decimal format.
304
* - a pointer to a string containing the number (no sign)
305
* - len contains the length of the string
306
* - is_negative is set to TRUE or FALSE depending on the sign
307
* of the number (always set to FALSE if is_unsigned is TRUE)
309
* The caller provides a buffer for the string: that is the buf_end argument
310
* which is a pointer to the END of the buffer + 1 (i.e. if the buffer
311
* is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
313
/* char * ap_php_conv_10() {{{ */
314
char * ap_php_conv_10(register wide_int num, register bool_int is_unsigned,
315
register bool_int * is_negative, char *buf_end, register int *len)
317
register char *p = buf_end;
318
register u_wide_int magnitude;
321
magnitude = (u_wide_int) num;
322
*is_negative = FALSE;
324
*is_negative = (num < 0);
327
* On a 2's complement machine, negating the most negative integer
328
* results in a number that cannot be represented as a signed integer.
329
* Here is what we do to obtain the number's magnitude:
330
* a. add 1 to the number
331
* b. negate it (becomes positive)
332
* c. convert it to unsigned
336
wide_int t = num + 1;
337
magnitude = ((u_wide_int) - t) + 1;
339
magnitude = (u_wide_int) num;
344
* We use a do-while loop so that we write at least 1 digit
347
register u_wide_int new_magnitude = magnitude / 10;
349
*--p = (char)(magnitude - new_magnitude * 10 + '0');
350
magnitude = new_magnitude;
359
/* If you change this value then also change bug24640.phpt.
360
* Also NDIG must be reasonable smaller than NUM_BUF_SIZE.
366
* Convert a floating point number to a string formats 'f', 'e' or 'E'.
367
* The result is placed in buf, and len denotes the length of the string
368
* The sign is returned in the is_negative argument (and is not placed
371
/* PHPAPI char * php_conv_fp() {{{ */
372
PHPAPI char * php_conv_fp(register char format, register double num,
373
boolean_e add_dp, int precision, char dec_point, bool_int * is_negative, char *buf, int *len)
375
register char *s = buf;
376
register char *p, *p_orig;
379
if (precision >= NDIG - 1) {
380
precision = NDIG - 2;
384
p_orig = p = php_fcvt(num, precision, &decimal_point, is_negative);
385
} else { /* either e or E format */
386
p_orig = p = php_ecvt(num, precision + 1, &decimal_point, is_negative);
390
* Check for Infinity and NaN
392
if (isalpha((int)*p)) {
394
memcpy(buf, p, *len + 1);
395
*is_negative = FALSE;
400
if (decimal_point <= 0) {
401
if (num != 0 || precision > 0) {
405
while (decimal_point++ < 0) {
413
int addz = decimal_point >= NDIG ? decimal_point - NDIG + 1 : 0;
414
decimal_point -= addz;
415
while (decimal_point-- > 0) {
421
if (precision > 0 || add_dp) {
427
if (precision > 0 || add_dp) {
433
* copy the rest of p, the NUL is NOT copied
440
char temp[EXPONENT_LENGTH]; /* for exponent conversion */
442
bool_int exponent_is_negative;
444
*s++ = format; /* either e or E */
446
if (decimal_point != 0) {
447
p = ap_php_conv_10((wide_int) decimal_point, FALSE, &exponent_is_negative, &temp[EXPONENT_LENGTH], &t_len);
448
*s++ = exponent_is_negative ? '-' : '+';
451
* Make sure the exponent has at least 2 digits
468
* Convert num to a base X number where X is a power of 2. nbits determines X.
469
* For example, if nbits is 3, we do base 8 conversion
471
* a pointer to a string containing the number
473
* The caller provides a buffer for the string: that is the buf_end argument
474
* which is a pointer to the END of the buffer + 1 (i.e. if the buffer
475
* is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
477
char * ap_php_conv_p2(register u_wide_int num, register int nbits, char format, char *buf_end, register int *len) /* {{{ */
479
register int mask = (1 << nbits) - 1;
480
register char *p = buf_end;
481
static char low_digits[] = "0123456789abcdef";
482
static char upper_digits[] = "0123456789ABCDEF";
483
register char *digits = (format == 'X') ? upper_digits : low_digits;
486
*--p = digits[num & mask];
497
* NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
499
* XXX: this is a magic number; do not decrease it
501
#define NUM_BUF_SIZE 512
505
* Descriptor for buffer area
509
char *nextb; /* pointer to next byte to read/write */
512
typedef struct buf_area buffy;
515
* The INS_CHAR macro inserts a character in the buffer and writes
516
* the buffer back to disk if necessary
517
* It uses the char pointers sp and bep:
518
* sp points to the next available character in the buffer
519
* bep points to the end-of-buffer+1
520
* While using this macro, note that the nextb pointer is NOT updated.
522
* NOTE: Evaluation of the c argument should not have any side-effects
524
#define INS_CHAR(c, sp, bep, cc) \
533
#define NUM( c ) ( c - '0' )
535
#define STR_TO_DEC( str, num ) \
536
num = NUM( *str++ ) ; \
537
while ( isdigit((int)*str ) ) \
540
num += NUM( *str++ ) ; \
544
* This macro does zero padding so that the precision
545
* requirement is satisfied. The padding is done by
546
* adding '0's to the left of the string that is going
549
#define FIX_PRECISION( adjust, precision, s, s_len ) \
551
while ( s_len < precision ) \
558
* Macro that does padding. The padding is done by printing
561
#define PAD( width, len, ch ) do \
563
INS_CHAR( ch, sp, bep, cc ) ; \
566
while ( width > len )
569
* Prefix the character ch to the string str
571
* Set the has_prefix flag
573
#define PREFIX( str, length, ch ) *--str = ch ; length++ ; has_prefix = YES
577
* Do format conversion placing the output in buffer
579
static int format_converter(register buffy * odp, const char *fmt, va_list ap) /* {{{ */
588
int s_len, free_zcopy;
600
wide_int i_num = (wide_int) 0;
603
char num_buf[NUM_BUF_SIZE];
604
char char_buf[2]; /* for printing %% and %<unknown> */
607
struct lconv *lconv = NULL;
613
length_modifier_e modifier;
614
boolean_e alternate_form;
615
boolean_e print_sign;
616
boolean_e print_blank;
617
boolean_e adjust_precision;
618
boolean_e adjust_width;
619
bool_int is_negative;
626
INS_CHAR(*fmt, sp, bep, cc);
629
* Default variable settings
632
alternate_form = print_sign = print_blank = NO;
640
* Try to avoid checking for flags, width or precision
642
if (isascii((int)*fmt) && !islower((int)*fmt)) {
644
* Recognize flags: -, #, BLANK, +
649
else if (*fmt == '+')
651
else if (*fmt == '#')
652
alternate_form = YES;
653
else if (*fmt == ' ')
655
else if (*fmt == '0')
662
* Check if a width was specified
664
if (isdigit((int)*fmt)) {
665
STR_TO_DEC(fmt, min_width);
667
} else if (*fmt == '*') {
668
min_width = va_arg(ap, int);
673
min_width = -min_width;
679
* Check if a precision was specified
681
* XXX: an unreasonable amount of precision may be specified
682
* resulting in overflow of num_buf. Currently we
683
* ignore this possibility.
686
adjust_precision = YES;
688
if (isdigit((int)*fmt)) {
689
STR_TO_DEC(fmt, precision);
690
} else if (*fmt == '*') {
691
precision = va_arg(ap, int);
698
adjust_precision = NO;
700
adjust_precision = adjust_width = NO;
708
modifier = LM_LONG_DOUBLE;
713
if (*fmt == '6' && *(fmt+1) == '4') {
715
modifier = LM_LONG_LONG;
718
if (*fmt == '3' && *(fmt+1) == '2') {
723
modifier = LM_LONG_LONG;
734
modifier = LM_LONG_LONG;
741
modifier = LM_SIZE_T;
746
modifier = LM_INTMAX_T;
748
modifier = LM_SIZE_T;
754
modifier = LM_PTRDIFF_T;
756
modifier = LM_SIZE_T;
764
/* these are promoted to int, so no break */
771
* Argument extraction and printing.
772
* First we determine the argument type.
773
* Then, we convert the argument to a string.
774
* On exit from the switch, s points to the string that
775
* must be printed, s_len has the length of the string
776
* The precision requirements, if any, are reflected in s_len.
778
* NOTE: pad_char may be set to '0' because of the 0 flag.
779
* It is reset to ' ' by non-numeric formats
783
zvp = (zval*) va_arg(ap, zval*);
784
zend_make_printable_zval(zvp, &zcopy, &free_zcopy);
788
s_len = Z_STRLEN_P(zvp);
790
if (adjust_precision && precision < s_len) {
797
i_num = (wide_int) va_arg(ap, unsigned int);
802
i_num = (wide_int) va_arg(ap, unsigned long int);
805
i_num = (wide_int) va_arg(ap, size_t);
809
i_num = (wide_int) va_arg(ap, u_wide_int);
814
i_num = (wide_int) va_arg(ap, uintmax_t);
819
i_num = (wide_int) va_arg(ap, ptrdiff_t);
824
* The rest also applies to other integer formats, so fall
830
* Get the arg if we haven't already.
835
i_num = (wide_int) va_arg(ap, int);
840
i_num = (wide_int) va_arg(ap, long int);
844
i_num = (wide_int) va_arg(ap, ssize_t);
846
i_num = (wide_int) va_arg(ap, size_t);
851
i_num = (wide_int) va_arg(ap, wide_int);
856
i_num = (wide_int) va_arg(ap, intmax_t);
861
i_num = (wide_int) va_arg(ap, ptrdiff_t);
866
s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
867
&num_buf[NUM_BUF_SIZE], &s_len);
868
FIX_PRECISION(adjust_precision, precision, s, s_len);
873
} else if (print_sign) {
875
} else if (print_blank) {
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, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
912
FIX_PRECISION(adjust_precision, precision, s, s_len);
913
if (alternate_form && *s != '0') {
924
ui_num = (u_wide_int) va_arg(ap, unsigned int);
929
ui_num = (u_wide_int) va_arg(ap, unsigned long int);
932
ui_num = (u_wide_int) va_arg(ap, size_t);
936
ui_num = (u_wide_int) va_arg(ap, u_wide_int);
941
ui_num = (u_wide_int) va_arg(ap, uintmax_t);
946
ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
950
s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
951
FIX_PRECISION(adjust_precision, precision, s, s_len);
952
if (alternate_form && i_num != 0) {
953
*--s = *fmt; /* 'x' or 'X' */
962
s = va_arg(ap, char *);
965
if (adjust_precision && precision < s_len) {
982
fp_num = (double) va_arg(ap, long double);
985
fp_num = va_arg(ap, double);
991
if (zend_isnan(fp_num)) {
994
} else if (zend_isinf(fp_num)) {
1000
lconv = localeconv();
1003
s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
1004
(adjust_precision == NO) ? FLOAT_DIGITS : precision,
1005
(*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
1006
&is_negative, &num_buf[1], &s_len);
1009
else if (print_sign)
1011
else if (print_blank)
1022
case LM_LONG_DOUBLE:
1023
fp_num = (double) va_arg(ap, long double);
1026
fp_num = va_arg(ap, double);
1032
if (zend_isnan(fp_num)) {
1036
} else if (zend_isinf(fp_num)) {
1047
if (adjust_precision == NO) {
1048
precision = FLOAT_DIGITS;
1049
} else if (precision == 0) {
1053
* * We use &num_buf[ 1 ], so that we have room for the sign
1055
#ifdef HAVE_LOCALE_H
1057
lconv = localeconv();
1060
s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
1063
} else if (print_sign) {
1065
} else if (print_blank) {
1071
if (alternate_form && (q = strchr(s, '.')) == NULL) {
1078
char_buf[0] = (char) (va_arg(ap, int));
1094
*(va_arg(ap, int *)) = cc;
1098
* Always extract the argument as a "char *" pointer. We
1099
* should be using "void *" but there are still machines
1100
* that don't understand it.
1101
* If the pointer size is equal to the size of an unsigned
1102
* integer we convert the pointer to a hex number, otherwise
1103
* we print "%p" to indicate that we don't handle "%p".
1106
if (sizeof(char *) <= sizeof(u_wide_int)) {
1107
ui_num = (u_wide_int)((size_t) va_arg(ap, char *));
1108
s = ap_php_conv_p2(ui_num, 4, 'x',
1109
&num_buf[NUM_BUF_SIZE], &s_len);
1125
* The last character of the format string was %.
1132
php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt);
1134
* The default case is for unrecognized %'s.
1135
* We print %<char> to help the user identify what
1136
* option is not understood.
1137
* This is also useful in case the user wants to pass
1138
* the output of format_converter to another function
1139
* that understands some other %<char> (like syslog).
1140
* Note that we can't point s inside fmt because the
1141
* unknown <char> could be preceded by width etc.
1152
if (prefix_char != NUL) {
1156
if (adjust_width && adjust == RIGHT && min_width > s_len) {
1157
if (pad_char == '0' && prefix_char != NUL) {
1158
INS_CHAR(*s, sp, bep, cc)
1163
PAD(min_width, s_len, pad_char);
1166
* Print the string s.
1168
for (i = s_len; i != 0; i--) {
1169
INS_CHAR(*s, sp, bep, cc);
1173
if (adjust_width && adjust == LEFT && min_width > s_len)
1174
PAD(min_width, s_len, pad_char);
1188
* This is the general purpose conversion function.
1190
static void strx_printv(int *ccp, char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1196
* First initialize the descriptor
1197
* Notice that if no length is given, we initialize buf_end to the
1198
* highest possible address.
1201
od.buf_end = (char *) ~0;
1202
od.nextb = (char *) ~0;
1204
od.buf_end = &buf[len-1];
1211
cc = format_converter(&od, format, ap);
1212
if (len != 0 && od.nextb <= od.buf_end) {
1221
PHPAPI int ap_php_slprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1226
va_start(ap, format);
1227
strx_printv(&cc, buf, len, format, ap);
1237
PHPAPI int ap_php_vslprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1241
strx_printv(&cc, buf, len, format, ap);
1250
PHPAPI int ap_php_snprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1255
va_start(ap, format);
1256
strx_printv(&cc, buf, len, format, ap);
1262
PHPAPI int ap_php_vsnprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1266
strx_printv(&cc, buf, len, format, ap);
1271
PHPAPI int ap_php_vasprintf(char **buf, const char *format, va_list ap) /* {{{ */
1277
cc = ap_php_vsnprintf(NULL, 0, format, ap2);
1283
if ((*buf = malloc(++cc)) != NULL) {
1284
if ((cc = ap_php_vsnprintf(*buf, cc, format, ap)) < 0) {
1295
PHPAPI int ap_php_asprintf(char **buf, const char *format, ...) /* {{{ */
1300
va_start(ap, format);
1301
cc = vasprintf(buf, format, ap);
1312
* vim600: sw=4 ts=4 fdm=marker
1313
* vim<600: sw=4 ts=4