Coverage Report

Created: 2026-06-02 06:40

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