-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdeepclone.c
More file actions
3437 lines (3134 loc) · 126 KB
/
deepclone.c
File metadata and controls
3437 lines (3134 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* deepclone extension: deep-clones any serializable PHP value while
* preserving copy-on-write for strings and arrays — resulting in lower
* memory usage and better performance than unserialize(serialize()).
*
* Works by converting the value graph to a pure-array representation (only
* scalars and nested arrays, no objects) and back. This array form is the
* wire format used by Symfony's VarExporter\DeepCloner, making the extension
* a transparent drop-in accelerator.
*
* function deepclone_to_array(mixed $value, ?array $allowed_classes = null): array
* Traverses a PHP value graph, extracts object properties, tracks
* references, and returns a pure-scalar array equivalent to what
* Symfony\Component\VarExporter\DeepCloner::toArray() produces.
* Leverages copy-on-write for strings and scalar arrays.
*
* function deepclone_from_array(array $data, ?array $allowed_classes = null): mixed
* Reconstructs the value graph from such an array, equivalent to
* Symfony\Component\VarExporter\DeepCloner::fromArray($data)->clone().
* Throws \ValueError on malformed input.
*
* function deepclone_hydrate(object|string $object_or_class,
* array $vars = [],
* int $flags = 0): object
* Instantiates a class (or takes an existing object) and sets its
* properties — including private, protected, and readonly — via direct
* property-slot writes. Replaces Symfony's Hydrator/Instantiator.
*
* `$allowed_classes` follows unserialize()'s semantics: null = allow all,
* [] = allow none, case-insensitive. Closures require `"Closure"` in the list.
*
* Typed exceptions (both extending \InvalidArgumentException):
* DeepClone\NotInstantiableException — deepclone_to_array / deepclone_hydrate
* DeepClone\ClassNotFoundException — deepclone_from_array / deepclone_hydrate
* ValueError is thrown on malformed input or disallowed class names.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_deepclone.h"
#include "ext/standard/info.h"
#include "ext/standard/php_var.h"
#include "Zend/zend_smart_str.h"
#include "ext/standard/php_incomplete_class.h"
#include "Zend/zend_closures.h"
#include "Zend/zend_exceptions.h"
/* Stack-limit protection requires PHP 8.4+; no-op on older versions. */
#if PHP_VERSION_ID >= 80400
# include "Zend/zend_call_stack.h"
#endif
#if PHP_VERSION_ID >= 80400
# include "Zend/zend_lazy_objects.h"
#endif
#include "Zend/zend_enum.h"
#include "Zend/zend_interfaces.h"
#include "ext/spl/spl_iterators.h"
#include "ext/spl/spl_exceptions.h"
#include "ext/spl/spl_array.h"
#include "ext/spl/spl_observer.h"
/* ext/reflection's class entries are PHPAPI but Debian's php-dev does not
* ship ext/reflection/php_reflection.h. Forward-declare what we use; the
* linker resolves the symbols against the loaded PHP binary at runtime. */
extern PHPAPI zend_class_entry *reflector_ptr;
extern PHPAPI zend_class_entry *reflection_type_ptr;
extern PHPAPI zend_class_entry *reflection_property_ptr;
/* ── Compatibility shims for older PHP versions ────────────── */
/* zend_zval_value_name() landed in PHP 8.3 (returns "true"/"false"/"null"
* /numeric literals as appropriate). On 8.2 fall back to the older
* zend_zval_type_name() which returns just the type name ("bool", "int", …).
* Slightly less informative, same printf format. */
#if PHP_VERSION_ID < 80300
# define zend_zval_value_name(zv) zend_zval_type_name(zv)
#endif
#if PHP_VERSION_ID < 80400
/* rebuild_object_properties_internal() was introduced in 8.4 alongside the
* zend_std_build_properties() refactor. On 8.2/8.3 the equivalent is the
* older rebuild_object_properties() (no "_internal" suffix). */
# define rebuild_object_properties_internal(obj) rebuild_object_properties(obj)
/* zend_register_internal_class_with_flags() landed in PHP 8.4. The
* stub-generated registration code calls it for our DeepClone\* exception
* classes. On 8.2/8.3 fall back to zend_register_internal_class_ex() and set
* the flags afterwards. We currently always pass 0 flags, so the assignment
* is a no-op, but we keep it for future-proofing. */
# define zend_register_internal_class_with_flags(ce, parent, flags) \
dc_register_internal_class_with_flags((ce), (parent), (flags))
static zend_always_inline zend_class_entry *dc_register_internal_class_with_flags(
zend_class_entry *class_entry, zend_class_entry *parent_ce, uint32_t flags)
{
zend_class_entry *registered = zend_register_internal_class_ex(class_entry, parent_ce);
if (flags) {
registered->ce_flags |= flags;
}
return registered;
}
/* Lazy objects landed in PHP 8.4. Pre-8.4 has no such concept, so the
* "is this a lazy object?" check is always false and we degrade to the
* normal walk path. */
# define zend_object_is_lazy(obj) (0)
/* Asymmetric visibility (set-only protected/private) landed in PHP 8.4.
* On older PHP, readonly is the closest equivalent: a public-read property
* whose writes are forced into the declaring scope. Aliasing PROTECTED_SET
* to ZEND_ACC_READONLY makes the existing scope-resolution branch route
* readonly props through the declaring class on 8.2/8.3 — same outcome as
* the asymmetric-visibility path on 8.4+. PRIVATE_SET has no pre-8.4
* equivalent and stays 0. */
# ifndef ZEND_ACC_PROTECTED_SET
# define ZEND_ACC_PROTECTED_SET ZEND_ACC_READONLY
# endif
# ifndef ZEND_ACC_PRIVATE_SET
# define ZEND_ACC_PRIVATE_SET (0)
# endif
# ifndef ZEND_ACC_VIRTUAL
# define ZEND_ACC_VIRTUAL (0)
# endif
# ifndef ZEND_VIRTUAL_PROPERTY_OFFSET
# define ZEND_VIRTUAL_PROPERTY_OFFSET ((uint32_t)-1)
# endif
# ifndef IS_HOOKED_PROPERTY_OFFSET
# define IS_HOOKED_PROPERTY_OFFSET(offset) (0)
# endif
/* ZEND_ACC_UNINSTANTIABLE composite landed in PHP 8.4. The bitmask is
* identical across versions; expand explicitly on 8.2/8.3. */
# ifndef ZEND_ACC_UNINSTANTIABLE
# define ZEND_ACC_UNINSTANTIABLE (\
ZEND_ACC_INTERFACE | \
ZEND_ACC_TRAIT | \
ZEND_ACC_IMPLICIT_ABSTRACT_CLASS | \
ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | \
ZEND_ACC_ENUM \
)
# endif
#endif
#if PHP_VERSION_ID >= 80400
# define DC_PROP_HAS_HOOKS(pi) ((pi)->hooks != NULL)
#else
# define DC_PROP_HAS_HOOKS(pi) (0)
#endif
/* Public flags for deepclone_hydrate()'s $flags parameter. Exported as
* PHP-level constants via deepclone.stub.php; values must match. */
#define DEEPCLONE_HYDRATE_CALL_HOOKS (1 << 0)
#define DEEPCLONE_HYDRATE_NO_LAZY_INIT (1 << 1)
#define DEEPCLONE_HYDRATE_PRESERVE_REFS (1 << 2)
#define DEEPCLONE_HYDRATE_FLAGS_MASK \
(DEEPCLONE_HYDRATE_CALL_HOOKS | DEEPCLONE_HYDRATE_NO_LAZY_INIT | DEEPCLONE_HYDRATE_PRESERVE_REFS)
/* The stub-generated header relies on the compat shims above (specifically
* zend_register_internal_class_with_flags on PHP < 8.4), so it has to be
* included after this point. */
#include "deepclone_arginfo.h"
/* Check whether the native call stack is about to overflow, the same way
* ext/standard/var.c guards php_var_serialize_intern against runaway
* recursion. Mirrors php_serialize_check_stack_limit(): returns true (and
* throws \Error via zend_call_stack_size_error) when we're too deep.
* dc_copy_value (the only recursive walker — dc_copy_array always goes
* through dc_copy_value) calls this at its entry. No-op on PHP < 8.4
* (see the header-include block above) or on platforms where
* ZEND_CHECK_STACK_LIMIT is disabled at configure time. */
static zend_always_inline bool dc_check_stack_limit(void)
{
#if PHP_VERSION_ID >= 80400 && defined(ZEND_CHECK_STACK_LIMIT)
if (UNEXPECTED(zend_call_stack_overflowed(EG(stack_limit)))) {
zend_call_stack_size_error();
return true;
}
#endif
return false;
}
/* We key ctx->ref_map on raw zend_reference pointers. Pre-hashing is
* unsafe because zend_hash uses the stored key as a bucket-chain identity
* (p->h == h), not just for distribution. The ref_map is sparse enough
* that aligned-pointer collisions don't cause measurable slowdowns. */
/* ── Permanent interned strings for output keys ───────────── */
static zend_string *dc_key_value;
static zend_string *dc_key_classes;
static zend_string *dc_key_object_meta;
static zend_string *dc_key_prepared;
static zend_string *dc_key_mask;
static zend_string *dc_key_properties;
static zend_string *dc_key_resolve;
static zend_string *dc_key_states;
static zend_string *dc_key_refs;
static zend_string *dc_key_ref_masks;
/* Interned strings for property name / key comparisons */
static zend_string *dc_str_trace;
static zend_string *dc_str_error_trace_mangled; /* "\0Error\0trace" */
static zend_string *dc_str_exception_trace_mangled; /* "\0Exception\0trace" */
static zend_string *dc_str_file_mangled; /* "\0*\0file" */
static zend_string *dc_str_line_mangled; /* "\0*\0line" */
/* Class entry for ReflectionGenerator (resolved at MINIT, since
* php_reflection.h doesn't export it). */
static zend_class_entry *dc_ce_reflection_generator;
/* Class entries for the exceptions thrown by deepclone_to_array() and
* deepclone_from_array(). Both extend \InvalidArgumentException; their bare
* message is the offending class or type name. Registered in MINIT via the
* stub-generated helpers in deepclone_arginfo.h. */
static zend_class_entry *dc_ce_not_instantiable_exception;
static zend_class_entry *dc_ce_class_not_found_exception;
/* ── Forward declarations ───────────────────────────────────── */
typedef struct _dc_ctx dc_ctx;
static void dc_process_object(dc_ctx *ctx, zval *src, zval *dst, zval *mask_dst);
/* ── Reference pool entry ───────────────────────────────────── */
typedef struct {
zend_reference *ref; /* the PHP reference (identity key) */
uint32_t id; /* 1-based ref ID */
uint32_t count; /* re-encounter count */
zval orig_type; /* original value for type detection */
zval cur_value; /* original value for unwrap restoration */
zval cur_mask; /* original mask for unwrap restoration */
zval *tree_pos; /* pointer to the dst slot in the prepared tree */
zval *mask_slot; /* pointer to the mask zval for this ref (in parent array) */
} dc_ref_entry;
/* ── Object pool entry ──────────────────────────────────────── */
typedef struct {
uint32_t id;
uint32_t cidx; /* class index in the deduped classes[] array */
zend_string *class_name;
bool class_name_owned; /* true if class_name was allocated (Serializable) */
int wakeup; /* >0 = __wakeup order, <0 = __unserialize order, 0 = none */
HashTable *props; /* [scope][name] => value (already prepared) */
HashTable *prop_mask; /* [scope][name] => mask marker (or NULL) */
} dc_pool_entry;
/* ── Traversal context ──────────────────────────────────────── */
struct _dc_ctx {
HashTable object_pool; /* obj_handle => dc_pool_entry */
dc_pool_entry **entries; /* indexed by entry->id (id-ordered iteration) */
uint32_t entries_cap;
dc_ref_entry *refs; /* dynamic array */
uint32_t refs_count;
uint32_t refs_cap;
HashTable ref_map; /* zend_reference* => index in refs[] */
uint32_t next_obj_id;
uint32_t objects_count;
bool is_static;
HashTable *allowed_ht; /* allowed class names set (or NULL = all) */
/* Output structures built incrementally during traversal */
zval classes; /* deduped class names */
zval properties; /* [scope][name][id] => value */
zval resolve; /* [scope][name][id] => marker */
HashTable class_map; /* class_name => cidx (uint32_t in zval long) */
/* Scope map cache: class_name => HashTable(prop_name => scope_class_name) */
HashTable scope_cache;
/* Class info cache: class_name => [has_unserialize, has_wakeup, serialize_method, has_sleep] */
HashTable class_info;
/* Proto cache: class_name => (array) prototype */
HashTable proto_cache;
};
/* ── Class info cache entry ─────────────────────────────────── */
#define DC_CI_HAS_UNSERIALIZE (1 << 0)
#define DC_CI_HAS_WAKEUP (1 << 1)
#define DC_CI_HAS_SERIALIZE (1 << 2)
#define DC_CI_SERIALIZE_PUBLIC (1 << 3)
#define DC_CI_HAS_SLEEP (1 << 4)
#define DC_CI_NOT_INSTANTIABLE (1 << 5)
#define DC_CI_COMPUTED (1 << 7)
/* ── Helpers ────────────────────────────────────────────────── */
static void dc_ctx_init(dc_ctx *ctx) {
zend_hash_init(&ctx->object_pool, 8, NULL, NULL, 0);
ctx->entries = NULL;
ctx->entries_cap = 0;
ctx->refs = NULL;
ctx->refs_count = 0;
ctx->refs_cap = 0;
ZVAL_UNDEF(&ctx->classes);
ZVAL_UNDEF(&ctx->properties);
ZVAL_UNDEF(&ctx->resolve);
zend_hash_init(&ctx->class_map, 4, NULL, NULL, 0);
zend_hash_init(&ctx->ref_map, 8, NULL, NULL, 0);
ctx->next_obj_id = 0;
ctx->objects_count = 0;
ctx->is_static = 1;
ctx->allowed_ht = NULL;
zend_hash_init(&ctx->scope_cache, 4, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_init(&ctx->class_info, 4, NULL, NULL, 0);
zend_hash_init(&ctx->proto_cache, 4, NULL, ZVAL_PTR_DTOR, 0);
}
static void dc_ctx_destroy(dc_ctx *ctx) {
zend_hash_destroy(&ctx->object_pool);
zval_ptr_dtor(&ctx->classes);
zval_ptr_dtor(&ctx->properties);
zval_ptr_dtor(&ctx->resolve);
zend_hash_destroy(&ctx->class_map);
if (ctx->entries) {
/* Free any remaining pool entries (entries whose props/prop_mask were
* transferred into the output have those fields nulled out by
* dc_build_output before reaching here). */
for (uint32_t id = 0; id < ctx->next_obj_id; id++) {
dc_pool_entry *e = ctx->entries[id];
if (!e) continue;
if (e->class_name_owned) {
zend_string_release(e->class_name);
}
if (e->props) {
zend_array_destroy(e->props);
}
if (e->prop_mask) {
zend_array_destroy(e->prop_mask);
}
efree(e);
}
efree(ctx->entries);
}
if (ctx->refs) {
for (uint32_t i = 0; i < ctx->refs_count; i++) {
zval_ptr_dtor(&ctx->refs[i].orig_type);
zval_ptr_dtor(&ctx->refs[i].cur_value);
zval_ptr_dtor(&ctx->refs[i].cur_mask);
}
efree(ctx->refs);
}
zend_hash_destroy(&ctx->ref_map);
zend_hash_destroy(&ctx->scope_cache);
zend_hash_destroy(&ctx->class_info);
zend_hash_destroy(&ctx->proto_cache);
if (ctx->allowed_ht) {
zend_hash_destroy(ctx->allowed_ht);
efree(ctx->allowed_ht);
}
}
/* Assign or fetch the deduplicated class index for a class name */
static uint32_t dc_class_index(dc_ctx *ctx, zend_string *class_name)
{
zval *cached = zend_hash_find(&ctx->class_map, class_name);
if (EXPECTED(cached)) {
return (uint32_t) Z_LVAL_P(cached);
}
if (Z_TYPE(ctx->classes) == IS_UNDEF) {
array_init_size(&ctx->classes, 1);
}
uint32_t cidx = zend_hash_num_elements(Z_ARRVAL(ctx->classes));
zval zidx;
ZVAL_LONG(&zidx, cidx);
zend_hash_add_new(&ctx->class_map, class_name, &zidx);
zval zclass;
ZVAL_STR_COPY(&zclass, class_name);
zend_hash_next_index_insert_new(Z_ARRVAL(ctx->classes), &zclass);
return cidx;
}
static uint32_t dc_ref_add(dc_ctx *ctx, zend_reference *ref, zval *orig, zval *current) {
if (ctx->refs_count >= ctx->refs_cap) {
/* Grow by 1.5× instead of 2× — slightly less memory at high counts
* while still amortised O(1). See folly's FBVector rationale. The
* +1 covers the cap=1 edge case where (1 * 3) >> 1 == 1 (no growth),
* and the `<8` floor keeps the very first allocation at a useful
* size without going through two or three grow steps. */
ctx->refs_cap = ctx->refs_cap < 8 ? 8 : ((ctx->refs_cap * 3) >> 1) + 1;
ctx->refs = safe_erealloc(ctx->refs, ctx->refs_cap, sizeof(dc_ref_entry), 0);
}
uint32_t idx = ctx->refs_count++;
ctx->refs[idx].ref = ref;
ctx->refs[idx].id = idx + 1; /* 1-based */
ctx->refs[idx].count = 0;
ZVAL_COPY(&ctx->refs[idx].orig_type, orig);
ZVAL_COPY(&ctx->refs[idx].cur_value, current);
ZVAL_UNDEF(&ctx->refs[idx].cur_mask);
ctx->refs[idx].tree_pos = NULL;
ctx->refs[idx].mask_slot = NULL;
/* Map ref pointer → index. See the comment at the top of the file
* about not pre-hashing keys handed to zend_hash_index_*. */
zval zidx;
ZVAL_LONG(&zidx, idx);
zend_hash_index_add_new(&ctx->ref_map, (zend_ulong)(uintptr_t)ref, &zidx);
return idx;
}
static uint8_t dc_get_class_info(dc_ctx *ctx, zend_class_entry *ce)
{
zval *cached = zend_hash_find(&ctx->class_info, ce->name);
if (EXPECTED(cached)) {
return (uint8_t) Z_LVAL_P(cached);
}
uint8_t flags = DC_CI_COMPUTED;
/* Use direct ce fields like native serialize does (O(1) vs hash lookup) */
if (ce->__unserialize) {
flags |= DC_CI_HAS_UNSERIALIZE;
}
if (ce->__serialize) {
flags |= DC_CI_HAS_SERIALIZE;
if (ce->__serialize->common.fn_flags & ZEND_ACC_PUBLIC) {
flags |= DC_CI_SERIALIZE_PUBLIC;
}
}
/* __sleep and __wakeup have no direct ce field — use known-string lookup */
if (zend_hash_find_known_hash(&ce->function_table, ZSTR_KNOWN(ZEND_STR_SLEEP))) {
flags |= DC_CI_HAS_SLEEP;
}
if (zend_hash_find_known_hash(&ce->function_table, ZSTR_KNOWN(ZEND_STR_WAKEUP))) {
flags |= DC_CI_HAS_WAKEUP;
}
/* Mark anonymous classes (names tied to file/line, can't round-trip) and
* Reflection / IteratorIterator / RecursiveIteratorIterator subclasses as
* non-instantiable. Escape hatches: Serializable, __wakeup, __unserialize. */
if (!(flags & (DC_CI_HAS_UNSERIALIZE | DC_CI_HAS_WAKEUP)) && ce->serialize == NULL
&& ((ce->ce_flags & ZEND_ACC_ANON_CLASS)
|| instanceof_function(ce, reflector_ptr)
|| instanceof_function(ce, reflection_type_ptr)
|| instanceof_function(ce, spl_ce_IteratorIterator)
|| instanceof_function(ce, spl_ce_RecursiveIteratorIterator)
|| (dc_ce_reflection_generator && instanceof_function(ce, dc_ce_reflection_generator)))) {
flags |= DC_CI_NOT_INSTANTIABLE;
}
/* Honour ZEND_ACC_NOT_SERIALIZABLE — classes that explicitly refuse
* serialization. Escape hatch: if the class declares its own
* (un)serialization API, trust the declaration. */
if ((ce->ce_flags & ZEND_ACC_NOT_SERIALIZABLE)
&& !(flags & (DC_CI_HAS_UNSERIALIZE | DC_CI_HAS_WAKEUP))
&& ce->serialize == NULL) {
flags |= DC_CI_NOT_INSTANTIABLE;
}
/* Internal classes with create_object and no serialization API:
* final → probe instantiation (stateless classes like BSON\MinKey pass);
* non-final → reject. Classes with __serialize/__unserialize are trusted. */
if (ce->type == ZEND_INTERNAL_CLASS
&& ce->create_object != NULL
&& (ce->ce_flags & ZEND_ACC_FINAL)
&& !(flags & (DC_CI_HAS_SERIALIZE | DC_CI_HAS_UNSERIALIZE | DC_CI_HAS_SLEEP | DC_CI_HAS_WAKEUP))
&& ce != php_ce_incomplete_class) {
zval probe;
if (object_init_ex(&probe, ce) != SUCCESS || EG(exception)) {
zend_clear_exception();
flags |= DC_CI_NOT_INSTANTIABLE;
} else {
zval_ptr_dtor(&probe);
}
} else if (ce->type == ZEND_INTERNAL_CLASS
&& ce->create_object != NULL
&& ce->serialize == NULL
&& !(flags & (DC_CI_HAS_SERIALIZE | DC_CI_HAS_UNSERIALIZE | DC_CI_HAS_SLEEP | DC_CI_HAS_WAKEUP))
&& ce != php_ce_incomplete_class) {
flags |= DC_CI_NOT_INSTANTIABLE;
}
zval zflags;
ZVAL_LONG(&zflags, flags);
zend_hash_add_new(&ctx->class_info, ce->name, &zflags);
return flags;
}
/* Get or build the scope map for a class: property_name => declaring_class_name */
static HashTable *dc_get_scope_map(dc_ctx *ctx, zend_class_entry *ce) {
zval *cached = zend_hash_find(&ctx->scope_cache, ce->name);
if (EXPECTED(cached)) {
return Z_ARRVAL_P(cached);
}
zval zmap;
array_init(&zmap);
HashTable *map = Z_ARRVAL(zmap);
zend_class_entry *parent = ce;
while (parent) {
for (uint32_t i = 0; i < parent->default_properties_count; i++) {
zend_property_info *pi = parent->properties_info_table[i];
if (!pi || (pi->flags & ZEND_ACC_STATIC)) continue;
/* Use unmangled name as key (pi->name is mangled for non-public) */
zend_string *key;
if (pi->flags & ZEND_ACC_PUBLIC) {
key = zend_string_copy(pi->name);
} else {
const char *class_name_unused, *uname;
size_t uname_len;
zend_unmangle_property_name_ex(pi->name, &class_name_unused, &uname, &uname_len);
key = zend_string_init_existing_interned(uname, uname_len, 0);
}
if (zend_hash_exists(map, key)) {
zend_string_release(key);
continue;
}
zval zscope;
if ((pi->flags & ZEND_ACC_PUBLIC) && !(pi->flags & ZEND_ACC_PROTECTED_SET) && !(pi->flags & ZEND_ACC_PRIVATE_SET)) {
ZVAL_STR_COPY(&zscope, ZEND_STANDARD_CLASS_DEF_PTR->name);
} else {
ZVAL_STR_COPY(&zscope, pi->ce->name);
}
zend_hash_add_new(map, key, &zscope);
zend_string_release(key);
}
parent = parent->parent;
}
zend_hash_add_new(&ctx->scope_cache, ce->name, &zmap);
return map;
}
/* Get (array) prototype for a class (cached) */
static HashTable *dc_get_proto(dc_ctx *ctx, zend_class_entry *ce) {
zval *cached = zend_hash_find(&ctx->proto_cache, ce->name);
if (EXPECTED(cached)) {
return Z_ARRVAL_P(cached);
}
/* Create a prototype instance */
zval proto_zval;
if (ce->create_object) {
zend_object *proto_obj = ce->create_object(ce);
ZVAL_OBJ(&proto_zval, proto_obj);
} else {
object_init_ex(&proto_zval, ce);
}
/* Cast to array */
zval proto_arr;
HashTable *ht = zend_get_properties_for(&proto_zval, ZEND_PROP_PURPOSE_ARRAY_CAST);
if (ht) {
ZVAL_ARR(&proto_arr, zend_array_dup(ht));
zend_release_properties(ht);
} else {
array_init(&proto_arr);
}
zval_ptr_dtor(&proto_zval);
zend_hash_add_new(&ctx->proto_cache, ce->name, &proto_arr);
return Z_ARRVAL(proto_arr);
}
/* Check if an array contains only scalars/enums (no objects, no refs, no
* resources). If so, the walker can COW-share it without recursing. */
static bool dc_array_is_static(HashTable *ht)
{
if (UNEXPECTED(GC_FLAGS(ht) & GC_IMMUTABLE)) {
return true;
}
if (UNEXPECTED(dc_check_stack_limit())) {
return false;
}
zval *val;
ZEND_HASH_FOREACH_VAL(ht, val) {
if (UNEXPECTED(Z_ISREF_P(val))) {
return false;
}
if (EXPECTED(Z_TYPE_P(val) <= IS_STRING)) {
continue;
}
if (Z_TYPE_P(val) == IS_ARRAY) {
if (zend_hash_num_elements(Z_ARRVAL_P(val)) > 0
&& !dc_array_is_static(Z_ARRVAL_P(val))) {
return false;
}
} else if (Z_TYPE_P(val) == IS_OBJECT) {
if (!(Z_OBJCE_P(val)->ce_flags & ZEND_ACC_ENUM)) {
return false;
}
} else {
/* IS_RESOURCE or anything else: force the walker to handle it,
* which will reject resources via dc_copy_value. */
return false;
}
} ZEND_HASH_FOREACH_END();
return true;
}
/* ── Allowed-class validation helpers ──────────────────────── */
/* Build a lowercased name-keyed HashTable from a user-provided list of
* class names, validating each entry like unserialize() does. Returns
* the set on success (caller must zend_hash_destroy + efree) or NULL on
* validation failure (exception already thrown). */
static HashTable *dc_build_allowed_set(HashTable *list, const char *func_name)
{
HashTable *set = emalloc(sizeof(HashTable));
zend_hash_init(set, zend_hash_num_elements(list), NULL, NULL, 0);
zval *entry;
ZEND_HASH_FOREACH_VAL(list, entry) {
if (Z_TYPE_P(entry) != IS_STRING) {
zend_hash_destroy(set);
efree(set);
zend_value_error("%s(): Argument $allowedClasses must be an array of class names, %s given",
func_name, zend_zval_value_name(entry));
return NULL;
}
if (!zend_is_valid_class_name(Z_STR_P(entry))) {
zend_hash_destroy(set);
efree(set);
zend_value_error("%s(): Argument $allowedClasses must be an array of class names, \"%s\" given",
func_name, ZSTR_VAL(Z_STR_P(entry)));
return NULL;
}
zend_string *lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(set, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
return set;
}
static zend_always_inline bool dc_class_allowed(HashTable *set, zend_string *name)
{
if (!set) return true;
zend_string *lcname = zend_string_tolower(name);
bool found = zend_hash_exists(set, lcname);
zend_string_release(lcname);
return found;
}
static zend_always_inline bool dc_is_backed_declared_property(zend_property_info *pi)
{
/* Non-static, non-virtual property with a real backing slot. ZEND_ACC_VIRTUAL
* already implies pi->offset == ZEND_VIRTUAL_PROPERTY_OFFSET, and
* IS_HOOKED_PROPERTY_OFFSET() is only meaningful on offsets returned by
* zend_get_property_offset() — not on the raw pi->offset. */
return pi && !(pi->flags & (ZEND_ACC_STATIC | ZEND_ACC_VIRTUAL));
}
static zend_always_inline bool dc_is_std_scope_property(zend_property_info *pi)
{
return pi
&& !(pi->flags & ZEND_ACC_STATIC)
&& (pi->flags & ZEND_ACC_PUBLIC)
&& !(pi->flags & (ZEND_ACC_PROTECTED_SET | ZEND_ACC_PRIVATE_SET));
}
#if PHP_VERSION_ID >= 80400
/* fn_proxy slot cached across calls — first invocation fills it via method
* lookup; subsequent invocations reuse the resolved zend_function*. */
static zend_function *dc_set_raw_no_lazy_fn = NULL;
/* HashTable destructor for lazy_init_refl_cache (releases cached
* ReflectionProperty instances). Defined later; forward-declared here. */
static void dc_lazy_refl_cache_dtor(zval *zv);
/* Delegates to ReflectionProperty::setRawValueWithoutLazyInitialization because the
* required engine helpers (zend_lazy_object_decr_lazy_props, _realize) aren't ZEND_API.
* Per-request cache keyed on pi — the ReflectionProperty is per-class, not per-instance. */
static bool dc_set_raw_value_without_lazy_init(zend_object *obj,
zend_property_info *pi, zend_string *name, zval *value)
{
HashTable *cache = &DC_G(lazy_init_refl_cache);
zend_object *refl_obj = NULL;
if (cache->nTableSize) {
refl_obj = zend_hash_index_find_ptr(cache, (zend_ulong) (uintptr_t) pi);
}
if (!refl_obj) {
zval refl_zv;
if (UNEXPECTED(object_init_ex(&refl_zv, reflection_property_ptr) != SUCCESS)) {
return false;
}
zval ctor_args[2];
ZVAL_STR_COPY(&ctor_args[0], pi->ce->name);
ZVAL_STR_COPY(&ctor_args[1], name);
zend_call_method_with_2_params(Z_OBJ(refl_zv), reflection_property_ptr,
&reflection_property_ptr->constructor, "__construct", NULL,
&ctor_args[0], &ctor_args[1]);
zval_ptr_dtor(&ctor_args[0]);
zval_ptr_dtor(&ctor_args[1]);
if (UNEXPECTED(EG(exception))) {
zval_ptr_dtor(&refl_zv);
return false;
}
if (!cache->nTableSize) {
zend_hash_init(cache, 8, NULL, dc_lazy_refl_cache_dtor, 0);
}
refl_obj = Z_OBJ(refl_zv);
zend_hash_index_add_ptr(cache, (zend_ulong) (uintptr_t) pi, refl_obj);
/* Cache holds the only reference; refcount stays at 1. */
}
zval method_args[2];
ZVAL_OBJ_COPY(&method_args[0], obj);
ZVAL_COPY(&method_args[1], value);
zend_call_method_with_2_params(refl_obj, reflection_property_ptr,
&dc_set_raw_no_lazy_fn,
"setRawValueWithoutLazyInitialization", NULL,
&method_args[0], &method_args[1]);
zval_ptr_dtor(&method_args[0]);
zval_ptr_dtor(&method_args[1]);
return !EG(exception);
}
#endif
/* Default dispatch matches ReflectionProperty::setRawValue. The non-obvious branch
* is the hook trampoline path: zend_std_write_property's recursion check sees
* prop_info on execute_data->func and short-circuits to the backing write,
* bypassing the user set hook while keeping the type-check.
* Caller must have verified dc_is_backed_declared_property(pi). */
static bool dc_write_backed_property(zend_object *obj, zend_property_info *pi,
zend_string *name, zval *value, zend_long flags)
{
#if PHP_VERSION_ID >= 80400
bool call_hooks = (flags & DEEPCLONE_HYDRATE_CALL_HOOKS) != 0;
bool no_lazy_init = (flags & DEEPCLONE_HYDRATE_NO_LAZY_INIT) != 0;
/* Lazy objects: a direct slot write would bypass the engine's realization
* hook and leave the object in a half-initialized state. Route through
* zend_update_property_ex() which triggers realization on first write.
* DEEPCLONE_HYDRATE_NO_LAZY_INIT has its own opt-out fast path below. */
if (!no_lazy_init && UNEXPECTED(!zend_lazy_object_initialized(obj))) {
zend_update_property_ex(pi->ce, obj, name, value);
return !EG(exception);
}
#endif
zval *slot = OBJ_PROP(obj, pi->offset);
/* Idempotent readonly write — readonly and hooks are XOR, so no trampoline concern. */
if ((pi->flags & ZEND_ACC_READONLY)
&& Z_TYPE_P(slot) != IS_UNDEF
&& !(Z_PROP_FLAG_P(slot) & IS_PROP_UNINIT)
&& zend_is_identical(slot, value))
{
return true;
}
/* null → uninitialized for non-nullable typed slots; hooked props excluded
* (no backing slot to "unset", and the set hook may handle null itself).
* Skip the shortcut on lazy objects — a direct slot write would bypass
* the lazy-props bookkeeping. On NO_LAZY_INIT + lazy we fall through to
* the Reflection-based path below, which enforces type semantics. */
if (Z_TYPE_P(value) == IS_NULL
&& ZEND_TYPE_IS_SET(pi->type)
&& !ZEND_TYPE_ALLOW_NULL(pi->type)
&& !DC_PROP_HAS_HOOKS(pi)
#if PHP_VERSION_ID >= 80400
&& zend_lazy_object_initialized(obj)
#endif
) {
if (Z_TYPE_P(slot) != IS_UNDEF) {
zval old;
ZVAL_COPY_VALUE(&old, slot);
ZVAL_UNDEF(slot);
Z_PROP_FLAG_P(slot) |= IS_PROP_UNINIT;
zval_ptr_dtor(&old);
} else {
Z_PROP_FLAG_P(slot) |= IS_PROP_UNINIT;
}
return true;
}
#if PHP_VERSION_ID >= 80100
/* Property-type-only decision: hook presence and CALL_HOOKS don't influence it. */
zval enum_holder;
bool enum_holder_used = false;
if ((Z_TYPE_P(value) == IS_LONG || Z_TYPE_P(value) == IS_STRING)
&& ZEND_TYPE_HAS_NAME(pi->type)
&& !ZEND_TYPE_HAS_LIST(pi->type)
/* Only cast for types of the form `Enum` or `?Enum` — unions like
* `Enum|string|int` already accept the scalar literally, so casting
* it to an enum case would be surprising. */
&& (ZEND_TYPE_PURE_MASK(pi->type) & ~MAY_BE_NULL) == 0)
{
zend_class_entry *type_ce = zend_lookup_class_ex(
ZEND_TYPE_NAME(pi->type), NULL, ZEND_FETCH_CLASS_NO_AUTOLOAD);
if (type_ce && (type_ce->ce_flags & ZEND_ACC_ENUM)
&& type_ce->enum_backing_type != IS_UNDEF)
{
/* Enum::from() for parity with polyfill: standard TypeError/ValueError, scalar coercion. */
ZVAL_UNDEF(&enum_holder);
zend_call_method_with_1_params(NULL, type_ce, NULL, "from",
&enum_holder, value);
if (UNEXPECTED(EG(exception))) {
return false;
}
value = &enum_holder;
enum_holder_used = true;
}
}
#endif
#if PHP_VERSION_ID >= 80400
/* Skip the Reflection round-trip when there's no lazy-init to skip. */
if (no_lazy_init && !zend_lazy_object_initialized(obj)) {
bool ok = dc_set_raw_value_without_lazy_init(obj, pi, name, value);
#if PHP_VERSION_ID >= 80100
if (enum_holder_used) {
zval_ptr_dtor(&enum_holder);
}
#endif
return ok;
}
#endif
if (!ZEND_TYPE_IS_SET(pi->type) && !DC_PROP_HAS_HOOKS(pi)) {
/* Move the old value out before running its destructor: a __destruct
* on the old value can legitimately read (or reassign) this same slot.
* Install the new value first so reentrant reads see a valid slot. */
zval old;
ZVAL_COPY_VALUE(&old, slot);
ZVAL_COPY(slot, value);
zval_ptr_dtor(&old);
}
#if PHP_VERSION_ID >= 80400
else if (!call_hooks && DC_PROP_HAS_HOOKS(pi) && pi->hooks[ZEND_PROPERTY_HOOK_SET]) {
zend_function *trampoline = zend_get_property_hook_trampoline(
pi, ZEND_PROPERTY_HOOK_SET, name);
zend_call_known_instance_method_with_1_params(trampoline, obj, NULL, value);
}
#endif
else {
zend_update_property_ex(pi->ce, obj, name, value);
}
#if PHP_VERSION_ID >= 80100
if (enum_holder_used) {
zval_ptr_dtor(&enum_holder);
}
#endif
return !EG(exception);
}
/* ── Core traversal ─────────────────────────────────────────── */
/* Mask markers: TRUE=obj_ref, FALSE=hard_ref, LONG(0)=named_closure,
* STRING("e")=enum, ARRAY=nested sub-mask. */
#define DC_MASK_OBJ_REF(m) ZVAL_TRUE(m)
#define DC_MASK_HARD_REF(m) ZVAL_FALSE(m)
#define DC_MASK_NAMED_CLOSURE(m) ZVAL_LONG((m), 0)
/* Test whether a mask slot carries a particular marker. */
#define DC_MASK_IS_OBJ_REF(m) (Z_TYPE_P(m) == IS_TRUE)
#define DC_MASK_IS_HARD_REF(m) (Z_TYPE_P(m) == IS_FALSE)
#define DC_MASK_IS_NAMED_CLOSURE(m) (Z_TYPE_P(m) == IS_LONG && Z_LVAL_P(m) == 0)
static void dc_copy_value(dc_ctx *ctx, zval *src, zval *dst, zval *mask_dst);
static void dc_copy_array(dc_ctx *ctx, HashTable *src_ht, zval *dst, zval *mask_dst);
static void dc_copy_array(dc_ctx *ctx, HashTable *src_ht, zval *dst, zval *mask_dst)
{
zend_string *key;
zend_ulong idx;
zval *src_val;
uint32_t n = zend_hash_num_elements(src_ht);
array_init_size(dst, n);
/* Seed mask slots with IS_NULL (not IS_UNDEF — HT iteration skips those). */
array_init_size(mask_dst, n);
/* Fast path: packed source without holes → lockstep arPacked walk. */
if (EXPECTED(HT_IS_PACKED(src_ht) && HT_IS_WITHOUT_HOLES(src_ht))) {
HashTable *dst_ht = Z_ARRVAL_P(dst);
HashTable *mask_ht = Z_ARRVAL_P(mask_dst);
zend_hash_real_init_packed(dst_ht);
zend_hash_real_init_packed(mask_ht);
ZEND_HASH_FILL_PACKED(dst_ht) {
for (uint32_t i = 0; i < n; i++) {
ZVAL_UNDEF(__fill_val);
ZEND_HASH_FILL_NEXT();
}
} ZEND_HASH_FILL_END();
ZEND_HASH_FILL_PACKED(mask_ht) {
for (uint32_t i = 0; i < n; i++) {
ZEND_HASH_FILL_SET_NULL();
ZEND_HASH_FILL_NEXT();
}
} ZEND_HASH_FILL_END();
zval *dst_slot = dst_ht->arPacked;
zval *mask_slot = mask_ht->arPacked;
ZEND_HASH_PACKED_FOREACH_VAL(src_ht, src_val) {
dc_copy_value(ctx, src_val, dst_slot, mask_slot);
if (UNEXPECTED(EG(exception))) return;
dst_slot++;
mask_slot++;
} ZEND_HASH_FOREACH_END();
return;
}
/* Force hash (mixed) storage up front. dc_copy_value on a reference
* stashes new_dst_slot in ref_entry->tree_pos; if the first insert here
* transitioned dst from packed to hash mode, the later zend_hash_add_new
* would free the packed storage and leave that tree_pos dangling. */
zend_hash_real_init_mixed(Z_ARRVAL_P(dst));
zend_hash_real_init_mixed(Z_ARRVAL_P(mask_dst));
ZEND_HASH_FOREACH_KEY_VAL(src_ht, idx, key, src_val) {
zval undef, null_marker;
ZVAL_UNDEF(&undef);
ZVAL_NULL(&null_marker);
zval *new_dst_slot, *new_mask_slot;
if (key) {
new_dst_slot = zend_hash_add_new(Z_ARRVAL_P(dst), key, &undef);
new_mask_slot = zend_hash_add_new(Z_ARRVAL_P(mask_dst), key, &null_marker);
} else {
new_dst_slot = zend_hash_index_add_new(Z_ARRVAL_P(dst), idx, &undef);
new_mask_slot = zend_hash_index_add_new(Z_ARRVAL_P(mask_dst), idx, &null_marker);
}
dc_copy_value(ctx, src_val, new_dst_slot, new_mask_slot);
if (UNEXPECTED(EG(exception))) return;
} ZEND_HASH_FOREACH_END();
}
static void dc_mask_cleanup(zval *mask);
/* zend_hash_apply callback: drop IS_NULL placeholders (the seeds dropped by
* dc_copy_array() that were never overwritten by a real marker, and the slots
* cleared by the unshared-ref unwrap pass). */
static int dc_mask_cleanup_apply(zval *v)
{
if (Z_TYPE_P(v) == IS_ARRAY) {
dc_mask_cleanup(v);
if (Z_TYPE_P(v) == IS_NULL) {
return ZEND_HASH_APPLY_REMOVE;
}
return ZEND_HASH_APPLY_KEEP;
}
return Z_TYPE_P(v) == IS_NULL ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP;
}
/* Recursively strip the IS_NULL placeholders that dc_copy_array() seeded into
* the mask buckets. After all real markers have been written, anything still
* IS_NULL means "no marker was written for this slot" — drop it. If the
* resulting array is empty, collapse the mask zval to NULL so callers see it
* as "no mask at all". */
static void dc_mask_cleanup(zval *mask)
{
if (Z_TYPE_P(mask) != IS_ARRAY) {
return;
}
SEPARATE_ARRAY(mask);
HashTable *mht = Z_ARRVAL_P(mask);
zend_hash_apply(mht, dc_mask_cleanup_apply);
if (zend_hash_num_elements(mht) == 0) {
zval_ptr_dtor(mask);
ZVAL_NULL(mask);
}
}
static void dc_copy_value(dc_ctx *ctx, zval *src, zval *dst, zval *mask_dst)
{
/* Bail out early if we're about to overflow the C stack. Throws \Error
* via zend_call_stack_size_error(); callers propagate by checking
* EG(exception), which is how the rest of this file already handles
* errors. */
if (UNEXPECTED(dc_check_stack_limit())) {
return;
}
bool is_ref = 0;
uint32_t ref_idx = 0;
/* ── Reference detection (cold — refs are rare) ── */
if (UNEXPECTED(Z_ISREF_P(src))) {
zend_reference *ref = Z_REF_P(src);
zval *inner = &ref->val;
is_ref = 1;
ctx->is_static = 0;
/* Check if we've seen this reference before. Same raw-pointer key
* as dc_ref_add(). */
zval *existing = zend_hash_index_find(&ctx->ref_map, (zend_ulong)(uintptr_t)ref);
if (existing) {
/* Re-encounter: emit -refId, set mask=false */
uint32_t idx = (uint32_t)Z_LVAL_P(existing);
ctx->refs[idx].count++;