-
Notifications
You must be signed in to change notification settings - Fork 3k
/
object-data.cpp
1696 lines (1483 loc) · 54.9 KB
/
object-data.cpp
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
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/object-data.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/collections.h"
#include "hphp/runtime/base/container-functions.h"
#include "hphp/runtime/base/exceptions.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/mixed-array-defs.h"
#include "hphp/runtime/base/object-iterator.h"
#include "hphp/runtime/base/runtime-error.h"
#include "hphp/runtime/base/request-info.h"
#include "hphp/runtime/base/tv-comparisons.h"
#include "hphp/runtime/base/tv-refcount.h"
#include "hphp/runtime/base/tv-type.h"
#include "hphp/runtime/base/type-variant.h"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/runtime/ext/generator/ext_generator.h"
#include "hphp/runtime/ext/simplexml/ext_simplexml.h"
#include "hphp/runtime/ext/datetime/ext_datetime.h"
#include "hphp/runtime/ext/std/ext_std_closure.h"
#include "hphp/runtime/vm/class.h"
#include "hphp/runtime/vm/member-operations.h"
#include "hphp/runtime/vm/memo-cache.h"
#include "hphp/runtime/vm/native-data.h"
#include "hphp/runtime/vm/native-prop-handler.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/runtime/vm/repo-global-data.h"
#include "hphp/system/systemlib.h"
#include <folly/Hash.h>
#include <folly/ScopeGuard.h>
#include <vector>
namespace HPHP {
//////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(runtime);
//////////////////////////////////////////////////////////////////////
namespace {
const StaticString s_clone("__clone");
ALWAYS_INLINE
void verifyTypeHint(const Class* thisCls,
const Class::Prop* prop,
tv_lval val) {
assertx(tvIsPlausible(*val));
assertx(type(val) != KindOfUninit);
if (!prop || RuntimeOption::EvalCheckPropTypeHints <= 0) return;
if (prop->typeConstraint.isCheckable()) {
prop->typeConstraint.verifyProperty(val, thisCls, prop->cls, prop->name);
}
if (RuntimeOption::EvalEnforceGenericsUB <= 0) return;
for (auto const& ub : prop->ubs) {
if (ub.isCheckable()) {
ub.verifyProperty(val, thisCls, prop->cls, prop->name);
}
}
}
ALWAYS_INLINE
void unsetTypeHint(const Class::Prop* prop) {
if (RuntimeOption::EvalCheckPropTypeHints <= 0) return;
if (!prop || prop->typeConstraint.isMixedResolved()) return;
raise_property_typehint_unset_error(
prop->cls,
prop->name,
prop->typeConstraint.isSoft(),
prop->typeConstraint.isUpperBound()
);
}
}
//////////////////////////////////////////////////////////////////////
// Check that the given property's type matches its type-hint.
namespace {
bool assertATypeHint(const TypeConstraint& tc, tv_rval val) {
if (!tc.isCheckable() || tc.isSoft()) return true;
if (val.type() == KindOfUninit) return tc.maybeMixed();
return tc.assertCheck(val);
}
}
bool ObjectData::assertTypeHint(tv_rval prop, Slot slot) const {
assertx(tvIsPlausible(*prop));
assertx(slot < m_cls->numDeclProperties());
auto const& propDecl = m_cls->declProperties()[slot];
if (debug && RuntimeOption::RepoAuthoritative) {
// The fact that uninitialized LateInit props are uninint isn't
// reflected in the repo-auth-type.
if (prop.type() != KindOfUninit || !(propDecl.attrs & AttrLateInit)) {
always_assert(tvMatchesRepoAuthType(*prop, propDecl.repoAuthType));
}
}
// If we're not hard enforcing, then the prop might contain anything.
if (RuntimeOption::EvalCheckPropTypeHints <= 2) return true;
if (!propDecl.typeConstraint.isCheckable() ||
propDecl.typeConstraint.isSoft()) return true;
if (propDecl.typeConstraint.isUpperBound() &&
RuntimeOption::EvalEnforceGenericsUB < 2) return true;
if (prop.type() == KindOfNull && !(propDecl.attrs & AttrNoImplicitNullable)) {
return true;
}
if (prop.type() == KindOfUninit && (propDecl.attrs & AttrLateInit)) {
return true;
}
assertATypeHint(propDecl.typeConstraint, prop);
if (RuntimeOption::EvalEnforceGenericsUB <= 2) return true;
for (auto const& ub : propDecl.ubs) {
if (!assertATypeHint(ub, prop)) return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////
NEVER_INLINE
static void freeDynPropArray(ObjectData* inst) {
auto& table = g_context->dynPropTable;
auto it = table.find(inst);
assertx(it != end(table));
assertx(it->second.arr().isPHPArray());
it->second.destroy();
table.erase(it);
}
NEVER_INLINE
void ObjectData::slowDestroyCases() {
assertx(slowDestroyCheck());
if (getAttribute(UsedMemoCache)) {
assertx(m_cls->hasMemoSlots());
auto const nSlots = m_cls->numMemoSlots();
for (Slot i = 0; i < nSlots; ++i) {
auto slot = memoSlot(i);
if (slot->isCache()) {
if (auto cache = slot->getCache()) req::destroy_raw(cache);
} else {
tvDecRefGen(*slot->getValue());
}
}
}
if (UNLIKELY(getAttribute(HasDynPropArr))) freeDynPropArray(this);
if (UNLIKELY(getAttribute(IsWeakRefed))) {
WeakRefData::invalidateWeakRef((uintptr_t)this);
}
auto const memoSize = m_cls->memoSize();
auto const ptr = reinterpret_cast<char*>(this) - memoSize;
tl_heap->objFreeIndex(ptr, m_cls->sizeIdx());
}
// Single check for a couple different unlikely actions during destruction.
inline bool ObjectData::slowDestroyCheck() const {
return m_aux16 & (HasDynPropArr | IsWeakRefed | UsedMemoCache | BigAllocSize);
}
void ObjectData::release(ObjectData* obj, const Class* cls) noexcept {
assertx(obj->kindIsValid());
assertx(!obj->hasInstanceDtor());
assertx(!obj->hasNativeData());
assertx(obj->getVMClass() == cls);
assertx(cls->releaseFunc() == &ObjectData::release);
assertx(obj->props()->checkInvariants(cls->numDeclProperties()));
// Note: cleanups done in this function are only run for classes without an
// instanceDtor. Some of these cleanups are duplicated in ~ObjectData, and
// your instanceDtor may call that to have them run; if you choose not to run
// ~ObjectData from your instanceDtor you MUST do some of them manually
// (e.g. invalidate WeakRefs). Some cleanups (e.g. clearing memo caches) are
// not done from ~ObjectData because it is assumed they're not needed for
// builtin classes (and in the case of memo caches, since the clearing needs
// to be done differently when there is native data).
// Finally, cleanups such as invalidating WeakRefs that have to be done for
// correctness MUST also be done in Collector::sweep, since none of the code
// in this function or the instanceDtor will be run when the object is
// collected by GC.
// `obj' is being torn down now---be careful about where/how you dereference
// it from here on.
obj->props()->release(cls->countablePropsEnd());
if (UNLIKELY(obj->slowDestroyCheck())) {
obj->slowDestroyCases();
} else {
assertx((obj->m_aux16 & BigAllocSize) == 0);
auto const memoSize = cls->memoSize();
auto const ptr = reinterpret_cast<char*>(obj) - memoSize;
assertx(memoSize == 0 ||
reinterpret_cast<const MemoNode*>(ptr)->objOff() == memoSize);
tl_heap->freeSmallIndex(ptr, cls->sizeIdx());
}
AARCH64_WALKABLE_FRAME();
}
///////////////////////////////////////////////////////////////////////////////
// class info
StrNR ObjectData::getClassName() const {
return m_cls->preClass()->nameStr();
}
bool ObjectData::instanceof(const String& s) const {
assertx(kindIsValid());
auto const cls = Unit::lookupClass(s.get());
return cls && instanceof(cls);
}
bool ObjectData::toBooleanImpl() const noexcept {
// Note: if you add more cases here, hhbbc/class-util.cpp also needs
// to be changed.
if (isCollection()) {
if (RuntimeOption::EvalNoticeOnCollectionToBool) {
raise_notice(
"%s to boolean cast",
collections::typeToString((CollectionType)m_kind)->data()
);
}
return collections::toBool(this);
}
if (instanceof(SimpleXMLElement_classof())) {
// SimpleXMLElement is the only non-collection class that has custom bool
// casting.
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement to boolean cast");
}
return SimpleXMLElement_objectCast(this, KindOfBoolean).toBoolean();
}
always_assert(false);
return false;
}
int64_t ObjectData::toInt64Impl() const noexcept {
// SimpleXMLElement is the only class that has proper custom int casting.
assertx(instanceof(SimpleXMLElement_classof()));
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement to integer cast");
}
return SimpleXMLElement_objectCast(this, KindOfInt64).toInt64();
}
double ObjectData::toDoubleImpl() const noexcept {
// SimpleXMLElement is the only class that has custom double casting.
assertx(instanceof(SimpleXMLElement_classof()));
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement to double cast");
}
return SimpleXMLElement_objectCast(this, KindOfDouble).toDouble();
}
///////////////////////////////////////////////////////////////////////////////
// instance methods and properties
const StaticString s_getIterator("getIterator");
Object ObjectData::iterableObject(bool& isIterable,
bool mayImplementIterator /* = true */) {
assertx(mayImplementIterator || !isIterator());
if (mayImplementIterator && isIterator()) {
isIterable = true;
return Object(this);
}
Object obj(this);
while (obj->instanceof(SystemLib::s_IteratorAggregateClass)) {
auto iterator = obj->o_invoke_few_args(s_getIterator, 0);
if (!iterator.isObject()) break;
auto o = iterator.getObjectData();
if (o->isIterator()) {
isIterable = true;
return Object{o};
}
obj.reset(o);
}
if (!isIterator() && obj->instanceof(SimpleXMLElement_classof())) {
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement used as iterator");
}
isIterable = true;
return create_object(
s_SimpleXMLElementIterator,
make_vec_array(obj)
);
}
isIterable = false;
return obj;
}
Array& ObjectData::dynPropArray() const {
assertx(getAttribute(HasDynPropArr));
assertx(g_context->dynPropTable.count(this));
assertx(g_context->dynPropTable[this].arr().isPHPArray());
return g_context->dynPropTable[this].arr();
}
void ObjectData::setDynProps(const Array& newArr) {
// don't expose the ref returned by setDynPropArr
(void)setDynPropArray(newArr);
}
void ObjectData::reserveDynProps(int numDynamic) {
// don't expose the ref returned by reserveProperties()
(void)reserveProperties(numDynamic);
}
Array& ObjectData::reserveProperties(int numDynamic /* = 2 */) {
if (getAttribute(HasDynPropArr)) {
return dynPropArray();
}
auto const allocsz = MixedArray::computeAllocBytesFromMaxElms(numDynamic);
if (UNLIKELY(allocsz > kMaxSmallSize && tl_heap->preAllocOOM(allocsz))) {
check_non_safepoint_surprise();
}
return setDynPropArray(
Array::attach(MixedArray::MakeReserveMixed(numDynamic))
);
}
Array& ObjectData::setDynPropArray(const Array& newArr) {
assertx(!g_context->dynPropTable.count(this));
assertx(!getAttribute(HasDynPropArr));
assertx(newArr.isPHPArray());
if (m_cls->forbidsDynamicProps()) {
throw_object_forbids_dynamic_props(getClassName().data());
}
if (RuntimeOption::EvalNoticeOnCreateDynamicProp) {
IterateKV(newArr.get(), [&] (TypedValue k, TypedValue v) {
auto const key = tvCastToString(k);
raiseCreateDynamicProp(key.get());
});
}
// newArr can have refcount 2 or higher
auto& arr = g_context->dynPropTable[this].arr();
assertx(arr.isPHPArray());
arr = newArr;
setAttribute(HasDynPropArr);
return arr;
}
tv_lval ObjectData::makeDynProp(const StringData* key) {
if (RuntimeOption::EvalNoticeOnCreateDynamicProp) {
raiseCreateDynamicProp(key);
}
return reserveProperties().lvalForce(StrNR(key), AccessFlags::Key);
}
void ObjectData::setDynProp(const StringData* key, TypedValue val) {
if (RuntimeOption::EvalNoticeOnCreateDynamicProp) {
raiseCreateDynamicProp(key);
}
reserveProperties().set(StrNR(key), val, true);
}
Variant ObjectData::o_get(const String& propName, bool error /* = true */,
const String& context /*= null_string*/) {
assertx(kindIsValid());
// This is not (just) a check for empty string; property names that start
// with null are intentionally being rejected here.
if (UNLIKELY(!*propName.data())) {
throw_invalid_property_name(propName);
}
Class* ctx = nullptr;
if (!context.empty()) {
ctx = Unit::lookupClass(context.get());
}
// Can't use propImpl here because if the property is not accessible and
// there is no native get, propImpl will raise_error("Cannot access ...",
// but o_get will only (maybe) raise_notice("Undefined property ..." :-(
auto const lookup = getPropImpl<false, true, true>(ctx, propName.get());
if (lookup.val && lookup.accessible) {
if (lookup.val.type() != KindOfUninit) {
return Variant::wrap(lookup.val.tv());
} else if (lookup.prop && (lookup.prop->attrs & AttrLateInit)) {
if (error) throw_late_init_prop(lookup.prop->cls, propName.get(), false);
return uninit_null();
}
}
if (error) {
raise_notice("Undefined property: %s::$%s", getClassName().data(),
propName.data());
}
return uninit_null();
}
void ObjectData::o_set(const String& propName, const Variant& v,
const String& context /* = null_string */) {
assertx(kindIsValid());
// This is not (just) a check for empty string; property names that start
// with null are intentionally being rejected here.
if (UNLIKELY(!*propName.data())) {
throw_invalid_property_name(propName);
}
Class* ctx = nullptr;
if (!context.empty()) {
ctx = Unit::lookupClass(context.get());
}
// Can't use setProp here because if the property is not accessible and
// there is no native set, setProp will raise_error("Cannot access ...",
// but o_set will skip writing and return normally.
auto const lookup = getPropImpl<true, false, true>(ctx, propName.get());
auto prop = lookup.val;
if (prop && lookup.accessible) {
if (UNLIKELY(lookup.isConst) && !isBeingConstructed()) {
throwMutateConstProp(lookup.slot);
}
auto val = tvToInit(*v.asTypedValue());
verifyTypeHint(m_cls, lookup.prop, &val);
tvSet(val, prop);
return;
}
if (!prop) {
setDynProp(propName.get(), tvToInit(*v.asTypedValue()));
}
}
void ObjectData::o_setArray(const Array& properties) {
for (ArrayIter iter(properties); iter; ++iter) {
String k = iter.first().toString();
Class* ctx = nullptr;
// If the key begins with a NUL, it's a private or protected property. Read
// the class name from between the two NUL bytes.
//
// Note: if you change this, you need to change similar logic in
// apc-object.
if (!k.empty() && k[0] == '\0') {
int subLen = k.find('\0', 1) + 1;
String cls = k.substr(1, subLen - 2);
if (cls.size() == 1 && cls[0] == '*') {
// Protected.
ctx = m_cls;
} else {
// Private.
ctx = Unit::lookupClass(cls.get());
if (!ctx) continue;
}
k = k.substr(subLen);
}
setProp(ctx, k.get(), tvAssertPlausible(iter.secondVal()));
}
}
void ObjectData::o_getArray(Array& props,
bool pubOnly /* = false */,
bool ignoreLateInit /* = false */) const {
assertx(kindIsValid());
// Fast path for classes with no declared properties
if (!m_cls->numDeclProperties() && getAttribute(HasDynPropArr)) {
props = dynPropArray();
if (RuntimeOption::EvalNoticeOnReadDynamicProp) {
IterateKV(props.get(), [&](TypedValue k, TypedValue) {
auto const key = tvCastToString(k);
raiseReadDynamicProp(key.get());
});
}
return;
}
auto cls = m_cls;
if (cls->hasReifiedGenerics()) {
auto const slot = cls->lookupReifiedInitProp();
assertx(slot != kInvalidSlot);
auto const declProps = cls->declProperties();
auto const prop = declProps[slot];
auto val = this->propRvalAtOffset(slot);
props.set(StrNR(prop.name).asString(), val.tv());
}
IteratePropToArrayOrderNoInc(
this,
[&](Slot slot, const Class::Prop& prop, tv_rval val) {
assertx(assertTypeHint(val, slot));
if (UNLIKELY(val.type() == KindOfUninit)) {
if (!ignoreLateInit && (prop.attrs & AttrLateInit)) {
throw_late_init_prop(prop.cls, prop.name, false);
}
} else if (!pubOnly || (prop.attrs & AttrPublic)) {
// Skip all the reified properties since we already prepended the
// current class' reified property to the list
if (prop.name != s_86reified_prop.get()) {
props.set(StrNR(prop.mangledName).asString(), val.tv());
}
}
},
[&](TypedValue key_tv, TypedValue val) {
props.set(key_tv, val, true);
if (RuntimeOption::EvalNoticeOnReadDynamicProp) {
auto const key = tvCastToString(key_tv);
raiseReadDynamicProp(key.get());
}
}
);
}
// a constant for ArrayIterators that changes the way the
// object is converted to an array
const int64_t ARRAY_OBJ_ITERATOR_STD_PROP_LIST = 1;
const StaticString s_flags("flags"),
s_storage("storage");
template <IntishCast IC /* = IntishCast::None */>
Array ObjectData::toArray(bool pubOnly /* = false */,
bool ignoreLateInit /* = false */) const {
assertx(kindIsValid());
// We can quickly tell if this object is a collection, which lets us avoid
// checking for each class in turn if it's not one.
if (isCollection()) {
return collections::toArray<IC>(this);
} else if (UNLIKELY(m_cls->rtAttribute(Class::CallToImpl))) {
// If we end up with other classes that need special behavior, turn the
// assert into an if and add cases.
assertx(instanceof(SimpleXMLElement_classof()));
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement to array cast");
}
return SimpleXMLElement_objectCast(this, KindOfArray).toArray();
} else if (UNLIKELY(instanceof(SystemLib::s_ArrayIteratorClass))) {
auto const flags = getProp(SystemLib::s_ArrayIteratorClass, s_flags.get());
assertx(flags.is_set());
if (UNLIKELY(flags.type() == KindOfInt64 &&
flags.val().num == ARRAY_OBJ_ITERATOR_STD_PROP_LIST)) {
auto ret = Array::CreateDArray();
o_getArray(ret, true, ignoreLateInit);
return ret;
}
check_recursion_throw();
auto const storage = getProp(SystemLib::s_ArrayIteratorClass, s_storage.get());
assertx(storage.is_set());
return tvCastToArrayLike(storage.tv());
} else if (UNLIKELY(instanceof(c_Closure::classof()))) {
return make_varray(Object(const_cast<ObjectData*>(this)));
} else if (UNLIKELY(instanceof(DateTimeData::getClass()))) {
return Native::data<DateTimeData>(this)->getDebugInfo();
} else {
auto ret = Array::CreateDArray();
o_getArray(ret, pubOnly, ignoreLateInit);
return ret;
}
}
template
Array ObjectData::toArray<IntishCast::None>(bool, bool) const;
template
Array ObjectData::toArray<IntishCast::Cast>(bool, bool) const;
namespace {
size_t getPropertyIfAccessible(ObjectData* obj,
const Class* ctx,
const StringData* key,
Array& properties,
size_t propLeft) {
auto const prop = obj->getProp(ctx, key);
if (prop && prop.type() != KindOfUninit) {
--propLeft;
properties.set(StrNR(key), prop.tv(), true);
}
return propLeft;
}
}
Array ObjectData::o_toIterArray(const String& context) {
if (!m_cls->numDeclProperties()) {
if (getAttribute(HasDynPropArr)) {
auto const props = dynPropArray();
if (RuntimeOption::EvalNoticeOnReadDynamicProp) {
IterateKV(props.get(), [&](TypedValue k, TypedValue) {
auto const key = tvCastToString(k);
raiseReadDynamicProp(key.get());
});
}
// not returning Array&; makes a copy
return props;
}
return Array::CreateDArray();
}
size_t accessibleProps = m_cls->declPropNumAccessible();
size_t size = accessibleProps;
if (getAttribute(HasDynPropArr)) {
size += dynPropArray().size();
}
Array retArray { Array::attach(MixedArray::MakeReserveMixed(size)) };
Class* ctx = nullptr;
if (!context.empty()) {
ctx = Unit::lookupClass(context.get());
}
// Get all declared properties first, bottom-to-top in the inheritance
// hierarchy, in declaration order.
const Class* klass = m_cls;
while (klass) {
const PreClass::Prop* props = klass->preClass()->properties();
const size_t numProps = klass->preClass()->numProperties();
for (size_t i = 0; i < numProps; ++i) {
auto key = const_cast<StringData*>(props[i].name());
accessibleProps = getPropertyIfAccessible(
this, ctx, key, retArray, accessibleProps);
}
klass = klass->parent();
}
if (!(m_cls->attrs() & AttrNoExpandTrait) && accessibleProps > 0) {
// we may have properties from traits
for (auto const& prop : m_cls->declProperties()) {
auto const key = prop.name.get();
if (!retArray.get()->exists(key)) {
accessibleProps = getPropertyIfAccessible(
this, ctx, key, retArray, accessibleProps);
if (accessibleProps == 0) break;
}
}
}
// Now get dynamic properties.
if (getAttribute(HasDynPropArr)) {
auto& dynProps = dynPropArray();
auto ad = dynProps.get();
ssize_t iter = ad->iter_begin();
auto pos_limit = ad->iter_end();
while (iter != pos_limit) {
ad = dynProps.get();
auto const key = ad->nvGetKey(iter);
iter = ad->iter_advance(iter);
if (RuntimeOption::EvalNoticeOnReadDynamicProp) {
auto const k = tvCastToString(key);
raiseReadDynamicProp(k.get());
}
// You can get this if you cast an array to object. These
// properties must be dynamic because you can't declare a
// property with a non-string name.
if (UNLIKELY(!isStringType(key.m_type))) {
assertx(key.m_type == KindOfInt64);
auto const val = dynProps.get()->at(key.m_data.num);
retArray.set(key.m_data.num, val);
continue;
}
auto const strKey = key.m_data.pstr;
auto const val = dynProps.get()->at(strKey);
retArray.set(StrNR(strKey), val, true /* isKey */);
}
}
return retArray;
}
static bool decode_invoke(const String& s, ObjectData* obj, bool fatal,
CallCtx& ctx) {
ctx.this_ = obj;
ctx.cls = obj->getVMClass();
ctx.dynamic = true;
ctx.func = ctx.cls->lookupMethod(s.get());
if (!ctx.func) {
// Bail if this_ is non-null AND we could not find a method.
o_invoke_failed(ctx.cls->name()->data(), s.data(), fatal);
return false;
}
// Null out this_ for statically called methods
if (ctx.func->isStaticInPrologue()) {
ctx.this_ = nullptr;
}
return true;
}
Variant ObjectData::o_invoke(const String& s, const Variant& params,
bool fatal /* = true */) {
CallCtx ctx;
if (!decode_invoke(s, this, fatal, ctx) ||
(!isContainer(params) && !params.isNull())) {
return Variant(Variant::NullInit());
}
return Variant::attach(
g_context->invokeFunc(ctx, params)
);
}
#define INVOKE_FEW_ARGS_IMPL3 \
const Variant& a0, const Variant& a1, const Variant& a2
#define INVOKE_FEW_ARGS_IMPL6 \
INVOKE_FEW_ARGS_IMPL3, \
const Variant& a3, const Variant& a4, const Variant& a5
#define INVOKE_FEW_ARGS_IMPL10 \
INVOKE_FEW_ARGS_IMPL6, \
const Variant& a6, const Variant& a7, const Variant& a8, const Variant& a9
#define INVOKE_FEW_ARGS_IMPL_ARGS INVOKE_FEW_ARGS(IMPL,INVOKE_FEW_ARGS_COUNT)
Variant ObjectData::o_invoke_few_args(const String& s, int count,
INVOKE_FEW_ARGS_IMPL_ARGS) {
CallCtx ctx;
if (!decode_invoke(s, this, true, ctx)) {
return Variant(Variant::NullInit());
}
TypedValue args[INVOKE_FEW_ARGS_COUNT];
switch(count) {
default: not_implemented();
#if INVOKE_FEW_ARGS_COUNT > 6
case 10: tvCopy(*a9.asTypedValue(), args[9]);
case 9: tvCopy(*a8.asTypedValue(), args[8]);
case 8: tvCopy(*a7.asTypedValue(), args[7]);
case 7: tvCopy(*a6.asTypedValue(), args[6]);
#endif
#if INVOKE_FEW_ARGS_COUNT > 3
case 6: tvCopy(*a5.asTypedValue(), args[5]);
case 5: tvCopy(*a4.asTypedValue(), args[4]);
case 4: tvCopy(*a3.asTypedValue(), args[3]);
#endif
case 3: tvCopy(*a2.asTypedValue(), args[2]);
case 2: tvCopy(*a1.asTypedValue(), args[1]);
case 1: tvCopy(*a0.asTypedValue(), args[0]);
case 0: break;
}
return Variant::attach(
g_context->invokeFuncFew(ctx, count, args)
);
}
ObjectData* ObjectData::clone() {
if (isCppBuiltin()) {
assertx(!m_cls->hasMemoSlots());
if (isCollection()) return collections::clone(this);
if (instanceof(c_Closure::classof())) {
return c_Closure::fromObject(this)->clone();
}
assertx(instanceof(c_Awaitable::classof()));
// cloning WaitHandles is not allowed
// invoke the instanceCtor to get the right sort of exception
auto const ctor = m_cls->instanceCtor();
ctor(m_cls);
always_assert(false);
}
// clone prevents a leak if something throws before clone() returns
Object clone;
auto const nProps = m_cls->numDeclProperties();
if (hasNativeData()) {
assertx(m_cls->instanceDtor() == Native::nativeDataInstanceDtor);
clone = Object::attach(
Native::nativeDataInstanceCopyCtor(this, m_cls, nProps)
);
assertx(clone->hasExactlyOneRef());
assertx(clone->hasInstanceDtor());
} else {
auto const alloc = allocMemoInit(m_cls);
auto const obj = new (NotNull{}, alloc.mem)
ObjectData(m_cls, InitRaw{}, alloc.flags);
clone = Object::attach(obj);
assertx(clone->hasExactlyOneRef());
assertx(!clone->hasInstanceDtor());
}
auto const cloneProps = clone->props();
cloneProps->init(m_cls->numDeclProperties());
for (auto slot = Slot{0}; slot < nProps; slot++) {
auto index = m_cls->propSlotToIndex(slot);
tvDup(*props()->at(index), cloneProps->at(index));
assertx(assertTypeHint(cloneProps->at(index), slot));
}
if (UNLIKELY(getAttribute(HasDynPropArr))) {
clone->setAttribute(HasDynPropArr);
g_context->dynPropTable.emplace(clone.get(), dynPropArray().get());
}
if (m_cls->rtAttribute(Class::HasClone)) {
assertx(!isCppBuiltin());
auto const method = clone->m_cls->lookupMethod(s_clone.get());
assertx(method);
clone->unlockObject();
SCOPE_EXIT { clone->lockObject(); };
g_context->invokeMethodV(clone.get(), method, InvokeArgs{}, false);
}
return clone.detach();
}
bool ObjectData::equal(const ObjectData& other) const {
if (this == &other) return true;
if (isCollection()) {
return collections::equals(this, &other);
}
if (UNLIKELY(instanceof(SystemLib::s_DateTimeInterfaceClass) &&
other.instanceof(SystemLib::s_DateTimeInterfaceClass))) {
return DateTimeData::compare(this, &other) == 0;
}
if (getVMClass() != other.getVMClass()) return false;
if (UNLIKELY(instanceof(SimpleXMLElement_classof()))) {
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement equality comparison");
}
// Compare the whole object (including native data), not just props
auto ar1 = SimpleXMLElement_objectCast(this, KindOfArray).toArray();
auto ar2 = SimpleXMLElement_objectCast(&other, KindOfArray).toArray();
return ArrayData::Equal(ar1.get(), ar2.get());
}
if (UNLIKELY(instanceof(c_Closure::classof()))) {
// First comparison already proves they are different
return false;
}
// check for dynamic props first because we need to short-circuit if there's
// a different number of them
auto thisSize = UNLIKELY(getAttribute(HasDynPropArr)) ?
dynPropArray().size() : 0;
size_t otherSize = 0;
ArrayData* otherDynProps = nullptr;
if (UNLIKELY(other.getAttribute(HasDynPropArr))) {
otherDynProps = other.dynPropArray().get();
otherSize = otherDynProps->size();
}
if (thisSize != otherSize) return false;
// Prevent circular referenced objects/arrays or deep ones.
check_recursion_error();
bool result = true;
IteratePropMemOrderNoInc(
this,
[&](Slot slot, const Class::Prop& prop, tv_rval thisVal) {
auto otherVal = other.propRvalAtOffset(slot);
if ((UNLIKELY(thisVal.type() == KindOfUninit) ||
UNLIKELY(otherVal.type() == KindOfUninit)) &&
(prop.attrs & AttrLateInit)) {
throw_late_init_prop(prop.cls, prop.name, false);
}
if (!tvEqual(thisVal.tv(), otherVal.tv())) {
result = false;
return true;
}
return false;
},
[&](TypedValue key, TypedValue thisVal) {
auto const otherVal = otherDynProps->get(key);
if (!otherVal.is_init() || !tvEqual(thisVal, otherVal)) {
result = false;
return true;
}
return false;
}
);
return result;
}
bool ObjectData::less(const ObjectData& other) const {
// compare is not symmetrical; order of operands matters here
return compare(other) < 0;
}
bool ObjectData::lessEqual(const ObjectData& other) const {
// compare is not symmetrical; order of operands matters here
return compare(other) <= 0;
}
bool ObjectData::more(const ObjectData& other) const {
// compare is not symmetrical; order of operands matters here
return other.compare(*this) < 0;
}
bool ObjectData::moreEqual(const ObjectData& other) const {
// compare is not symmetrical; order of operands matters here
return other.compare(*this) <= 0;
}
int64_t ObjectData::compare(const ObjectData& other) const {
if (isCollection() || other.isCollection()) {
throw_collection_compare_exception();
}
if (this == &other) return 0;
if (UNLIKELY(instanceof(SystemLib::s_DateTimeInterfaceClass) &&
other.instanceof(SystemLib::s_DateTimeInterfaceClass))) {
return DateTimeData::compare(this, &other);
}
// Return 1 for different classes to match PHP7 behavior.
if (getVMClass() != other.getVMClass()) return 1;
if (UNLIKELY(instanceof(SimpleXMLElement_classof()))) {
if (RuntimeOption::EvalNoticeOnSimpleXMLBehavior) {
raise_notice("SimpleXMLElement comparison");
}
// Compare the whole object (including native data), not just props
auto ar1 = SimpleXMLElement_objectCast(this, KindOfArray).toArray();
auto ar2 = SimpleXMLElement_objectCast(&other, KindOfArray).toArray();
return ArrayData::Compare(ar1.get(), ar2.get());
}
if (UNLIKELY(instanceof(c_Closure::classof()))) {
// comparing different closures with <=> always returns 1
return 1;
}
// check for dynamic props first, because we need to short circuit if there's
// a different number of them
auto thisSize = UNLIKELY(getAttribute(HasDynPropArr)) ?
dynPropArray().size() : 0;
size_t otherSize = 0;
ArrayData* otherDynProps = nullptr;
if (UNLIKELY(other.getAttribute(HasDynPropArr))) {
otherDynProps = other.dynPropArray().get();
otherSize = otherDynProps->size();
}
if (thisSize > otherSize) {
return 1;
} else if (thisSize < otherSize) {
return -1;
}
// Prevent circular referenced objects/arrays or deep ones.
check_recursion_error();
int64_t result = 0;
IteratePropToArrayOrderNoInc(
this,
[&](Slot slot, const Class::Prop& prop, tv_rval thisVal) {
auto otherVal = other.propRvalAtOffset(slot);
if ((UNLIKELY(thisVal.type() == KindOfUninit) ||
UNLIKELY(otherVal.type() == KindOfUninit)) &&
(prop.attrs & AttrLateInit)) {
throw_late_init_prop(prop.cls, prop.name, false);
}
auto cmp = tvCompare(thisVal.tv(), otherVal.tv());
if (cmp != 0) {
result = cmp;
return true;
}
return false;
},
[&](TypedValue key, TypedValue thisVal) {
auto const otherVal = otherDynProps->get(key);
if (!otherVal.is_init()) {
result = 1;
return true;
}
auto cmp = tvCompare(thisVal, otherVal);
if (cmp != 0) {
result = cmp;
return true;
}
return false;
}
);