Coverage Report

Created: 2025-07-23 06:33

/src/php-src/main/snprintf.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
  +----------------------------------------------------------------------+
3
  | Copyright (c) The PHP Group                                          |
4
  +----------------------------------------------------------------------+
5
  | This source file is subject to version 3.01 of the PHP license,      |
6
  | that is bundled with this package in the file LICENSE, and is        |
7
  | available through the world-wide-web at the following url:           |
8
  | https://www.php.net/license/3_01.txt                                 |
9
  | If you did not receive a copy of the PHP license and are unable to   |
10
  | obtain it through the world-wide-web, please send a note to          |
11
  | license@php.net so we can mail you a copy immediately.               |
12
  +----------------------------------------------------------------------+
13
  | Author:                                                              |
14
  +----------------------------------------------------------------------+
15
*/
16
17
#ifndef _GNU_SOURCE
18
# define _GNU_SOURCE
19
#endif
20
#include "php.h"
21
22
#include <zend_strtod.h>
23
24
#include <stddef.h>
25
#include <stdio.h>
26
#include <ctype.h>
27
#include <sys/types.h>
28
#include <stdarg.h>
29
#include <string.h>
30
#include <stdlib.h>
31
#include <math.h>
32
#include <inttypes.h>
33
34
#include <locale.h>
35
#ifdef ZTS
36
#include "ext/standard/php_string.h"
37
#define LCONV_DECIMAL_POINT (*lconv.decimal_point)
38
#else
39
0
#define LCONV_DECIMAL_POINT (*lconv->decimal_point)
40
#endif
41
42
/*
43
 * Copyright (c) 2002, 2006 Todd C. Miller <Todd.Miller@courtesan.com>
44
 *
45
 * Permission to use, copy, modify, and distribute this software for any
46
 * purpose with or without fee is hereby granted, provided that the above
47
 * copyright notice and this permission notice appear in all copies.
48
 *
49
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
50
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
51
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
52
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
53
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
54
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
55
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
56
 *
57
 * Sponsored in part by the Defense Advanced Research Projects
58
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
59
 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
60
 */
61
62
static char * __cvt(double value, int ndigit, int *decpt, bool *sign, int fmode, int pad) /* {{{ */
63
922
{
64
922
  char *s = NULL;
65
922
  char *p, *rve, c;
66
922
  size_t siz;
67
68
922
  if (ndigit < 0) {
69
0
    siz = -ndigit + 1;
70
922
  } else {
71
922
    siz = ndigit + 1;
72
922
  }
73
74
  /* __dtoa() doesn't allocate space for 0 so we do it by hand */
75
922
  if (value == 0.0) {
76
29
    *decpt = 1 - fmode; /* 1 for 'e', 0 for 'f' */
77
29
    *sign = 0;
78
29
    if ((rve = s = (char *)malloc(ndigit?siz:2)) == NULL) {
79
0
      return(NULL);
80
0
    }
81
29
    *rve++ = '0';
82
29
    *rve = '\0';
83
29
    if (!ndigit) {
84
0
      return(s);
85
0
    }
86
893
  } else {
87
893
    p = zend_dtoa(value, fmode + 2, ndigit, decpt, sign, &rve);
88
893
    if (*decpt == 9999) {
89
      /* Infinity or Nan, convert to inf or nan like printf */
90
0
      *decpt = 0;
91
0
      c = *p;
92
0
      zend_freedtoa(p);
93
0
      return strdup((c == 'I' ? "INF" : "NAN"));
94
0
    }
95
    /* Make a local copy and adjust rve to be in terms of s */
96
893
    if (pad && fmode) {
97
893
      siz += *decpt;
98
893
    }
99
893
    if ((s = (char *)malloc(siz+1)) == NULL) {
100
0
      zend_freedtoa(p);
101
0
      return(NULL);
102
0
    }
103
893
    (void) strlcpy(s, p, siz);
104
893
    rve = s + (rve - p);
105
893
    zend_freedtoa(p);
106
893
  }
107
108
  /* Add trailing zeros */
109
922
  if (pad) {
110
922
    siz -= rve - s;
111
3.30k
    while (--siz) {
112
2.38k
      *rve++ = '0';
113
2.38k
    }
114
922
    *rve = '\0';
115
922
  }
116
117
922
  return(s);
118
922
}
119
/* }}} */
120
121
static inline char *php_ecvt(double value, int ndigit, int *decpt, bool *sign) /* {{{ */
122
2
{
123
2
  return(__cvt(value, ndigit, decpt, sign, 0, 1));
124
2
}
125
/* }}} */
126
127
static inline char *php_fcvt(double value, int ndigit, int *decpt, bool *sign) /* {{{ */
128
920
{
129
920
  return(__cvt(value, ndigit, decpt, sign, 1, 1));
130
920
}
131
/* }}} */
132
133
/* {{{ Apache license */
134
/* ====================================================================
135
 * Copyright (c) 1995-1998 The Apache Group.  All rights reserved.
136
 *
137
 * Redistribution and use in source and binary forms, with or without
138
 * modification, are permitted provided that the following conditions
139
 * are met:
140
 *
141
 * 1. Redistributions of source code must retain the above copyright
142
 *    notice, this list of conditions and the following disclaimer.
143
 *
144
 * 2. Redistributions in binary form must reproduce the above copyright
145
 *    notice, this list of conditions and the following disclaimer in
146
 *    the documentation and/or other materials provided with the
147
 *    distribution.
148
 *
149
 * 3. All advertising materials mentioning features or use of this
150
 *    software must display the following acknowledgment:
151
 *    "This product includes software developed by the Apache Group
152
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
153
 *
154
 * 4. The names "Apache Server" and "Apache Group" must not be used to
155
 *    endorse or promote products derived from this software without
156
 *    prior written permission.
157
 *
158
 * 5. Redistributions of any form whatsoever must retain the following
159
 *    acknowledgment:
160
 *    "This product includes software developed by the Apache Group
161
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
162
 *
163
 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
164
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
165
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
166
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
167
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
168
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
169
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
170
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
171
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
172
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
173
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
174
 * OF THE POSSIBILITY OF SUCH DAMAGE.
175
 * ====================================================================
176
 *
177
 * This software consists of voluntary contributions made by many
178
 * individuals on behalf of the Apache Group and was originally based
179
 * on public domain software written at the National Center for
180
 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
181
 * For more information on the Apache Group and the Apache HTTP server
182
 * project, please see <http://www.apache.org/>.
183
 *
184
 * This code is based on, and used with the permission of, the
185
 * SIO stdio-replacement strx_* functions by Panos Tsirigotis
186
 * <panos@alumni.cs.colorado.edu> for xinetd.
187
 */
188
/* }}} */
189
190
1.75M
#define NUL     '\0'
191
#define INT_NULL    ((int *)0)
192
193
0
#define S_NULL      "(null)"
194
0
#define S_NULL_LEN    6
195
196
0
#define FLOAT_DIGITS    6
197
0
#define EXPONENT_LENGTH   10
198
199
200
/*
201
 * Convert num to its decimal format.
202
 * Return value:
203
 *   - a pointer to a string containing the number (no sign)
204
 *   - len contains the length of the string
205
 *   - is_negative is set to true or false depending on the sign
206
 *     of the number (always set to false if is_unsigned is true)
207
 *
208
 * The caller provides a buffer for the string: that is the buf_end argument
209
 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
210
 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
211
 */
212
/* char * ap_php_conv_10() {{{ */
213
PHPAPI char * ap_php_conv_10(int64_t num, bool is_unsigned,
214
     bool * is_negative, char *buf_end, size_t *len)
215
4.31M
{
216
4.31M
  char *p = buf_end;
217
4.31M
  uint64_t magnitude;
218
219
4.31M
  if (is_unsigned) {
220
180k
    magnitude = (uint64_t) num;
221
180k
    *is_negative = false;
222
4.13M
  } else {
223
4.13M
    *is_negative = (num < 0);
224
225
    /*
226
     * On a 2's complement machine, negating the most negative integer
227
     * results in a number that cannot be represented as a signed integer.
228
     * Here is what we do to obtain the number's magnitude:
229
     *      a. add 1 to the number
230
     *      b. negate it (becomes positive)
231
     *      c. convert it to unsigned
232
     *      d. add 1
233
     */
234
4.13M
    if (*is_negative) {
235
92.9k
      int64_t t = num + 1;
236
92.9k
      magnitude = ((uint64_t) - t) + 1;
237
4.04M
    } else {
238
4.04M
      magnitude = (uint64_t) num;
239
4.04M
    }
240
4.13M
  }
241
242
  /*
243
   * We use a do-while loop so that we write at least 1 digit
244
   */
245
12.5M
  do {
246
12.5M
    uint64_t new_magnitude = magnitude / 10;
247
248
12.5M
    *--p = (char)(magnitude - new_magnitude * 10 + '0');
249
12.5M
    magnitude = new_magnitude;
250
12.5M
  }
251
12.5M
  while (magnitude);
252
253
4.31M
  *len = buf_end - p;
254
4.31M
  return (p);
255
4.31M
}
256
/* }}} */
257
258
/* If you change this value then also change bug24640.phpt.
259
 * Also NDIG must be reasonable smaller than NUM_BUF_SIZE.
260
 */
261
1.48k
#define NDIG  320
262
263
264
/*
265
 * Convert a floating point number to a string formats 'f', 'e' or 'E'.
266
 * The result is placed in buf, and len denotes the length of the string
267
 * The sign is returned in the is_negative argument (and is not placed
268
 * in buf).
269
 */
270
/* PHPAPI char * php_conv_fp() {{{ */
271
PHPAPI char * php_conv_fp(char format, double num,
272
     bool add_dp, int precision, char dec_point, bool * is_negative, char *buf, size_t *len)
273
922
{
274
922
  char *s = buf;
275
922
  char *p, *p_orig;
276
922
  int decimal_point;
277
278
922
  if (precision >= NDIG - 1) {
279
0
    precision = NDIG - 2;
280
0
  }
281
282
922
  if (format == 'F') {
283
920
    p_orig = p = php_fcvt(num, precision, &decimal_point, is_negative);
284
920
  } else {           /* either e or E format */
285
2
    p_orig = p = php_ecvt(num, precision + 1, &decimal_point, is_negative);
286
2
  }
287
288
  /*
289
   * Check for Infinity and NaN
290
   */
291
922
  if (isalpha((int)*p)) {
292
0
    *len = strlen(p);
293
0
    memcpy(buf, p, *len + 1);
294
0
    *is_negative = false;
295
0
    free(p_orig);
296
0
    return (buf);
297
0
  }
298
922
  if (format == 'F') {
299
920
    if (decimal_point <= 0) {
300
362
      if (num != 0 || precision > 0) {
301
362
        *s++ = '0';
302
362
        if (precision > 0) {
303
362
          *s++ = dec_point;
304
933
          while (decimal_point++ < 0) {
305
571
            *s++ = '0';
306
571
          }
307
362
        } else if (add_dp) {
308
0
          *s++ = dec_point;
309
0
        }
310
362
      }
311
558
    } else {
312
558
      int addz = decimal_point >= NDIG ? decimal_point - NDIG + 1 : 0;
313
558
      decimal_point -= addz;
314
4.07k
      while (decimal_point-- > 0) {
315
3.51k
        *s++ = *p++;
316
3.51k
      }
317
558
      while (addz-- > 0) {
318
0
        *s++ = '0';
319
0
      }
320
558
      if (precision > 0 || add_dp) {
321
558
        *s++ = dec_point;
322
558
      }
323
558
    }
324
920
  } else {
325
2
    *s++ = *p++;
326
2
    if (precision > 0 || add_dp) {
327
2
      *s++ = '.';
328
2
    }
329
2
  }
330
331
  /*
332
   * copy the rest of p, the NUL is NOT copied
333
   */
334
6.03k
  while (*p) {
335
5.10k
    *s++ = *p++;
336
5.10k
  }
337
338
922
  if (format != 'F') {
339
2
    char temp[EXPONENT_LENGTH];   /* for exponent conversion */
340
2
    size_t t_len;
341
2
    bool exponent_is_negative;
342
343
2
    *s++ = format;      /* either e or E */
344
2
    decimal_point--;
345
2
    if (decimal_point != 0) {
346
0
      p = ap_php_conv_10((int64_t) decimal_point, false, &exponent_is_negative, &temp[EXPONENT_LENGTH], &t_len);
347
0
      *s++ = exponent_is_negative ? '-' : '+';
348
349
      /*
350
       * Make sure the exponent has at least 2 digits
351
       */
352
0
      while (t_len--) {
353
0
        *s++ = *p++;
354
0
      }
355
2
    } else {
356
2
      *s++ = '+';
357
2
      *s++ = '0';
358
2
    }
359
2
  }
360
922
  *len = s - buf;
361
922
  free(p_orig);
362
922
  return (buf);
363
922
}
364
/* }}} */
365
366
/*
367
 * Convert num to a base X number where X is a power of 2. nbits determines X.
368
 * For example, if nbits is 3, we do base 8 conversion
369
 * Return value:
370
 *      a pointer to a string containing the number
371
 *
372
 * The caller provides a buffer for the string: that is the buf_end argument
373
 * which is a pointer to the END of the buffer + 1 (i.e. if the buffer
374
 * is declared as buf[ 100 ], buf_end should be &buf[ 100 ])
375
 */
376
PHPAPI char * ap_php_conv_p2(uint64_t num, int nbits, char format, char *buf_end, size_t *len) /* {{{ */
377
134k
{
378
134k
  int mask = (1 << nbits) - 1;
379
134k
  char *p = buf_end;
380
134k
  static const char low_digits[] = "0123456789abcdef";
381
134k
  static const char upper_digits[] = "0123456789ABCDEF";
382
134k
  const char *digits = (format == 'X') ? upper_digits : low_digits;
383
384
452k
  do {
385
452k
    *--p = digits[num & mask];
386
452k
    num >>= nbits;
387
452k
  }
388
452k
  while (num);
389
390
134k
  *len = buf_end - p;
391
134k
  return (p);
392
134k
}
393
/* }}} */
394
395
/*
396
 * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
397
 *
398
 * XXX: this is a magic number; do not decrease it
399
 * Emax = 1023
400
 * NDIG = 320
401
 * NUM_BUF_SIZE >= strlen("-") + Emax + strlen(".") + NDIG + strlen("E+1023") + 1;
402
 */
403
711k
#define NUM_BUF_SIZE    2048
404
405
406
/*
407
 * Descriptor for buffer area
408
 */
409
struct buf_area {
410
  char *buf_end;
411
  char *nextb;        /* pointer to next byte to read/write   */
412
};
413
414
typedef struct buf_area buffy;
415
416
/*
417
 * The INS_CHAR macro inserts a character in the buffer and writes
418
 * the buffer back to disk if necessary
419
 * It uses the char pointers sp and bep:
420
 *      sp points to the next available character in the buffer
421
 *      bep points to the end-of-buffer+1
422
 * While using this macro, note that the nextb pointer is NOT updated.
423
 *
424
 * NOTE: Evaluation of the c argument should not have any side effects
425
 */
426
#define INS_CHAR(c, sp, bep, cc) \
427
6.79M
  {                            \
428
6.79M
    if (sp < bep)            \
429
6.79M
    {                        \
430
6.79M
      *sp++ = c;           \
431
6.79M
    }                        \
432
6.79M
    cc++;                    \
433
6.79M
  }
434
435
206k
#define NUM( c )      ( c - '0' )
436
437
#define STR_TO_DEC( str, num )    \
438
206k
    num = NUM( *str++ ) ;    \
439
206k
    while ( isdigit((int)*str ) )   \
440
206k
    {         \
441
0
  num *= 10 ;     \
442
0
  num += NUM( *str++ ) ;    \
443
0
    }
444
445
/*
446
 * This macro does zero padding so that the precision
447
 * requirement is satisfied. The padding is done by
448
 * adding '0's to the left of the string that is going
449
 * to be printed.
450
 */
451
#define FIX_PRECISION( adjust, precision, s, s_len )  \
452
711k
  if ( adjust )            \
453
711k
  while ( s_len < (size_t)precision )  \
454
0
  {                 \
455
0
      *--s = '0' ;          \
456
0
      s_len++ ;           \
457
0
  }
458
459
/*
460
 * Macro that does padding. The padding is done by printing
461
 * the character ch.
462
 */
463
126k
#define PAD( width, len, ch ) do    \
464
170k
  {         \
465
170k
      INS_CHAR( ch, sp, bep, cc ) ; \
466
170k
      width-- ;       \
467
170k
  }          \
468
170k
  while ( (size_t)width > len )
469
470
/*
471
 * Do format conversion placing the output in buffer
472
 */
473
static size_t format_converter(buffy * odp, const char *fmt, va_list ap) /* {{{ */
474
579k
{
475
579k
  char *sp;
476
579k
  char *bep;
477
579k
  size_t cc = 0;
478
579k
  size_t i;
479
480
579k
  char *s = NULL;
481
579k
  size_t s_len;
482
483
579k
  int min_width = 0;
484
579k
  int precision = 0;
485
579k
  enum {
486
579k
    LEFT, RIGHT
487
579k
  } adjust;
488
579k
  char pad_char;
489
579k
  char prefix_char;
490
491
579k
  double fp_num;
492
579k
  int64_t i_num = (int64_t) 0;
493
579k
  uint64_t ui_num;
494
495
579k
  char num_buf[NUM_BUF_SIZE];
496
579k
  char char_buf[2];     /* for printing %% and %<unknown> */
497
498
#ifdef ZTS
499
  struct lconv lconv;
500
#else
501
579k
  struct lconv *lconv = NULL;
502
579k
#endif
503
504
  /*
505
   * Flag variables
506
   */
507
579k
  length_modifier_e modifier;
508
579k
  bool alternate_form;
509
579k
  bool print_sign;
510
579k
  bool print_blank;
511
579k
  bool adjust_precision;
512
579k
  bool adjust_width;
513
579k
  bool is_negative;
514
515
579k
  sp = odp->nextb;
516
579k
  bep = odp->buf_end;
517
518
5.31M
  while (*fmt) {
519
4.73M
    if (*fmt != '%') {
520
3.92M
      INS_CHAR(*fmt, sp, bep, cc);
521
3.92M
    } else {
522
      /*
523
       * Default variable settings
524
       */
525
814k
      zend_string *tmp_str = NULL;
526
814k
      adjust = RIGHT;
527
814k
      alternate_form = print_sign = print_blank = false;
528
814k
      pad_char = ' ';
529
814k
      prefix_char = NUL;
530
531
814k
      fmt++;
532
533
      /*
534
       * Try to avoid checking for flags, width or precision
535
       */
536
814k
      if (isascii((int)*fmt) && !islower((int)*fmt)) {
537
        /*
538
         * Recognize flags: -, #, BLANK, +
539
         */
540
398k
        for (;; fmt++) {
541
398k
          if (*fmt == '-')
542
0
            adjust = LEFT;
543
398k
          else if (*fmt == '+')
544
0
            print_sign = true;
545
398k
          else if (*fmt == '#')
546
0
            alternate_form = true;
547
398k
          else if (*fmt == ' ')
548
0
            print_blank = true;
549
398k
          else if (*fmt == '0')
550
192k
            pad_char = '0';
551
206k
          else
552
206k
            break;
553
398k
        }
554
555
        /*
556
         * Check if a width was specified
557
         */
558
206k
        if (isdigit((int)*fmt)) {
559
206k
          STR_TO_DEC(fmt, min_width);
560
206k
          adjust_width = true;
561
206k
        } else if (*fmt == '*') {
562
0
          min_width = va_arg(ap, int);
563
0
          fmt++;
564
0
          adjust_width = true;
565
0
          if (min_width < 0) {
566
0
            adjust = LEFT;
567
0
            min_width = -min_width;
568
0
          }
569
0
        } else
570
0
          adjust_width = false;
571
572
        /*
573
         * Check if a precision was specified
574
         */
575
206k
        if (*fmt == '.') {
576
0
          adjust_precision = true;
577
0
          fmt++;
578
0
          if (isdigit((int)*fmt)) {
579
0
            STR_TO_DEC(fmt, precision);
580
0
          } else if (*fmt == '*') {
581
0
            precision = va_arg(ap, int);
582
0
            fmt++;
583
0
            if (precision < -1)
584
0
              precision = -1;
585
0
          } else
586
0
            precision = 0;
587
0
        } else
588
206k
          adjust_precision = false;
589
206k
      } else
590
607k
        adjust_precision = adjust_width = false;
591
592
      /*
593
       * Modifier check
594
       */
595
814k
      switch (*fmt) {
596
0
        case 'L':
597
0
          fmt++;
598
0
          modifier = LM_LONG_DOUBLE;
599
0
          break;
600
25.2k
        case 'l':
601
25.2k
          fmt++;
602
25.2k
#if SIZEOF_LONG_LONG
603
25.2k
          if (*fmt == 'l') {
604
4.15k
            fmt++;
605
4.15k
            modifier = LM_LONG_LONG;
606
4.15k
          } else
607
21.0k
#endif
608
21.0k
            modifier = LM_LONG;
609
25.2k
          break;
610
44
        case 'z':
611
44
          fmt++;
612
44
          modifier = LM_SIZE_T;
613
44
          break;
614
0
        case 'j':
615
0
          fmt++;
616
0
          modifier = LM_INTMAX_T;
617
0
          break;
618
0
        case 't':
619
0
          fmt++;
620
0
          modifier = LM_PTRDIFF_T;
621
0
          break;
622
0
        case 'p':
623
0
        {
624
0
          char __next = *(fmt+1);
625
0
          if ('d' == __next || 'u' == __next || 'x' == __next || 'o' == __next) {
626
0
            zend_error_noreturn(E_CORE_ERROR,
627
0
              "printf \"p\" modifier is no longer supported, use ZEND_LONG_FMT");
628
0
          }
629
0
          modifier = LM_STD;
630
0
          break;
631
0
        }
632
0
        case 'h':
633
0
          fmt++;
634
0
          if (*fmt == 'h') {
635
0
            fmt++;
636
0
          }
637
          /* these are promoted to int, so no break */
638
0
          ZEND_FALLTHROUGH;
639
788k
        default:
640
788k
          modifier = LM_STD;
641
788k
          break;
642
814k
      }
643
644
      /*
645
       * Argument extraction and printing.
646
       * First we determine the argument type.
647
       * Then, we convert the argument to a string.
648
       * On exit from the switch, s points to the string that
649
       * must be printed, s_len has the length of the string
650
       * The precision requirements, if any, are reflected in s_len.
651
       *
652
       * NOTE: pad_char may be set to '0' because of the 0 flag.
653
       *   It is reset to ' ' by non-numeric formats
654
       */
655
814k
      switch (*fmt) {
656
0
        case 'Z': {
657
0
          zval *zvp = va_arg(ap, zval*);
658
0
          zend_string *str = zval_get_tmp_string(zvp, &tmp_str);
659
0
          s_len = ZSTR_LEN(str);
660
0
          s = ZSTR_VAL(str);
661
0
          if (adjust_precision && (size_t)precision < s_len) {
662
0
            s_len = precision;
663
0
          }
664
0
          break;
665
0
        }
666
22.5k
        case 'u':
667
22.5k
          switch(modifier) {
668
22.4k
            default:
669
22.4k
              i_num = (int64_t) va_arg(ap, unsigned int);
670
22.4k
              break;
671
0
            case LM_LONG_DOUBLE:
672
0
              goto fmt_error;
673
55
            case LM_LONG:
674
55
              i_num = (int64_t) va_arg(ap, unsigned long int);
675
55
              break;
676
44
            case LM_SIZE_T:
677
44
              i_num = (int64_t) va_arg(ap, size_t);
678
44
              break;
679
0
#if SIZEOF_LONG_LONG
680
0
            case LM_LONG_LONG:
681
0
              i_num = (int64_t) va_arg(ap, unsigned long long int);
682
0
              break;
683
0
#endif
684
0
            case LM_INTMAX_T:
685
0
              i_num = (int64_t) va_arg(ap, uintmax_t);
686
0
              break;
687
0
            case LM_PTRDIFF_T:
688
0
              i_num = (int64_t) va_arg(ap, ptrdiff_t);
689
0
              break;
690
22.5k
          }
691
          /*
692
           * The rest also applies to other integer formats, so fall
693
           * into that case.
694
           */
695
22.5k
          ZEND_FALLTHROUGH;
696
468k
        case 'd':
697
661k
        case 'i':
698
          /*
699
           * Get the arg if we haven't already.
700
           */
701
661k
          if ((*fmt) != 'u') {
702
639k
            switch(modifier) {
703
614k
              default:
704
614k
                i_num = (int64_t) va_arg(ap, int);
705
614k
                break;
706
0
              case LM_LONG_DOUBLE:
707
0
                goto fmt_error;
708
21.0k
              case LM_LONG:
709
21.0k
                i_num = (int64_t) va_arg(ap, long int);
710
21.0k
                break;
711
0
              case LM_SIZE_T:
712
0
                i_num = (int64_t) va_arg(ap, ssize_t);
713
0
                break;
714
0
#if SIZEOF_LONG_LONG
715
4.15k
              case LM_LONG_LONG:
716
4.15k
                i_num = (int64_t) va_arg(ap, long long int);
717
4.15k
                break;
718
0
#endif
719
0
              case LM_INTMAX_T:
720
0
                i_num = (int64_t) va_arg(ap, intmax_t);
721
0
                break;
722
0
              case LM_PTRDIFF_T:
723
0
                i_num = (int64_t) va_arg(ap, ptrdiff_t);
724
0
                break;
725
639k
            }
726
639k
          }
727
661k
          s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
728
661k
                &num_buf[NUM_BUF_SIZE], &s_len);
729
661k
          FIX_PRECISION(adjust_precision, precision, s, s_len);
730
731
661k
          if (*fmt != 'u') {
732
639k
            if (is_negative) {
733
45.4k
              prefix_char = '-';
734
593k
            } else if (print_sign) {
735
0
              prefix_char = '+';
736
593k
            } else if (print_blank) {
737
0
              prefix_char = ' ';
738
0
            }
739
639k
          }
740
661k
          break;
741
742
743
0
        case 'o':
744
0
          switch(modifier) {
745
0
            default:
746
0
              ui_num = (uint64_t) va_arg(ap, unsigned int);
747
0
              break;
748
0
            case LM_LONG_DOUBLE:
749
0
              goto fmt_error;
750
0
            case LM_LONG:
751
0
              ui_num = (uint64_t) va_arg(ap, unsigned long int);
752
0
              break;
753
0
            case LM_SIZE_T:
754
0
              ui_num = (uint64_t) va_arg(ap, size_t);
755
0
              break;
756
0
#if SIZEOF_LONG_LONG
757
0
            case LM_LONG_LONG:
758
0
              ui_num = (uint64_t) va_arg(ap, unsigned long long int);
759
0
              break;
760
0
#endif
761
0
            case LM_INTMAX_T:
762
0
              ui_num = (uint64_t) va_arg(ap, uintmax_t);
763
0
              break;
764
0
            case LM_PTRDIFF_T:
765
0
              ui_num = (uint64_t) va_arg(ap, ptrdiff_t);
766
0
              break;
767
0
          }
768
0
          s = ap_php_conv_p2(ui_num, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
769
0
          FIX_PRECISION(adjust_precision, precision, s, s_len);
770
0
          if (alternate_form && *s != '0') {
771
0
            *--s = '0';
772
0
            s_len++;
773
0
          }
774
0
          break;
775
776
777
0
        case 'x':
778
49.5k
        case 'X':
779
49.5k
          switch(modifier) {
780
49.5k
            default:
781
49.5k
              ui_num = (uint64_t) va_arg(ap, unsigned int);
782
49.5k
              break;
783
0
            case LM_LONG_DOUBLE:
784
0
              goto fmt_error;
785
0
            case LM_LONG:
786
0
              ui_num = (uint64_t) va_arg(ap, unsigned long int);
787
0
              break;
788
0
            case LM_SIZE_T:
789
0
              ui_num = (uint64_t) va_arg(ap, size_t);
790
0
              break;
791
0
#if SIZEOF_LONG_LONG
792
0
            case LM_LONG_LONG:
793
0
              ui_num = (uint64_t) va_arg(ap, unsigned long long int);
794
0
              break;
795
0
#endif
796
0
            case LM_INTMAX_T:
797
0
              ui_num = (uint64_t) va_arg(ap, uintmax_t);
798
0
              break;
799
0
            case LM_PTRDIFF_T:
800
0
              ui_num = (uint64_t) va_arg(ap, ptrdiff_t);
801
0
              break;
802
49.5k
          }
803
49.5k
          s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
804
49.5k
          FIX_PRECISION(adjust_precision, precision, s, s_len);
805
49.5k
          if (alternate_form && i_num != 0) {
806
0
            *--s = *fmt;  /* 'x' or 'X' */
807
0
            *--s = '0';
808
0
            s_len += 2;
809
0
          }
810
49.5k
          break;
811
812
813
85.1k
        case 's':
814
85.1k
          s = va_arg(ap, char *);
815
85.1k
          if (s != NULL) {
816
85.1k
            s_len = strlen(s);
817
85.1k
            if (adjust_precision && (size_t)precision < s_len) {
818
0
              s_len = precision;
819
0
            }
820
85.1k
          } else {
821
0
            s = S_NULL;
822
0
            s_len = S_NULL_LEN;
823
0
          }
824
85.1k
          pad_char = ' ';
825
85.1k
          break;
826
827
828
0
        case 'f':
829
0
        case 'F':
830
0
        case 'e':
831
0
        case 'E':
832
0
          switch(modifier) {
833
0
            case LM_LONG_DOUBLE:
834
0
              fp_num = (double) va_arg(ap, long double);
835
0
              break;
836
0
            case LM_STD:
837
0
              fp_num = va_arg(ap, double);
838
0
              break;
839
0
            default:
840
0
              goto fmt_error;
841
0
          }
842
843
0
          if (zend_isnan(fp_num)) {
844
0
            s = "NAN";
845
0
            s_len = 3;
846
0
          } else if (zend_isinf(fp_num)) {
847
0
            s = "INF";
848
0
            s_len = 3;
849
0
          } else {
850
#ifdef ZTS
851
            localeconv_r(&lconv);
852
#else
853
0
            if (!lconv) {
854
0
              lconv = localeconv();
855
0
            }
856
0
#endif
857
0
            s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
858
0
             (adjust_precision == false) ? FLOAT_DIGITS : precision,
859
0
             (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
860
0
                  &is_negative, &num_buf[1], &s_len);
861
0
            if (is_negative)
862
0
              prefix_char = '-';
863
0
            else if (print_sign)
864
0
              prefix_char = '+';
865
0
            else if (print_blank)
866
0
              prefix_char = ' ';
867
0
          }
868
0
          break;
869
870
871
0
        case 'g':
872
0
        case 'k':
873
0
        case 'G':
874
0
        case 'H':
875
0
          switch(modifier) {
876
0
            case LM_LONG_DOUBLE:
877
0
              fp_num = (double) va_arg(ap, long double);
878
0
              break;
879
0
            case LM_STD:
880
0
              fp_num = va_arg(ap, double);
881
0
              break;
882
0
            default:
883
0
              goto fmt_error;
884
0
          }
885
886
0
          if (zend_isnan(fp_num)) {
887
0
            s = "NAN";
888
0
            s_len = 3;
889
0
            break;
890
0
          } else if (zend_isinf(fp_num)) {
891
0
            if (fp_num > 0) {
892
0
              s = "INF";
893
0
              s_len = 3;
894
0
            } else {
895
0
              s = "-INF";
896
0
              s_len = 4;
897
0
            }
898
0
            break;
899
0
          }
900
901
0
          if (adjust_precision == false) {
902
0
            precision = FLOAT_DIGITS;
903
0
          } else if (precision == 0) {
904
0
            precision = 1;
905
0
          }
906
          /*
907
           * * We use &num_buf[ 1 ], so that we have room for the sign
908
           */
909
#ifdef ZTS
910
          localeconv_r(&lconv);
911
#else
912
0
          if (!lconv) {
913
0
            lconv = localeconv();
914
0
          }
915
0
#endif
916
0
          s = zend_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
917
0
          if (*s == '-') {
918
0
            prefix_char = *s++;
919
0
          } else if (print_sign) {
920
0
            prefix_char = '+';
921
0
          } else if (print_blank) {
922
0
            prefix_char = ' ';
923
0
          }
924
925
0
          s_len = strlen(s);
926
927
0
          if (alternate_form && (strchr(s, '.')) == NULL) {
928
0
            s[s_len++] = '.';
929
0
          }
930
0
          break;
931
932
933
17.6k
        case 'c':
934
17.6k
          char_buf[0] = (char) (va_arg(ap, int));
935
17.6k
          s = &char_buf[0];
936
17.6k
          s_len = 1;
937
17.6k
          pad_char = ' ';
938
17.6k
          break;
939
940
941
0
        case '%':
942
0
          char_buf[0] = '%';
943
0
          s = &char_buf[0];
944
0
          s_len = 1;
945
0
          pad_char = ' ';
946
0
          break;
947
948
949
0
        case 'n':
950
0
          *(va_arg(ap, int *)) = cc;
951
0
          goto skip_output;
952
953
          /*
954
           * Always extract the argument as a "char *" pointer. We
955
           * should be using "void *" but there are still machines
956
           * that don't understand it.
957
           * If the pointer size is equal to the size of an unsigned
958
           * integer we convert the pointer to a hex number, otherwise
959
           * we print "%p" to indicate that we don't handle "%p".
960
           */
961
0
        case 'p':
962
0
          if (sizeof(char *) <= sizeof(uint64_t)) {
963
0
            ui_num = (uint64_t)((size_t) va_arg(ap, char *));
964
0
            s = ap_php_conv_p2(ui_num, 4, 'x',
965
0
                &num_buf[NUM_BUF_SIZE], &s_len);
966
0
            if (ui_num != 0) {
967
0
              *--s = 'x';
968
0
              *--s = '0';
969
0
              s_len += 2;
970
0
            }
971
0
          } else {
972
0
            s = "%p";
973
0
            s_len = 2;
974
0
          }
975
0
          pad_char = ' ';
976
0
          break;
977
978
979
0
        case NUL:
980
          /*
981
           * The last character of the format string was %.
982
           * We ignore it.
983
           */
984
0
          continue;
985
986
987
0
fmt_error:
988
0
        php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt);
989
          /*
990
           * The default case is for unrecognized %'s.
991
           * We print %<char> to help the user identify what
992
           * option is not understood.
993
           * This is also useful in case the user wants to pass
994
           * the output of format_converter to another function
995
           * that understands some other %<char> (like syslog).
996
           * Note that we can't point s inside fmt because the
997
           * unknown <char> could be preceded by width etc.
998
           */
999
0
          ZEND_FALLTHROUGH;
1000
0
        default:
1001
0
          char_buf[0] = '%';
1002
0
          char_buf[1] = *fmt;
1003
0
          s = char_buf;
1004
0
          s_len = 2;
1005
0
          pad_char = ' ';
1006
0
          break;
1007
814k
      }
1008
1009
814k
      if (prefix_char != NUL) {
1010
45.4k
        *--s = prefix_char;
1011
45.4k
        s_len++;
1012
45.4k
      }
1013
814k
      if (adjust_width && adjust == RIGHT && (size_t)min_width > s_len) {
1014
126k
        if (pad_char == '0' && prefix_char != NUL) {
1015
0
          INS_CHAR(*s, sp, bep, cc)
1016
0
            s++;
1017
0
          s_len--;
1018
0
          min_width--;
1019
0
        }
1020
126k
        PAD(min_width, s_len, pad_char);
1021
126k
      }
1022
      /*
1023
       * Print the string s.
1024
       */
1025
3.51M
      for (i = s_len; i != 0; i--) {
1026
2.70M
        INS_CHAR(*s, sp, bep, cc);
1027
2.70M
        s++;
1028
2.70M
      }
1029
1030
814k
      if (adjust_width && adjust == LEFT && (size_t)min_width > s_len)
1031
0
        PAD(min_width, s_len, pad_char);
1032
814k
      zend_tmp_string_release(tmp_str);
1033
814k
    }
1034
4.73M
skip_output:
1035
4.73M
    fmt++;
1036
4.73M
  }
1037
579k
  odp->nextb = sp;
1038
579k
  return (cc);
1039
579k
}
1040
/* }}} */
1041
1042
/*
1043
 * This is the general purpose conversion function.
1044
 */
1045
static size_t strx_printv(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1046
579k
{
1047
579k
  buffy od;
1048
579k
  size_t cc;
1049
1050
  /*
1051
   * First initialize the descriptor
1052
   * Notice that if no length is given, we initialize buf_end to the
1053
   * highest possible address.
1054
   */
1055
579k
  if (len == 0) {
1056
0
    od.buf_end = (char *) ~0;
1057
0
    od.nextb   = (char *) ~0;
1058
579k
  } else {
1059
579k
    od.buf_end = &buf[len-1];
1060
579k
    od.nextb   = buf;
1061
579k
  }
1062
1063
  /*
1064
   * Do the conversion
1065
   */
1066
579k
  cc = format_converter(&od, format, ap);
1067
579k
  if (len != 0 && od.nextb <= od.buf_end) {
1068
579k
    *(od.nextb) = '\0';
1069
579k
  }
1070
579k
  return cc;
1071
579k
}
1072
/* }}} */
1073
1074
PHPAPI int ap_php_slprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1075
407k
{
1076
407k
  size_t cc;
1077
407k
  va_list ap;
1078
1079
407k
  va_start(ap, format);
1080
407k
  cc = strx_printv(buf, len, format, ap);
1081
407k
  va_end(ap);
1082
407k
  if (cc >= len) {
1083
0
    cc = len -1;
1084
0
    buf[cc] = '\0';
1085
0
  }
1086
407k
  return (int) cc;
1087
407k
}
1088
/* }}} */
1089
1090
PHPAPI int ap_php_vslprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1091
0
{
1092
0
  size_t cc = strx_printv(buf, len, format, ap);
1093
0
  if (cc >= len) {
1094
0
    cc = len -1;
1095
0
    buf[cc] = '\0';
1096
0
  }
1097
0
  return (int) cc;
1098
0
}
1099
/* }}} */
1100
1101
PHPAPI int ap_php_snprintf(char *buf, size_t len, const char *format,...) /* {{{ */
1102
171k
{
1103
171k
  size_t cc;
1104
171k
  va_list ap;
1105
1106
171k
  va_start(ap, format);
1107
171k
  cc = strx_printv(buf, len, format, ap);
1108
171k
  va_end(ap);
1109
171k
  return (int) cc;
1110
171k
}
1111
/* }}} */
1112
1113
PHPAPI int ap_php_vsnprintf(char *buf, size_t len, const char *format, va_list ap) /* {{{ */
1114
0
{
1115
0
  size_t cc = strx_printv(buf, len, format, ap);
1116
0
  return (int) cc;
1117
0
}
1118
/* }}} */
1119
1120
PHPAPI int ap_php_vasprintf(char **buf, const char *format, va_list ap) /* {{{ */
1121
0
{
1122
0
  va_list ap2;
1123
0
  int cc;
1124
1125
0
  va_copy(ap2, ap);
1126
0
  cc = ap_php_vsnprintf(NULL, 0, format, ap2);
1127
0
  va_end(ap2);
1128
1129
0
  *buf = NULL;
1130
1131
0
  if (cc >= 0) {
1132
0
    if ((*buf = malloc(++cc)) != NULL) {
1133
0
      if ((cc = ap_php_vsnprintf(*buf, cc, format, ap)) < 0) {
1134
0
        free(*buf);
1135
0
        *buf = NULL;
1136
0
      }
1137
0
    }
1138
0
  }
1139
1140
0
  return cc;
1141
0
}
1142
/* }}} */
1143
1144
PHPAPI int ap_php_asprintf(char **buf, const char *format, ...) /* {{{ */
1145
0
{
1146
0
  int cc;
1147
0
  va_list ap;
1148
1149
0
  va_start(ap, format);
1150
0
  cc = vasprintf(buf, format, ap);
1151
0
  va_end(ap);
1152
0
  return cc;
1153
0
}
1154
/* }}} */