1/*
2  +----------------------------------------------------------------------+
3  | PHP Version 5                                                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 1997-2014 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  +----------------------------------------------------------------------+
15  | Author:                                                              |
16  +----------------------------------------------------------------------+
17*/
18
19/* $Id$ */
20
21#define _GNU_SOURCE
22#include "php.h"
23
24#include <zend_strtod.h>
25
26#include <stddef.h>
27#include <stdio.h>
28#include <ctype.h>
29#include <sys/types.h>
30#include <stdarg.h>
31#include <string.h>
32#include <stdlib.h>
33#include <math.h>
34
35#ifdef HAVE_INTTYPES_H
36#include <inttypes.h>
37#endif
38
39#ifdef HAVE_LOCALE_H
40#include <locale.h>
41#define LCONV_DECIMAL_POINT (*lconv->decimal_point)
42#else
43#define LCONV_DECIMAL_POINT '.'
44#endif
45
46/*
47 * Copyright (c) 2002, 2006 Todd C. Miller <Todd.Miller@courtesan.com>
48 *
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.
52 *
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.
60 *
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.
64 */
65
66static char * __cvt(double value, int ndigit, int *decpt, int *sign, int fmode, int pad) /* {{{ */
67{
68    register char *s = NULL;
69    char *p, *rve, c;
70    size_t siz;
71
72    if (ndigit < 0) {
73        siz = -ndigit + 1;
74    } else {
75        siz = ndigit + 1;
76    }
77
78    /* __dtoa() doesn't allocate space for 0 so we do it by hand */
79    if (value == 0.0) {
80        *decpt = 1 - fmode; /* 1 for 'e', 0 for 'f' */
81        *sign = 0;
82        if ((rve = s = (char *)malloc(ndigit?siz:2)) == NULL) {
83            return(NULL);
84        }
85        *rve++ = '0';
86        *rve = '\0';
87        if (!ndigit) {
88            return(s);
89        }
90    } else {
91        p = zend_dtoa(value, fmode + 2, ndigit, decpt, sign, &rve);
92        if (*decpt == 9999) {
93            /* Infinity or Nan, convert to inf or nan like printf */
94            *decpt = 0;
95            c = *p;
96            zend_freedtoa(p);
97            return strdup((c == 'I' ? "INF" : "NAN"));
98        }
99        /* Make a local copy and adjust rve to be in terms of s */
100        if (pad && fmode) {
101            siz += *decpt;
102        }
103        if ((s = (char *)malloc(siz+1)) == NULL) {
104            zend_freedtoa(p);
105            return(NULL);
106        }
107        (void) strlcpy(s, p, siz);
108        rve = s + (rve - p);
109        zend_freedtoa(p);
110    }
111
112    /* Add trailing zeros */
113    if (pad) {
114        siz -= rve - s;
115        while (--siz) {
116            *rve++ = '0';
117        }
118        *rve = '\0';
119    }
120
121    return(s);
122}
123/* }}} */
124
125static inline char *php_ecvt(double value, int ndigit, int *decpt, int *sign) /* {{{ */
126{
127    return(__cvt(value, ndigit, decpt, sign, 0, 1));
128}
129/* }}} */
130
131static inline char *php_fcvt(double value, int ndigit, int *decpt, int *sign) /* {{{ */
132{
133    return(__cvt(value, ndigit, decpt, sign, 1, 1));
134}
135/* }}} */
136
137PHPAPI char *php_gcvt(double value, int ndigit, char dec_point, char exponent, char *buf) /* {{{ */
138{
139    char *digits, *dst, *src;
140    int i, decpt, sign;
141
142    digits = zend_dtoa(value, 2, ndigit, &decpt, &sign, NULL);
143    if (decpt == 9999) {
144        /*
145         * Infinity or NaN, convert to inf or nan with sign.
146         * We assume the buffer is at least ndigit long.
147         */
148        snprintf(buf, ndigit + 1, "%s%s", (sign && *digits == 'I') ? "-" : "", *digits == 'I' ? "INF" : "NAN");
149        zend_freedtoa(digits);
150        return (buf);
151    }
152
153    dst = buf;
154    if (sign) {
155        *dst++ = '-';
156    }
157
158    if ((decpt >= 0 && decpt > ndigit) || decpt < -3) { /* use E-style */
159        /* exponential format (e.g. 1.2345e+13) */
160        if (--decpt < 0) {
161            sign = 1;
162            decpt = -decpt;
163        } else {
164            sign = 0;
165        }
166        src = digits;
167        *dst++ = *src++;
168        *dst++ = dec_point;
169        if (*src == '\0') {
170            *dst++ = '0';
171        } else {
172            do {
173                *dst++ = *src++;
174            } while (*src != '\0');
175        }
176        *dst++ = exponent;
177        if (sign) {
178            *dst++ = '-';
179        } else {
180            *dst++ = '+';
181        }
182        if (decpt < 10) {
183            *dst++ = '0' + decpt;
184            *dst = '\0';
185        } else {
186            /* XXX - optimize */
187            for (sign = decpt, i = 0; (sign /= 10) != 0; i++)
188                continue;
189            dst[i + 1] = '\0';
190            while (decpt != 0) {
191                dst[i--] = '0' + decpt % 10;
192                decpt /= 10;
193            }
194        }
195    } else if (decpt < 0) {
196        /* standard format 0. */
197        *dst++ = '0';   /* zero before decimal point */
198        *dst++ = dec_point;
199        do {
200            *dst++ = '0';
201        } while (++decpt < 0);
202        src = digits;
203        while (*src != '\0') {
204            *dst++ = *src++;
205        }
206        *dst = '\0';
207    } else {
208        /* standard format */
209        for (i = 0, src = digits; i < decpt; i++) {
210            if (*src != '\0') {
211                *dst++ = *src++;
212            } else {
213                *dst++ = '0';
214            }
215        }
216        if (*src != '\0') {
217            if (src == digits) {
218                *dst++ = '0';   /* zero before decimal point */
219            }
220            *dst++ = dec_point;
221            for (i = decpt; digits[i] != '\0'; i++) {
222                *dst++ = digits[i];
223            }
224        }
225        *dst = '\0';
226    }
227    zend_freedtoa(digits);
228    return (buf);
229}
230/* }}} */
231
232/* {{{ Apache license */
233/* ====================================================================
234 * Copyright (c) 1995-1998 The Apache Group.  All rights reserved.
235 *
236 * Redistribution and use in source and binary forms, with or without
237 * modification, are permitted provided that the following conditions
238 * are met:
239 *
240 * 1. Redistributions of source code must retain the above copyright
241 *    notice, this list of conditions and the following disclaimer.
242 *
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
246 *    distribution.
247 *
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/)."
252 *
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.
256 *
257 * 5. Redistributions of any form whatsoever must retain the following
258 *    acknowledgment:
259 *    "This product includes software developed by the Apache Group
260 *    for use in the Apache HTTP server project (http://www.apache.org/)."
261 *
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 * ====================================================================
275 *
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/>.
282 *
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.
286 */
287/* }}} */
288
289#define FALSE           0
290#define TRUE            1
291#define NUL         '\0'
292#define INT_NULL        ((int *)0)
293
294#define S_NULL          "(null)"
295#define S_NULL_LEN      6
296
297#define FLOAT_DIGITS        6
298#define EXPONENT_LENGTH     10
299
300
301/*
302 * Convert num to its decimal format.
303 * Return value:
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)
308 *
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 ])
312 */
313/* char * ap_php_conv_10() {{{ */
314char * ap_php_conv_10(register wide_int num, register bool_int is_unsigned,
315       register bool_int * is_negative, char *buf_end, register size_t *len)
316{
317    register char *p = buf_end;
318    register u_wide_int magnitude;
319
320    if (is_unsigned) {
321        magnitude = (u_wide_int) num;
322        *is_negative = FALSE;
323    } else {
324        *is_negative = (num < 0);
325
326        /*
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
333         *      d. add 1
334         */
335        if (*is_negative) {
336            wide_int t = num + 1;
337            magnitude = ((u_wide_int) - t) + 1;
338        } else {
339            magnitude = (u_wide_int) num;
340        }
341    }
342
343    /*
344     * We use a do-while loop so that we write at least 1 digit
345     */
346    do {
347        register u_wide_int new_magnitude = magnitude / 10;
348
349        *--p = (char)(magnitude - new_magnitude * 10 + '0');
350        magnitude = new_magnitude;
351    }
352    while (magnitude);
353
354    *len = buf_end - p;
355    return (p);
356}
357/* }}} */
358
359/* If you change this value then also change bug24640.phpt.
360 * Also NDIG must be reasonable smaller than NUM_BUF_SIZE.
361 */
362#define NDIG    320
363
364
365/*
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
369 * in buf).
370 */
371/* PHPAPI char * php_conv_fp() {{{ */
372PHPAPI 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, size_t *len)
374{
375    register char *s = buf;
376    register char *p, *p_orig;
377    int decimal_point;
378
379    if (precision >= NDIG - 1) {
380        precision = NDIG - 2;
381    }
382
383    if (format == 'F') {
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);
387    }
388
389    /*
390     * Check for Infinity and NaN
391     */
392    if (isalpha((int)*p)) {
393        *len = strlen(p);
394        memcpy(buf, p, *len + 1);
395        *is_negative = FALSE;
396        free(p_orig);
397        return (buf);
398    }
399    if (format == 'F') {
400        if (decimal_point <= 0) {
401            if (num != 0 || precision > 0) {
402                *s++ = '0';
403                if (precision > 0) {
404                    *s++ = dec_point;
405                    while (decimal_point++ < 0) {
406                        *s++ = '0';
407                    }
408                } else if (add_dp) {
409                    *s++ = dec_point;
410                }
411            }
412        } else {
413            int addz = decimal_point >= NDIG ? decimal_point - NDIG + 1 : 0;
414            decimal_point -= addz;
415            while (decimal_point-- > 0) {
416                *s++ = *p++;
417            }
418            while (addz-- > 0) {
419                *s++ = '0';
420            }
421            if (precision > 0 || add_dp) {
422                *s++ = dec_point;
423            }
424        }
425    } else {
426        *s++ = *p++;
427        if (precision > 0 || add_dp) {
428            *s++ = '.';
429        }
430    }
431
432    /*
433     * copy the rest of p, the NUL is NOT copied
434     */
435    while (*p) {
436        *s++ = *p++;
437    }
438
439    if (format != 'F') {
440        char temp[EXPONENT_LENGTH];     /* for exponent conversion */
441        size_t t_len;
442        bool_int exponent_is_negative;
443
444        *s++ = format;          /* either e or E */
445        decimal_point--;
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 ? '-' : '+';
449
450            /*
451             * Make sure the exponent has at least 2 digits
452             */
453            while (t_len--) {
454                *s++ = *p++;
455            }
456        } else {
457            *s++ = '+';
458            *s++ = '0';
459        }
460    }
461    *len = s - buf;
462    free(p_orig);
463    return (buf);
464}
465/* }}} */
466
467/*
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
470 * Return value:
471 *      a pointer to a string containing the number
472 *
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 ])
476 */
477char * ap_php_conv_p2(register u_wide_int num, register int nbits, char format, char *buf_end, register size_t *len) /* {{{ */
478{
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;
484
485    do {
486        *--p = digits[num & mask];
487        num >>= nbits;
488    }
489    while (num);
490
491    *len = buf_end - p;
492    return (p);
493}
494/* }}} */
495
496/*
497 * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
498 *
499 * XXX: this is a magic number; do not decrease it
500 * Emax = 1023
501 * NDIG = 320
502 * NUM_BUF_SIZE >= strlen("-") + Emax + strlrn(".") + NDIG + strlen("E+1023") + 1;
503 */
504#define NUM_BUF_SIZE        2048
505
506
507/*
508 * Descriptor for buffer area
509 */
510struct buf_area {
511    char *buf_end;
512    char *nextb;                /* pointer to next byte to read/write   */
513};
514
515typedef struct buf_area buffy;
516
517/*
518 * The INS_CHAR macro inserts a character in the buffer and writes
519 * the buffer back to disk if necessary
520 * It uses the char pointers sp and bep:
521 *      sp points to the next available character in the buffer
522 *      bep points to the end-of-buffer+1
523 * While using this macro, note that the nextb pointer is NOT updated.
524 *
525 * NOTE: Evaluation of the c argument should not have any side-effects
526 */
527#define INS_CHAR(c, sp, bep, cc) \
528    {                            \
529        if (sp < bep)            \
530        {                        \
531            *sp++ = c;           \
532        }                        \
533        cc++;                    \
534    }
535
536#define NUM( c )            ( c - '0' )
537
538#define STR_TO_DEC( str, num )      \
539    num = NUM( *str++ ) ;       \
540    while ( isdigit((int)*str ) )       \
541    {                   \
542    num *= 10 ;         \
543    num += NUM( *str++ ) ;      \
544    }
545
546/*
547 * This macro does zero padding so that the precision
548 * requirement is satisfied. The padding is done by
549 * adding '0's to the left of the string that is going
550 * to be printed.
551 */
552#define FIX_PRECISION( adjust, precision, s, s_len )    \
553    if ( adjust )                   \
554    while ( s_len < precision )         \
555    {                       \
556        *--s = '0' ;                \
557        s_len++ ;                   \
558    }
559
560/*
561 * Macro that does padding. The padding is done by printing
562 * the character ch.
563 */
564#define PAD( width, len, ch )   do      \
565    {                   \
566        INS_CHAR( ch, sp, bep, cc ) ;   \
567        width-- ;               \
568    }                   \
569    while ( width > len )
570
571/*
572 * Prefix the character ch to the string str
573 * Increase length
574 * Set the has_prefix flag
575 */
576#define PREFIX( str, length, ch )    *--str = ch ; length++ ; has_prefix = YES
577
578
579/*
580 * Do format conversion placing the output in buffer
581 */
582static int format_converter(register buffy * odp, const char *fmt, va_list ap) /* {{{ */
583{
584    char *sp;
585    char *bep;
586    int cc = 0;
587    size_t i;
588
589    char *s = NULL;
590    size_t s_len;
591    int free_zcopy;
592    zval *zvp, zcopy;
593
594    int min_width = 0;
595    int precision = 0;
596    enum {
597        LEFT, RIGHT
598    } adjust;
599    char pad_char;
600    char prefix_char;
601
602    double fp_num;
603    wide_int i_num = (wide_int) 0;
604    u_wide_int ui_num;
605
606    char num_buf[NUM_BUF_SIZE];
607    char char_buf[2];           /* for printing %% and %<unknown> */
608
609#ifdef HAVE_LOCALE_H
610    struct lconv *lconv = NULL;
611#endif
612
613    /*
614     * Flag variables
615     */
616    length_modifier_e modifier;
617    boolean_e alternate_form;
618    boolean_e print_sign;
619    boolean_e print_blank;
620    boolean_e adjust_precision;
621    boolean_e adjust_width;
622    bool_int is_negative;
623
624    sp = odp->nextb;
625    bep = odp->buf_end;
626
627    while (*fmt) {
628        if (*fmt != '%') {
629            INS_CHAR(*fmt, sp, bep, cc);
630        } else {
631            /*
632             * Default variable settings
633             */
634            adjust = RIGHT;
635            alternate_form = print_sign = print_blank = NO;
636            pad_char = ' ';
637            prefix_char = NUL;
638            free_zcopy = 0;
639
640            fmt++;
641
642            /*
643             * Try to avoid checking for flags, width or precision
644             */
645            if (isascii((int)*fmt) && !islower((int)*fmt)) {
646                /*
647                 * Recognize flags: -, #, BLANK, +
648                 */
649                for (;; fmt++) {
650                    if (*fmt == '-')
651                        adjust = LEFT;
652                    else if (*fmt == '+')
653                        print_sign = YES;
654                    else if (*fmt == '#')
655                        alternate_form = YES;
656                    else if (*fmt == ' ')
657                        print_blank = YES;
658                    else if (*fmt == '0')
659                        pad_char = '0';
660                    else
661                        break;
662                }
663
664                /*
665                 * Check if a width was specified
666                 */
667                if (isdigit((int)*fmt)) {
668                    STR_TO_DEC(fmt, min_width);
669                    adjust_width = YES;
670                } else if (*fmt == '*') {
671                    min_width = va_arg(ap, int);
672                    fmt++;
673                    adjust_width = YES;
674                    if (min_width < 0) {
675                        adjust = LEFT;
676                        min_width = -min_width;
677                    }
678                } else
679                    adjust_width = NO;
680
681                /*
682                 * Check if a precision was specified
683                 */
684                if (*fmt == '.') {
685                    adjust_precision = YES;
686                    fmt++;
687                    if (isdigit((int)*fmt)) {
688                        STR_TO_DEC(fmt, precision);
689                    } else if (*fmt == '*') {
690                        precision = va_arg(ap, int);
691                        fmt++;
692                        if (precision < 0)
693                            precision = 0;
694                    } else
695                        precision = 0;
696
697                    if (precision > FORMAT_CONV_MAX_PRECISION) {
698                        precision = FORMAT_CONV_MAX_PRECISION;
699                    }
700                } else
701                    adjust_precision = NO;
702            } else
703                adjust_precision = adjust_width = NO;
704
705            /*
706             * Modifier check
707             */
708            switch (*fmt) {
709                case 'L':
710                    fmt++;
711                    modifier = LM_LONG_DOUBLE;
712                    break;
713                case 'I':
714                    fmt++;
715#if SIZEOF_LONG_LONG
716                    if (*fmt == '6' && *(fmt+1) == '4') {
717                        fmt += 2;
718                        modifier = LM_LONG_LONG;
719                    } else
720#endif
721                        if (*fmt == '3' && *(fmt+1) == '2') {
722                            fmt += 2;
723                            modifier = LM_LONG;
724                        } else {
725#ifdef _WIN64
726                            modifier = LM_LONG_LONG;
727#else
728                            modifier = LM_LONG;
729#endif
730                        }
731                    break;
732                case 'l':
733                    fmt++;
734#if SIZEOF_LONG_LONG
735                    if (*fmt == 'l') {
736                        fmt++;
737                        modifier = LM_LONG_LONG;
738                    } else
739#endif
740                        modifier = LM_LONG;
741                    break;
742                case 'z':
743                    fmt++;
744                    modifier = LM_SIZE_T;
745                    break;
746                case 'j':
747                    fmt++;
748#if SIZEOF_INTMAX_T
749                    modifier = LM_INTMAX_T;
750#else
751                    modifier = LM_SIZE_T;
752#endif
753                    break;
754                case 't':
755                    fmt++;
756#if SIZEOF_PTRDIFF_T
757                    modifier = LM_PTRDIFF_T;
758#else
759                    modifier = LM_SIZE_T;
760#endif
761                    break;
762                case 'p':
763                    fmt++;
764                    modifier = LM_PHP_INT_T;
765                    break;
766                case 'h':
767                    fmt++;
768                    if (*fmt == 'h') {
769                        fmt++;
770                    }
771                    /* these are promoted to int, so no break */
772                default:
773                    modifier = LM_STD;
774                    break;
775            }
776
777            /*
778             * Argument extraction and printing.
779             * First we determine the argument type.
780             * Then, we convert the argument to a string.
781             * On exit from the switch, s points to the string that
782             * must be printed, s_len has the length of the string
783             * The precision requirements, if any, are reflected in s_len.
784             *
785             * NOTE: pad_char may be set to '0' because of the 0 flag.
786             *   It is reset to ' ' by non-numeric formats
787             */
788            switch (*fmt) {
789                case 'Z': {
790                    TSRMLS_FETCH();
791                    zvp = (zval*) va_arg(ap, zval*);
792                    free_zcopy = zend_make_printable_zval(zvp, &zcopy TSRMLS_CC);
793                    if (free_zcopy) {
794                        zvp = &zcopy;
795                    }
796                    s_len = Z_STRLEN_P(zvp);
797                    s = Z_STRVAL_P(zvp);
798                    if (adjust_precision && precision < s_len) {
799                        s_len = precision;
800                    }
801                    break;
802                }
803                case 'u':
804                    switch(modifier) {
805                        default:
806                            i_num = (wide_int) va_arg(ap, unsigned int);
807                            break;
808                        case LM_LONG_DOUBLE:
809                            goto fmt_error;
810                        case LM_LONG:
811                            i_num = (wide_int) va_arg(ap, unsigned long int);
812                            break;
813                        case LM_SIZE_T:
814                            i_num = (wide_int) va_arg(ap, size_t);
815                            break;
816#if SIZEOF_LONG_LONG
817                        case LM_LONG_LONG:
818                            i_num = (wide_int) va_arg(ap, u_wide_int);
819                            break;
820#endif
821#if SIZEOF_INTMAX_T
822                        case LM_INTMAX_T:
823                            i_num = (wide_int) va_arg(ap, uintmax_t);
824                            break;
825#endif
826#if SIZEOF_PTRDIFF_T
827                        case LM_PTRDIFF_T:
828                            i_num = (wide_int) va_arg(ap, ptrdiff_t);
829                            break;
830#endif
831                        case LM_PHP_INT_T:
832                            i_num = (wide_int) va_arg(ap, zend_ulong);
833                            break;
834                    }
835                    /*
836                     * The rest also applies to other integer formats, so fall
837                     * into that case.
838                     */
839                case 'd':
840                case 'i':
841                    /*
842                     * Get the arg if we haven't already.
843                     */
844                    if ((*fmt) != 'u') {
845                        switch(modifier) {
846                            default:
847                                i_num = (wide_int) va_arg(ap, int);
848                                break;
849                            case LM_LONG_DOUBLE:
850                                goto fmt_error;
851                            case LM_LONG:
852                                i_num = (wide_int) va_arg(ap, long int);
853                                break;
854                            case LM_SIZE_T:
855#if SIZEOF_SSIZE_T
856                                i_num = (wide_int) va_arg(ap, ssize_t);
857#else
858                                i_num = (wide_int) va_arg(ap, size_t);
859#endif
860                                break;
861#if SIZEOF_LONG_LONG
862                            case LM_LONG_LONG:
863                                i_num = (wide_int) va_arg(ap, wide_int);
864                                break;
865#endif
866#if SIZEOF_INTMAX_T
867                            case LM_INTMAX_T:
868                                i_num = (wide_int) va_arg(ap, intmax_t);
869                                break;
870#endif
871#if SIZEOF_PTRDIFF_T
872                            case LM_PTRDIFF_T:
873                                i_num = (wide_int) va_arg(ap, ptrdiff_t);
874                                break;
875#endif
876                            case LM_PHP_INT_T:
877                                i_num = (wide_int) va_arg(ap, zend_long);
878                                break;
879                        }
880                    }
881                    s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
882                                &num_buf[NUM_BUF_SIZE], &s_len);
883                    FIX_PRECISION(adjust_precision, precision, s, s_len);
884
885                    if (*fmt != 'u') {
886                        if (is_negative) {
887                            prefix_char = '-';
888                        } else if (print_sign) {
889                            prefix_char = '+';
890                        } else if (print_blank) {
891                            prefix_char = ' ';
892                        }
893                    }
894                    break;
895
896
897                case 'o':
898                    switch(modifier) {
899                        default:
900                            ui_num = (u_wide_int) va_arg(ap, unsigned int);
901                            break;
902                        case LM_LONG_DOUBLE:
903                            goto fmt_error;
904                        case LM_LONG:
905                            ui_num = (u_wide_int) va_arg(ap, unsigned long int);
906                            break;
907                        case LM_SIZE_T:
908                            ui_num = (u_wide_int) va_arg(ap, size_t);
909                            break;
910#if SIZEOF_LONG_LONG
911                        case LM_LONG_LONG:
912                            ui_num = (u_wide_int) va_arg(ap, u_wide_int);
913                            break;
914#endif
915#if SIZEOF_INTMAX_T
916                        case LM_INTMAX_T:
917                            ui_num = (u_wide_int) va_arg(ap, uintmax_t);
918                            break;
919#endif
920#if SIZEOF_PTRDIFF_T
921                        case LM_PTRDIFF_T:
922                            ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
923                            break;
924#endif
925                        case LM_PHP_INT_T:
926                            ui_num = (u_wide_int) va_arg(ap, zend_ulong);
927                            break;
928                    }
929                    s = ap_php_conv_p2(ui_num, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
930                    FIX_PRECISION(adjust_precision, precision, s, s_len);
931                    if (alternate_form && *s != '0') {
932                        *--s = '0';
933                        s_len++;
934                    }
935                    break;
936
937
938                case 'x':
939                case 'X':
940                    switch(modifier) {
941                        default:
942                            ui_num = (u_wide_int) va_arg(ap, unsigned int);
943                            break;
944                        case LM_LONG_DOUBLE:
945                            goto fmt_error;
946                        case LM_LONG:
947                            ui_num = (u_wide_int) va_arg(ap, unsigned long int);
948                            break;
949                        case LM_SIZE_T:
950                            ui_num = (u_wide_int) va_arg(ap, size_t);
951                            break;
952#if SIZEOF_LONG_LONG
953                        case LM_LONG_LONG:
954                            ui_num = (u_wide_int) va_arg(ap, u_wide_int);
955                            break;
956#endif
957#if SIZEOF_INTMAX_T
958                        case LM_INTMAX_T:
959                            ui_num = (u_wide_int) va_arg(ap, uintmax_t);
960                            break;
961#endif
962#if SIZEOF_PTRDIFF_T
963                        case LM_PTRDIFF_T:
964                            ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
965                            break;
966#endif
967                        case LM_PHP_INT_T:
968                            ui_num = (u_wide_int) va_arg(ap, zend_ulong);
969                            break;
970                    }
971                    s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
972                    FIX_PRECISION(adjust_precision, precision, s, s_len);
973                    if (alternate_form && i_num != 0) {
974                        *--s = *fmt;    /* 'x' or 'X' */
975                        *--s = '0';
976                        s_len += 2;
977                    }
978                    break;
979
980
981                case 's':
982                case 'v':
983                    s = va_arg(ap, char *);
984                    if (s != NULL) {
985                        s_len = strlen(s);
986                        if (adjust_precision && precision < s_len) {
987                            s_len = precision;
988                        }
989                    } else {
990                        s = S_NULL;
991                        s_len = S_NULL_LEN;
992                    }
993                    pad_char = ' ';
994                    break;
995
996
997                case 'f':
998                case 'F':
999                case 'e':
1000                case 'E':
1001                    switch(modifier) {
1002                        case LM_LONG_DOUBLE:
1003                            fp_num = (double) va_arg(ap, long double);
1004                            break;
1005                        case LM_STD:
1006                            fp_num = va_arg(ap, double);
1007                            break;
1008                        default:
1009                            goto fmt_error;
1010                    }
1011
1012                    if (zend_isnan(fp_num)) {
1013                        s = "NAN";
1014                        s_len = 3;
1015                    } else if (zend_isinf(fp_num)) {
1016                        s = "INF";
1017                        s_len = 3;
1018                    } else {
1019#ifdef HAVE_LOCALE_H
1020                        if (!lconv) {
1021                            lconv = localeconv();
1022                        }
1023#endif
1024                        s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
1025                         (adjust_precision == NO) ? FLOAT_DIGITS : precision,
1026                         (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
1027                                    &is_negative, &num_buf[1], &s_len);
1028                        if (is_negative)
1029                            prefix_char = '-';
1030                        else if (print_sign)
1031                            prefix_char = '+';
1032                        else if (print_blank)
1033                            prefix_char = ' ';
1034                    }
1035                    break;
1036
1037
1038                case 'g':
1039                case 'k':
1040                case 'G':
1041                case 'H':
1042                    switch(modifier) {
1043                        case LM_LONG_DOUBLE:
1044                            fp_num = (double) va_arg(ap, long double);
1045                            break;
1046                        case LM_STD:
1047                            fp_num = va_arg(ap, double);
1048                            break;
1049                        default:
1050                            goto fmt_error;
1051                    }
1052
1053                    if (zend_isnan(fp_num)) {
1054                        s = "NAN";
1055                        s_len = 3;
1056                        break;
1057                    } else if (zend_isinf(fp_num)) {
1058                        if (fp_num > 0) {
1059                            s = "INF";
1060                            s_len = 3;
1061                        } else {
1062                            s = "-INF";
1063                            s_len = 4;
1064                        }
1065                        break;
1066                    }
1067
1068                    if (adjust_precision == NO) {
1069                        precision = FLOAT_DIGITS;
1070                    } else if (precision == 0) {
1071                        precision = 1;
1072                    }
1073                    /*
1074                     * * We use &num_buf[ 1 ], so that we have room for the sign
1075                     */
1076#ifdef HAVE_LOCALE_H
1077                    if (!lconv) {
1078                        lconv = localeconv();
1079                    }
1080#endif
1081                    s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
1082                    if (*s == '-') {
1083                        prefix_char = *s++;
1084                    } else if (print_sign) {
1085                        prefix_char = '+';
1086                    } else if (print_blank) {
1087                        prefix_char = ' ';
1088                    }
1089
1090                    s_len = strlen(s);
1091
1092                    if (alternate_form && (strchr(s, '.')) == NULL) {
1093                        s[s_len++] = '.';
1094                    }
1095                    break;
1096
1097
1098                case 'c':
1099                    char_buf[0] = (char) (va_arg(ap, int));
1100                    s = &char_buf[0];
1101                    s_len = 1;
1102                    pad_char = ' ';
1103                    break;
1104
1105
1106                case '%':
1107                    char_buf[0] = '%';
1108                    s = &char_buf[0];
1109                    s_len = 1;
1110                    pad_char = ' ';
1111                    break;
1112
1113
1114                case 'n':
1115                    *(va_arg(ap, int *)) = cc;
1116                    goto skip_output;
1117
1118                    /*
1119                     * Always extract the argument as a "char *" pointer. We
1120                     * should be using "void *" but there are still machines
1121                     * that don't understand it.
1122                     * If the pointer size is equal to the size of an unsigned
1123                     * integer we convert the pointer to a hex number, otherwise
1124                     * we print "%p" to indicate that we don't handle "%p".
1125                     */
1126                case 'p':
1127                    if (sizeof(char *) <= sizeof(u_wide_int)) {
1128                        ui_num = (u_wide_int)((size_t) va_arg(ap, char *));
1129                        s = ap_php_conv_p2(ui_num, 4, 'x',
1130                                &num_buf[NUM_BUF_SIZE], &s_len);
1131                        if (ui_num != 0) {
1132                            *--s = 'x';
1133                            *--s = '0';
1134                            s_len += 2;
1135                        }
1136                    } else {
1137                        s = "%p";
1138                        s_len = 2;
1139                    }
1140                    pad_char = ' ';
1141                    break;
1142
1143
1144                case NUL:
1145                    /*
1146                     * The last character of the format string was %.
1147                     * We ignore it.
1148                     */
1149                    continue;
1150
1151
1152fmt_error:
1153                php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt);
1154                    /*
1155                     * The default case is for unrecognized %'s.
1156                     * We print %<char> to help the user identify what
1157                     * option is not understood.
1158                     * This is also useful in case the user wants to pass
1159                     * the output of format_converter to another function
1160                     * that understands some other %<char> (like syslog).
1161                     * Note that we can't point s inside fmt because the
1162                     * unknown <char> could be preceded by width etc.
1163                     */
1164                default:
1165                    char_buf[0] = '%';
1166                    char_buf[1] = *fmt;
1167                    s = char_buf;
1168                    s_len = 2;
1169                    pad_char = ' ';
1170                    break;
1171            }
1172
1173            if (prefix_char != NUL) {
1174                *--s = prefix_char;
1175                s_len++;
1176            }
1177            if (adjust_width && adjust == RIGHT && min_width > s_len) {
1178                if (pad_char == '0' && prefix_char != NUL) {
1179                    INS_CHAR(*s, sp, bep, cc)
1180                        s++;
1181                    s_len--;
1182                    min_width--;
1183                }
1184                PAD(min_width, s_len, pad_char);
1185            }
1186            /*
1187             * Print the string s.
1188             */
1189            for (i = s_len; i != 0; i--) {
1190                INS_CHAR(*s, sp, bep, cc);
1191                s++;
1192            }
1193
1194            if (adjust_width && adjust == LEFT && min_width > s_len)
1195                PAD(min_width, s_len, pad_char);
1196            if (free_zcopy) {
1197                zval_dtor(&zcopy);
1198            }
1199        }
1200skip_output:
1201        fmt++;
1202    }
1203    odp->nextb = sp;
1204    return (cc);
1205}
1206/* }}} */
1207
1208/*
1209 * This is the general purpose conversion function.
1210 */
1211static void strx_printv(int *ccp, char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1212{
1213    buffy od;
1214    int cc;
1215
1216    /*
1217     * First initialize the descriptor
1218     * Notice that if no length is given, we initialize buf_end to the
1219     * highest possible address.
1220     */
1221    if (len == 0) {
1222        od.buf_end = (char *) ~0;
1223        od.nextb   = (char *) ~0;
1224    } else {
1225        od.buf_end = &buf[len-1];
1226        od.nextb   = buf;
1227    }
1228
1229    /*
1230     * Do the conversion
1231     */
1232    cc = format_converter(&od, format, ap);
1233    if (len != 0 && od.nextb <= od.buf_end) {
1234        *(od.nextb) = '\0';
1235    }
1236    if (ccp) {
1237        *ccp = cc;
1238    }
1239}
1240/* }}} */
1241
1242PHPAPI int ap_php_slprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1243{
1244    unsigned int cc;
1245    va_list ap;
1246
1247    va_start(ap, format);
1248    strx_printv(&cc, buf, len, format, ap);
1249    va_end(ap);
1250    if (cc >= len) {
1251        cc = len -1;
1252        buf[cc] = '\0';
1253    }
1254    return cc;
1255}
1256/* }}} */
1257
1258PHPAPI int ap_php_vslprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1259{
1260    unsigned int cc;
1261
1262    strx_printv(&cc, buf, len, format, ap);
1263    if (cc >= len) {
1264        cc = len -1;
1265        buf[cc] = '\0';
1266    }
1267    return cc;
1268}
1269/* }}} */
1270
1271PHPAPI int ap_php_snprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1272{
1273    int cc;
1274    va_list ap;
1275
1276    va_start(ap, format);
1277    strx_printv(&cc, buf, len, format, ap);
1278    va_end(ap);
1279    return (cc);
1280}
1281/* }}} */
1282
1283PHPAPI int ap_php_vsnprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1284{
1285    int cc;
1286
1287    strx_printv(&cc, buf, len, format, ap);
1288    return (cc);
1289}
1290/* }}} */
1291
1292PHPAPI int ap_php_vasprintf(char **buf, const char *format, va_list ap) /* {{{ */
1293{
1294    va_list ap2;
1295    int cc;
1296
1297    va_copy(ap2, ap);
1298    cc = ap_php_vsnprintf(NULL, 0, format, ap2);
1299    va_end(ap2);
1300
1301    *buf = NULL;
1302
1303    if (cc >= 0) {
1304        if ((*buf = malloc(++cc)) != NULL) {
1305            if ((cc = ap_php_vsnprintf(*buf, cc, format, ap)) < 0) {
1306                free(*buf);
1307                *buf = NULL;
1308            }
1309        }
1310    }
1311
1312    return cc;
1313}
1314/* }}} */
1315
1316PHPAPI int ap_php_asprintf(char **buf, const char *format, ...) /* {{{ */
1317{
1318    int cc;
1319    va_list ap;
1320
1321    va_start(ap, format);
1322    cc = vasprintf(buf, format, ap);
1323    va_end(ap);
1324    return cc;
1325}
1326/* }}} */
1327
1328/*
1329 * Local variables:
1330 * tab-width: 4
1331 * c-basic-offset: 4
1332 * End:
1333 * vim600: sw=4 ts=4 fdm=marker
1334 * vim<600: sw=4 ts=4
1335 */
1336