Coverage Report

Created: 2025-12-14 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/php-src/ext/json/json_encoder.c
Line
Count
Source
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: Omar Kilani <omar@php.net>                                   |
14
  |         Jakub Zelenka <bukka@php.net>                                |
15
  +----------------------------------------------------------------------+
16
*/
17
18
#ifdef HAVE_CONFIG_H
19
#include <config.h>
20
#endif
21
22
#include "php.h"
23
#include "ext/standard/html.h"
24
#include "zend_smart_str.h"
25
#include "php_json.h"
26
#include "php_json_encoder.h"
27
#include "zend_portability.h"
28
#include <zend_exceptions.h>
29
#include "zend_enum.h"
30
#include "zend_property_hooks.h"
31
#include "zend_lazy_objects.h"
32
33
static const char digits[] = "0123456789abcdef";
34
35
static zend_always_inline bool php_json_check_stack_limit(void)
36
2
{
37
2
#ifdef ZEND_CHECK_STACK_LIMIT
38
2
  return zend_call_stack_overflowed(EG(stack_limit));
39
#else
40
  return false;
41
#endif
42
2
}
43
44
/* {{{ Pretty printing support functions */
45
46
static inline void php_json_pretty_print_char(smart_str *buf, int options, char c) /* {{{ */
47
8
{
48
8
  if (options & PHP_JSON_PRETTY_PRINT) {
49
0
    smart_str_appendc(buf, c);
50
0
  }
51
8
}
52
/* }}} */
53
54
static inline void php_json_pretty_print_indent(smart_str *buf, int options, const php_json_encoder *encoder) /* {{{ */
55
5
{
56
5
  if (options & PHP_JSON_PRETTY_PRINT) {
57
0
    for (int i = 0; i < encoder->depth; ++i) {
58
0
      smart_str_appendl(buf, "    ", 4);
59
0
    }
60
0
  }
61
5
}
62
/* }}} */
63
64
/* }}} */
65
66
static
67
#if defined(_MSC_VER) && defined(_M_ARM64)
68
// MSVC bug: https://developercommunity.visualstudio.com/t/corrupt-optimization-on-arm64-with-Ox-/10102551
69
zend_never_inline
70
#else
71
inline
72
#endif
73
bool php_json_is_valid_double(double d) /* {{{ */
74
0
{
75
0
  return !zend_isinf(d) && !zend_isnan(d);
76
0
}
77
/* }}} */
78
79
static inline void php_json_encode_double(smart_str *buf, double d, int options) /* {{{ */
80
0
{
81
0
  size_t len;
82
0
  char num[ZEND_DOUBLE_MAX_LENGTH];
83
84
0
  zend_gcvt(d, (int)PG(serialize_precision), '.', 'e', num);
85
0
  len = strlen(num);
86
0
  if (options & PHP_JSON_PRESERVE_ZERO_FRACTION && strchr(num, '.') == NULL && len < ZEND_DOUBLE_MAX_LENGTH - 2) {
87
0
    num[len++] = '.';
88
0
    num[len++] = '0';
89
0
    num[len] = '\0';
90
0
  }
91
0
  smart_str_appendl(buf, num, len);
92
0
}
93
/* }}} */
94
95
#define PHP_JSON_HASH_PROTECT_RECURSION(_tmp_ht) \
96
2
  do { \
97
2
    if (_tmp_ht) { \
98
2
      GC_TRY_PROTECT_RECURSION(_tmp_ht); \
99
2
    } \
100
2
  } while (0)
101
102
#define PHP_JSON_HASH_UNPROTECT_RECURSION(_tmp_ht) \
103
2
  do { \
104
2
    if (_tmp_ht) { \
105
2
      GC_TRY_UNPROTECT_RECURSION(_tmp_ht); \
106
2
    } \
107
2
  } while (0)
108
109
static zend_result php_json_encode_array(smart_str *buf, zval *val, int options, php_json_encoder *encoder) /* {{{ */
110
2
{
111
2
  bool encode_as_object = options & PHP_JSON_FORCE_OBJECT;
112
2
  HashTable *myht, *prop_ht;
113
2
  zend_refcounted *recursion_rc;
114
115
2
  if (php_json_check_stack_limit()) {
116
0
    encoder->error_code = PHP_JSON_ERROR_DEPTH;
117
0
    if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
118
0
      smart_str_appendl(buf, "null", 4);
119
0
    }
120
0
    return FAILURE;
121
0
  }
122
123
2
  if (Z_TYPE_P(val) == IS_ARRAY) {
124
0
    myht = Z_ARRVAL_P(val);
125
0
    recursion_rc = (zend_refcounted *)myht;
126
0
    prop_ht = NULL;
127
0
    encode_as_object = encode_as_object || !zend_array_is_list(myht);
128
2
  } else if (Z_OBJ_P(val)->properties == NULL
129
0
   && Z_OBJ_HT_P(val)->get_properties_for == NULL
130
0
   && Z_OBJ_HT_P(val)->get_properties == zend_std_get_properties
131
0
   && Z_OBJ_P(val)->ce->num_hooked_props == 0
132
0
   && !zend_object_is_lazy(Z_OBJ_P(val))) {
133
    /* Optimized version without rebuilding properties HashTable */
134
0
    zend_object *obj = Z_OBJ_P(val);
135
0
    const zend_class_entry *ce = obj->ce;
136
137
0
    if (GC_IS_RECURSIVE(obj)) {
138
0
      encoder->error_code = PHP_JSON_ERROR_RECURSION;
139
0
      smart_str_appendl(buf, "null", 4);
140
0
      return FAILURE;
141
0
    }
142
143
0
    PHP_JSON_HASH_PROTECT_RECURSION(obj);
144
145
0
    smart_str_appendc(buf, '{');
146
147
0
    ++encoder->depth;
148
149
0
    for (int i = 0; i < ce->default_properties_count; i++) {
150
0
      zend_property_info *prop_info = ce->properties_info_table[i];
151
0
      if (!prop_info) {
152
0
        continue;
153
0
      }
154
0
      if (ZSTR_VAL(prop_info->name)[0] == '\0' && ZSTR_LEN(prop_info->name) > 0) {
155
        /* Skip protected and private members. */
156
0
        continue;
157
0
      }
158
0
      zval *prop = OBJ_PROP(obj, prop_info->offset);
159
0
      if (Z_TYPE_P(prop) == IS_UNDEF) {
160
0
        continue;
161
0
      }
162
163
0
      php_json_pretty_print_char(buf, options, '\n');
164
0
      php_json_pretty_print_indent(buf, options, encoder);
165
166
0
      if (php_json_escape_string(buf, ZSTR_VAL(prop_info->name), ZSTR_LEN(prop_info->name),
167
0
          options & ~PHP_JSON_NUMERIC_CHECK, encoder) == FAILURE &&
168
0
          (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) &&
169
0
          buf->s) {
170
0
        ZSTR_LEN(buf->s) -= 4;
171
0
        smart_str_appendl(buf, "\"\"", 2);
172
0
      }
173
174
0
      smart_str_appendc(buf, ':');
175
0
      php_json_pretty_print_char(buf, options, ' ');
176
177
0
      if (php_json_encode_zval(buf, prop, options, encoder) == FAILURE &&
178
0
          !(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
179
0
        PHP_JSON_HASH_UNPROTECT_RECURSION(obj);
180
0
        return FAILURE;
181
0
      }
182
183
0
      smart_str_appendc(buf, ',');
184
0
    }
185
186
0
    bool empty = ZSTR_VAL(buf->s)[ZSTR_LEN(buf->s) - 1] != ',';
187
0
    if (!empty) {
188
      /* Drop the trailing comma. */
189
0
      ZSTR_LEN(buf->s)--;
190
0
    }
191
192
0
    PHP_JSON_HASH_UNPROTECT_RECURSION(obj);
193
0
    if (encoder->depth > encoder->max_depth) {
194
0
      encoder->error_code = PHP_JSON_ERROR_DEPTH;
195
0
      if (!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
196
0
        return FAILURE;
197
0
      }
198
0
    }
199
0
    --encoder->depth;
200
201
0
    if (!empty) {
202
0
      php_json_pretty_print_char(buf, options, '\n');
203
0
      php_json_pretty_print_indent(buf, options, encoder);
204
0
    }
205
0
    smart_str_appendc(buf, '}');
206
0
    return SUCCESS;
207
2
  } else {
208
2
    zend_object *obj = Z_OBJ_P(val);
209
2
    prop_ht = myht = zend_get_properties_for(val, ZEND_PROP_PURPOSE_JSON);
210
2
    if (obj->ce->num_hooked_props == 0) {
211
0
      recursion_rc = (zend_refcounted *)prop_ht;
212
2
    } else {
213
      /* Protecting the object itself is fine here because myht is temporary and can't be
214
       * referenced from a different place in the object graph. */
215
2
      recursion_rc = (zend_refcounted *)obj;
216
2
    }
217
2
    encode_as_object = true;
218
2
  }
219
220
2
  if (recursion_rc && GC_IS_RECURSIVE(recursion_rc)) {
221
0
    encoder->error_code = PHP_JSON_ERROR_RECURSION;
222
0
    smart_str_appendl(buf, "null", 4);
223
0
    zend_release_properties(prop_ht);
224
0
    return FAILURE;
225
0
  }
226
227
2
  PHP_JSON_HASH_PROTECT_RECURSION(recursion_rc);
228
229
2
  if (!encode_as_object) {
230
0
    smart_str_appendc(buf, '[');
231
2
  } else {
232
2
    smart_str_appendc(buf, '{');
233
2
  }
234
235
2
  ++encoder->depth;
236
237
2
  uint32_t i = myht ? zend_hash_num_elements(myht) : 0;
238
239
2
  bool empty = true;
240
2
  if (i > 0) {
241
2
    zend_string *key;
242
2
    zval *data;
243
2
    zend_ulong index;
244
245
8
    ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, data) {
246
8
      bool need_dtor = false;
247
8
      zval tmp;
248
8
      ZVAL_UNDEF(&tmp);
249
250
8
      if (!encode_as_object) {
251
0
        ZEND_ASSERT(Z_TYPE_P(data) != IS_PTR);
252
253
0
        php_json_pretty_print_char(buf, options, '\n');
254
0
        php_json_pretty_print_indent(buf, options, encoder);
255
3
      } else {
256
3
        if (key) {
257
3
          if (ZSTR_VAL(key)[0] == '\0' && ZSTR_LEN(key) > 0 && Z_TYPE_P(val) == IS_OBJECT) {
258
            /* Skip protected and private members. */
259
0
            continue;
260
0
          }
261
262
          /* data is IS_PTR for properties with hooks. */
263
3
          if (UNEXPECTED(Z_TYPE_P(data) == IS_PTR)) {
264
2
            zend_property_info *prop_info = Z_PTR_P(data);
265
2
            if ((prop_info->flags & ZEND_ACC_VIRTUAL) && !prop_info->hooks[ZEND_PROPERTY_HOOK_GET]) {
266
0
              continue;
267
0
            }
268
2
            need_dtor = true;
269
2
            data = zend_read_property_ex(prop_info->ce, Z_OBJ_P(val), prop_info->name, /* silent */ true, &tmp);
270
2
            if (EG(exception)) {
271
0
              PHP_JSON_HASH_UNPROTECT_RECURSION(recursion_rc);
272
0
              zend_release_properties(prop_ht);
273
0
              return FAILURE;
274
0
            }
275
2
          }
276
277
278
3
          php_json_pretty_print_char(buf, options, '\n');
279
3
          php_json_pretty_print_indent(buf, options, encoder);
280
281
3
          if (php_json_escape_string(buf, ZSTR_VAL(key), ZSTR_LEN(key),
282
3
                options & ~PHP_JSON_NUMERIC_CHECK, encoder) == FAILURE &&
283
0
              (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) &&
284
0
              buf->s) {
285
0
            ZSTR_LEN(buf->s) -= 4;
286
0
            smart_str_appendl(buf, "\"\"", 2);
287
0
          }
288
3
        } else {
289
0
          php_json_pretty_print_char(buf, options, '\n');
290
0
          php_json_pretty_print_indent(buf, options, encoder);
291
292
0
          smart_str_appendc(buf, '"');
293
0
          smart_str_append_long(buf, (zend_long) index);
294
0
          smart_str_appendc(buf, '"');
295
0
        }
296
297
3
        smart_str_appendc(buf, ':');
298
3
        php_json_pretty_print_char(buf, options, ' ');
299
3
      }
300
301
3
      if (php_json_encode_zval(buf, data, options, encoder) == FAILURE &&
302
0
          !(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
303
0
        PHP_JSON_HASH_UNPROTECT_RECURSION(recursion_rc);
304
0
        zend_release_properties(prop_ht);
305
0
        zval_ptr_dtor(&tmp);
306
0
        return FAILURE;
307
0
      }
308
3
      if (UNEXPECTED(need_dtor)) {
309
2
        zval_ptr_dtor(&tmp);
310
2
      }
311
312
3
      smart_str_appendc(buf, ',');
313
3
    } ZEND_HASH_FOREACH_END();
314
315
2
    empty = ZSTR_VAL(buf->s)[ZSTR_LEN(buf->s) - 1] != ',';
316
2
    if (!empty) {
317
      /* Drop the trailing comma. */
318
2
      ZSTR_LEN(buf->s)--;
319
2
    }
320
2
  }
321
322
2
  PHP_JSON_HASH_UNPROTECT_RECURSION(recursion_rc);
323
324
2
  if (encoder->depth > encoder->max_depth) {
325
0
    encoder->error_code = PHP_JSON_ERROR_DEPTH;
326
0
    if (!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
327
0
      zend_release_properties(prop_ht);
328
0
      return FAILURE;
329
0
    }
330
0
  }
331
2
  --encoder->depth;
332
333
  /* Only keep closing bracket on same line for empty arrays/objects */
334
2
  if (!empty) {
335
2
    php_json_pretty_print_char(buf, options, '\n');
336
2
    php_json_pretty_print_indent(buf, options, encoder);
337
2
  }
338
339
2
  if (!encode_as_object) {
340
0
    smart_str_appendc(buf, ']');
341
2
  } else {
342
2
    smart_str_appendc(buf, '}');
343
2
  }
344
345
2
  zend_release_properties(prop_ht);
346
2
  return SUCCESS;
347
2
}
348
/* }}} */
349
350
zend_result php_json_escape_string(
351
    smart_str *buf, const char *s, size_t len,
352
    int options, php_json_encoder *encoder) /* {{{ */
353
3
{
354
3
  size_t pos, checkpoint;
355
3
  char *dst;
356
357
3
  if (len == 0) {
358
0
    smart_str_appendl(buf, "\"\"", 2);
359
0
    return SUCCESS;
360
0
  }
361
362
3
  if (options & PHP_JSON_NUMERIC_CHECK) {
363
0
    double d;
364
0
    int type;
365
0
    zend_long p;
366
367
0
    if ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) {
368
0
      if (type == IS_LONG) {
369
0
        smart_str_append_long(buf, p);
370
0
        return SUCCESS;
371
0
      } else if (type == IS_DOUBLE && php_json_is_valid_double(d)) {
372
0
        php_json_encode_double(buf, d, options);
373
0
        return SUCCESS;
374
0
      }
375
0
    }
376
377
0
  }
378
3
  checkpoint = buf->s ? ZSTR_LEN(buf->s) : 0;
379
380
  /* pre-allocate for string length plus 2 quotes */
381
3
  smart_str_alloc(buf, len+2, 0);
382
3
  smart_str_appendc(buf, '"');
383
384
3
  pos = 0;
385
386
6
  do {
387
6
    static const uint32_t charmap[8] = {
388
6
      0xffffffff, 0x500080c4, 0x10000000, 0x00000000,
389
6
      0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff};
390
391
6
    unsigned int us = (unsigned char)s[pos];
392
6
    if (EXPECTED(!ZEND_BIT_TEST(charmap, us))) {
393
6
      pos++;
394
6
      len--;
395
6
      if (len == 0) {
396
3
        smart_str_appendl(buf, s, pos);
397
3
        break;
398
3
      }
399
6
    } else {
400
0
      if (pos) {
401
0
        smart_str_appendl(buf, s, pos);
402
0
        s += pos;
403
0
        pos = 0;
404
0
      }
405
0
      us = (unsigned char)s[0];
406
0
      if (UNEXPECTED(us >= 0x80)) {
407
0
        zend_result status;
408
0
        us = php_next_utf8_char((unsigned char *)s, len, &pos, &status);
409
410
        /* check whether UTF8 character is correct */
411
0
        if (UNEXPECTED(status != SUCCESS)) {
412
0
          if (options & PHP_JSON_INVALID_UTF8_IGNORE) {
413
            /* ignore invalid UTF8 character */
414
0
          } else if (options & PHP_JSON_INVALID_UTF8_SUBSTITUTE) {
415
            /* Use Unicode character 'REPLACEMENT CHARACTER' (U+FFFD) */
416
0
            if (options & PHP_JSON_UNESCAPED_UNICODE) {
417
0
              smart_str_appendl(buf, "\xef\xbf\xbd", 3);
418
0
            } else {
419
0
              smart_str_appendl(buf, "\\ufffd", 6);
420
0
            }
421
0
          } else {
422
0
            ZSTR_LEN(buf->s) = checkpoint;
423
0
            encoder->error_code = PHP_JSON_ERROR_UTF8;
424
0
            if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
425
0
              smart_str_appendl(buf, "null", 4);
426
0
            }
427
0
            return FAILURE;
428
0
          }
429
430
        /* Escape U+2028/U+2029 line terminators, UNLESS both
431
           JSON_UNESCAPED_UNICODE and
432
           JSON_UNESCAPED_LINE_TERMINATORS were provided */
433
0
        } else if ((options & PHP_JSON_UNESCAPED_UNICODE)
434
0
            && ((options & PHP_JSON_UNESCAPED_LINE_TERMINATORS)
435
0
            || us < 0x2028 || us > 0x2029)) {
436
0
          smart_str_appendl(buf, s, pos);
437
0
        } else {
438
          /* From http://en.wikipedia.org/wiki/UTF16 */
439
0
          if (us >= 0x10000) {
440
0
            unsigned int next_us;
441
442
0
            us -= 0x10000;
443
0
            next_us = (unsigned short)((us & 0x3ff) | 0xdc00);
444
0
            us = (unsigned short)((us >> 10) | 0xd800);
445
0
            dst = smart_str_extend(buf, 6);
446
0
            dst[0] = '\\';
447
0
            dst[1] = 'u';
448
0
            dst[2] = digits[(us >> 12) & 0xf];
449
0
            dst[3] = digits[(us >> 8) & 0xf];
450
0
            dst[4] = digits[(us >> 4) & 0xf];
451
0
            dst[5] = digits[us & 0xf];
452
0
            us = next_us;
453
0
          }
454
0
          dst = smart_str_extend(buf, 6);
455
0
          dst[0] = '\\';
456
0
          dst[1] = 'u';
457
0
          dst[2] = digits[(us >> 12) & 0xf];
458
0
          dst[3] = digits[(us >> 8) & 0xf];
459
0
          dst[4] = digits[(us >> 4) & 0xf];
460
0
          dst[5] = digits[us & 0xf];
461
0
        }
462
0
        s += pos;
463
0
        len -= pos;
464
0
        pos = 0;
465
0
      } else {
466
0
        s++;
467
0
        switch (us) {
468
0
          case '"':
469
0
            if (options & PHP_JSON_HEX_QUOT) {
470
0
              smart_str_appendl(buf, "\\u0022", 6);
471
0
            } else {
472
0
              smart_str_appendl(buf, "\\\"", 2);
473
0
            }
474
0
            break;
475
476
0
          case '\\':
477
0
            smart_str_appendl(buf, "\\\\", 2);
478
0
            break;
479
480
0
          case '/':
481
0
            if (options & PHP_JSON_UNESCAPED_SLASHES) {
482
0
              smart_str_appendc(buf, '/');
483
0
            } else {
484
0
              smart_str_appendl(buf, "\\/", 2);
485
0
            }
486
0
            break;
487
488
0
          case '\b':
489
0
            smart_str_appendl(buf, "\\b", 2);
490
0
            break;
491
492
0
          case '\f':
493
0
            smart_str_appendl(buf, "\\f", 2);
494
0
            break;
495
496
0
          case '\n':
497
0
            smart_str_appendl(buf, "\\n", 2);
498
0
            break;
499
500
0
          case '\r':
501
0
            smart_str_appendl(buf, "\\r", 2);
502
0
            break;
503
504
0
          case '\t':
505
0
            smart_str_appendl(buf, "\\t", 2);
506
0
            break;
507
508
0
          case '<':
509
0
            if (options & PHP_JSON_HEX_TAG) {
510
0
              smart_str_appendl(buf, "\\u003C", 6);
511
0
            } else {
512
0
              smart_str_appendc(buf, '<');
513
0
            }
514
0
            break;
515
516
0
          case '>':
517
0
            if (options & PHP_JSON_HEX_TAG) {
518
0
              smart_str_appendl(buf, "\\u003E", 6);
519
0
            } else {
520
0
              smart_str_appendc(buf, '>');
521
0
            }
522
0
            break;
523
524
0
          case '&':
525
0
            if (options & PHP_JSON_HEX_AMP) {
526
0
              smart_str_appendl(buf, "\\u0026", 6);
527
0
            } else {
528
0
              smart_str_appendc(buf, '&');
529
0
            }
530
0
            break;
531
532
0
          case '\'':
533
0
            if (options & PHP_JSON_HEX_APOS) {
534
0
              smart_str_appendl(buf, "\\u0027", 6);
535
0
            } else {
536
0
              smart_str_appendc(buf, '\'');
537
0
            }
538
0
            break;
539
540
0
          default:
541
0
            ZEND_ASSERT(us < ' ');
542
0
            dst = smart_str_extend(buf, 6);
543
0
            dst[0] = '\\';
544
0
            dst[1] = 'u';
545
0
            dst[2] = '0';
546
0
            dst[3] = '0';
547
0
            dst[4] = digits[(us >> 4) & 0xf];
548
0
            dst[5] = digits[us & 0xf];
549
0
            break;
550
0
        }
551
0
        len--;
552
0
      }
553
0
    }
554
6
  } while (len);
555
556
3
  smart_str_appendc(buf, '"');
557
558
3
  return SUCCESS;
559
3
}
560
/* }}} */
561
562
static zend_result php_json_encode_serializable_object(smart_str *buf, zend_object *obj, int options, php_json_encoder *encoder)
563
0
{
564
0
  zend_class_entry *ce = obj->ce;
565
0
  uint32_t *guard = zend_get_recursion_guard(obj);
566
0
  zval retval;
567
0
  zend_result return_code;
568
569
0
  ZEND_ASSERT(guard != NULL);
570
571
0
  if (ZEND_GUARD_IS_RECURSIVE(guard, JSON)) {
572
0
    encoder->error_code = PHP_JSON_ERROR_RECURSION;
573
0
    if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
574
0
      smart_str_appendl(buf, "null", 4);
575
0
    }
576
0
    return FAILURE;
577
0
  }
578
579
0
  ZEND_GUARD_PROTECT_RECURSION(guard, JSON);
580
581
0
  zend_function *json_serialize_method = zend_hash_str_find_ptr(&ce->function_table, ZEND_STRL("jsonserialize"));
582
0
  ZEND_ASSERT(json_serialize_method != NULL && "This should be guaranteed prior to calling this function");
583
0
  zend_call_known_function(json_serialize_method, obj, ce, &retval, 0, NULL, NULL);
584
  /* An exception has occurred */
585
0
  if (Z_TYPE(retval) == IS_UNDEF) {
586
0
    if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
587
0
      smart_str_appendl(buf, "null", 4);
588
0
    }
589
0
    ZEND_GUARD_UNPROTECT_RECURSION(guard, JSON);
590
0
    return FAILURE;
591
0
  }
592
593
0
  if (Z_TYPE(retval) == IS_OBJECT && Z_OBJ(retval) == obj) {
594
    /* Handle the case where jsonSerialize does: return $this; by going straight to encode array */
595
0
    ZEND_GUARD_UNPROTECT_RECURSION(guard, JSON);
596
0
    return_code = php_json_encode_array(buf, &retval, options, encoder);
597
0
  } else {
598
    /* All other types, encode as normal */
599
0
    return_code = php_json_encode_zval(buf, &retval, options, encoder);
600
0
    ZEND_GUARD_UNPROTECT_RECURSION(guard, JSON);
601
0
  }
602
603
0
  zval_ptr_dtor(&retval);
604
605
0
  return return_code;
606
0
}
607
608
static zend_result php_json_encode_serializable_enum(smart_str *buf, zval *val, int options, php_json_encoder *encoder)
609
0
{
610
0
  const zend_class_entry *ce = Z_OBJCE_P(val);
611
0
  if (ce->enum_backing_type == IS_UNDEF) {
612
0
    encoder->error_code = PHP_JSON_ERROR_NON_BACKED_ENUM;
613
0
    smart_str_appendc(buf, '0');
614
0
    return FAILURE;
615
0
  }
616
617
0
  zval *value_zv = zend_enum_fetch_case_value(Z_OBJ_P(val));
618
0
  return php_json_encode_zval(buf, value_zv, options, encoder);
619
0
}
620
621
zend_result php_json_encode_zval(smart_str *buf, zval *val, int options, php_json_encoder *encoder) /* {{{ */
622
5
{
623
6
again:
624
6
  switch (Z_TYPE_P(val))
625
6
  {
626
2
    case IS_NULL:
627
2
      smart_str_appendl(buf, "null", 4);
628
2
      break;
629
630
0
    case IS_TRUE:
631
0
      smart_str_appendl(buf, "true", 4);
632
0
      break;
633
0
    case IS_FALSE:
634
0
      smart_str_appendl(buf, "false", 5);
635
0
      break;
636
637
1
    case IS_LONG:
638
1
      smart_str_append_long(buf, Z_LVAL_P(val));
639
1
      break;
640
641
0
    case IS_DOUBLE:
642
0
      if (php_json_is_valid_double(Z_DVAL_P(val))) {
643
0
        php_json_encode_double(buf, Z_DVAL_P(val), options);
644
0
      } else {
645
0
        encoder->error_code = PHP_JSON_ERROR_INF_OR_NAN;
646
0
        smart_str_appendc(buf, '0');
647
0
      }
648
0
      break;
649
650
0
    case IS_STRING:
651
0
      return php_json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options, encoder);
652
653
2
    case IS_OBJECT:
654
2
      if (instanceof_function(Z_OBJCE_P(val), php_json_serializable_ce)) {
655
0
        return php_json_encode_serializable_object(buf, Z_OBJ_P(val), options, encoder);
656
0
      }
657
2
      if (Z_OBJCE_P(val)->ce_flags & ZEND_ACC_ENUM) {
658
0
        return php_json_encode_serializable_enum(buf, val, options, encoder);
659
0
      }
660
      /* fallthrough -- Non-serializable object */
661
2
      ZEND_FALLTHROUGH;
662
2
    case IS_ARRAY: {
663
      /* Avoid modifications (and potential freeing) of the array through a reference when a
664
       * jsonSerialize() method is invoked. */
665
2
      zval zv;
666
2
      zend_result res;
667
2
      ZVAL_COPY(&zv, val);
668
2
      res = php_json_encode_array(buf, &zv, options, encoder);
669
2
      zval_ptr_dtor_nogc(&zv);
670
2
      return res;
671
2
    }
672
673
1
    case IS_REFERENCE:
674
1
      val = Z_REFVAL_P(val);
675
1
      goto again;
676
677
0
    default:
678
0
      encoder->error_code = PHP_JSON_ERROR_UNSUPPORTED_TYPE;
679
0
      if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
680
0
        smart_str_appendl(buf, "null", 4);
681
0
      }
682
0
      return FAILURE;
683
6
  }
684
685
3
  return SUCCESS;
686
6
}
687
/* }}} */