forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSObject.cpp
More file actions
3250 lines (2916 loc) · 110 KB
/
JSObject.cpp
File metadata and controls
3250 lines (2916 loc) · 110 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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/VM/JSObject.h"
#include "hermes/VM/BuildMetadata.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/HostModel.h"
#include "hermes/VM/InternalProperty.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSDate.h"
#include "hermes/VM/JSProxy.h"
#include "hermes/VM/Operations.h"
#include "llvh/ADT/SmallSet.h"
namespace hermes {
namespace vm {
ObjectVTable JSObject::vt{
VTable(
CellKind::ObjectKind,
cellSize<JSObject>(),
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr, // externalMemorySize
VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Object,
JSObject::_snapshotNameImpl,
JSObject::_snapshotAddEdgesImpl,
nullptr,
JSObject::_snapshotAddLocationsImpl}),
JSObject::_getOwnIndexedRangeImpl,
JSObject::_haveOwnIndexedImpl,
JSObject::_getOwnIndexedPropertyFlagsImpl,
JSObject::_getOwnIndexedImpl,
JSObject::_setOwnIndexedImpl,
JSObject::_deleteOwnIndexedImpl,
JSObject::_checkAllOwnIndexedImpl,
};
void ObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) {
// This call is just for debugging and consistency purposes.
mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSObject>());
const auto *self = static_cast<const JSObject *>(cell);
mb.addField("parent", &self->parent_);
mb.addField("class", &self->clazz_);
mb.addField("propStorage", &self->propStorage_);
// Declare the direct properties.
static const char *directPropName[JSObject::DIRECT_PROPERTY_SLOTS] = {
"directProp0", "directProp1", "directProp2", "directProp3"};
for (unsigned i = mb.getJSObjectOverlapSlots();
i < JSObject::DIRECT_PROPERTY_SLOTS;
++i) {
mb.addField(directPropName[i], self->directProps() + i);
}
}
#ifdef HERMESVM_SERIALIZE
void JSObject::serializeObjectImpl(
Serializer &s,
const GCCell *cell,
unsigned overlapSlots) {
auto *self = vmcast<const JSObject>(cell);
s.writeData(&self->flags_, sizeof(ObjectFlags));
s.writeRelocation(self->parent_.get(s.getRuntime()));
s.writeRelocation(self->clazz_.get(s.getRuntime()));
// propStorage_ : GCPointer<PropStorage> is also ArrayStorage. Serialize
// *propStorage_ with this JSObject.
bool hasArray = (bool)self->propStorage_;
s.writeInt<uint8_t>(hasArray);
if (hasArray) {
ArrayStorage::serializeArrayStorage(
s, self->propStorage_.get(s.getRuntime()));
}
// Record the number of overlap slots, so that the deserialization code
// doesn't need to keep track of it.
s.writeInt<uint8_t>(overlapSlots);
for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {
s.writeHermesValue(self->directProps()[i]);
}
}
void ObjectSerialize(Serializer &s, const GCCell *cell) {
JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSObject>());
s.endObject(cell);
}
void ObjectDeserialize(Deserializer &d, CellKind kind) {
assert(kind == CellKind::ObjectKind && "Expected JSObject");
void *mem = d.getRuntime()->alloc</*fixedSize*/ true>(cellSize<JSObject>());
auto *obj = new (mem) JSObject(d, &JSObject::vt.base);
d.endObject(obj);
}
JSObject::JSObject(Deserializer &d, const VTable *vtp)
: GCCell(&d.getRuntime()->getHeap(), vtp) {
d.readData(&flags_, sizeof(ObjectFlags));
d.readRelocation(&parent_, RelocationKind::GCPointer);
d.readRelocation(&clazz_, RelocationKind::GCPointer);
if (d.readInt<uint8_t>()) {
propStorage_.set(
d.getRuntime(),
ArrayStorage::deserializeArrayStorage(d),
&d.getRuntime()->getHeap());
}
auto overlapSlots = d.readInt<uint8_t>();
for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {
d.readHermesValue(&directProps()[i]);
}
}
#endif
PseudoHandle<JSObject> JSObject::create(
Runtime *runtime,
Handle<JSObject> parentHandle) {
JSObjectAlloc<JSObject> mem{runtime};
return mem.initToPseudoHandle(new (mem) JSObject(
runtime,
&vt.base,
*parentHandle,
runtime->getHiddenClassForPrototypeRaw(
*parentHandle,
numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),
GCPointerBase::NoBarriers()));
}
PseudoHandle<JSObject> JSObject::create(Runtime *runtime) {
JSObjectAlloc<JSObject> mem{runtime};
JSObject *objProto = runtime->objectPrototypeRawPtr;
return mem.initToPseudoHandle(new (mem) JSObject(
runtime,
&vt.base,
objProto,
runtime->getHiddenClassForPrototypeRaw(
objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),
GCPointerBase::NoBarriers()));
}
PseudoHandle<JSObject> JSObject::create(
Runtime *runtime,
unsigned propertyCount) {
JSObjectAlloc<JSObject> mem{runtime};
JSObject *objProto = runtime->objectPrototypeRawPtr;
auto self = mem.initToPseudoHandle(new (mem) JSObject(
runtime,
&vt.base,
objProto,
runtime->getHiddenClassForPrototypeRaw(
objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),
GCPointerBase::NoBarriers()));
return runtime->ignoreAllocationFailure(
JSObject::allocatePropStorage(std::move(self), runtime, propertyCount));
}
PseudoHandle<JSObject> JSObject::create(
Runtime *runtime,
Handle<HiddenClass> clazz) {
auto obj = JSObject::create(runtime, clazz->getNumProperties());
obj->clazz_.set(runtime, *clazz, &runtime->getHeap());
// If the hidden class has index like property, we need to clear the fast path
// flag.
if (LLVM_UNLIKELY(obj->clazz_.get(runtime)->getHasIndexLikeProperties()))
obj->flags_.fastIndexProperties = false;
return obj;
}
void JSObject::initializeLazyObject(
Runtime *runtime,
Handle<JSObject> lazyObject) {
assert(lazyObject->flags_.lazyObject && "object must be lazy");
// object is now assumed to be a regular object.
lazyObject->flags_.lazyObject = 0;
// only functions can be lazy.
assert(vmisa<Callable>(lazyObject.get()) && "unexpected lazy object");
Callable::defineLazyProperties(Handle<Callable>::vmcast(lazyObject), runtime);
}
ObjectID JSObject::getObjectID(JSObject *self, Runtime *runtime) {
if (LLVM_LIKELY(self->flags_.objectID))
return self->flags_.objectID;
// Object ID does not yet exist, get next unique global ID..
self->flags_.objectID = runtime->generateNextObjectID();
// Make sure it is not zero.
if (LLVM_UNLIKELY(!self->flags_.objectID))
--self->flags_.objectID;
return self->flags_.objectID;
}
CallResult<PseudoHandle<JSObject>> JSObject::getPrototypeOf(
PseudoHandle<JSObject> selfHandle,
Runtime *runtime) {
if (LLVM_LIKELY(!selfHandle->isProxyObject())) {
return createPseudoHandle(selfHandle->getParent(runtime));
}
return JSProxy::getPrototypeOf(
runtime->makeHandle(std::move(selfHandle)), runtime);
}
namespace {
CallResult<bool> proxyOpFlags(
Runtime *runtime,
PropOpFlags opFlags,
const char *msg,
CallResult<bool> res) {
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (!*res && opFlags.getThrowOnError()) {
return runtime->raiseTypeError(msg);
}
return res;
}
} // namespace
CallResult<bool> JSObject::setParent(
JSObject *self,
Runtime *runtime,
JSObject *parent,
PropOpFlags opFlags) {
if (LLVM_UNLIKELY(self->isProxyObject())) {
return proxyOpFlags(
runtime,
opFlags,
"Object is not extensible.",
JSProxy::setPrototypeOf(
runtime->makeHandle(self), runtime, runtime->makeHandle(parent)));
}
// ES9 9.1.2
// 4.
if (self->parent_.get(runtime) == parent)
return true;
// 5.
if (!self->isExtensible()) {
if (opFlags.getThrowOnError()) {
return runtime->raiseTypeError("Object is not extensible.");
} else {
return false;
}
}
// 6-8. Check for a prototype cycle.
for (JSObject *cur = parent; cur; cur = cur->parent_.get(runtime)) {
if (cur == self) {
if (opFlags.getThrowOnError()) {
return runtime->raiseTypeError("Prototype cycle detected");
} else {
return false;
}
} else if (LLVM_UNLIKELY(cur->isProxyObject())) {
// TODO this branch should also be used for module namespace and
// immutable prototype exotic objects.
break;
}
}
// 9.
self->parent_.set(runtime, parent, &runtime->getHeap());
// 10.
return true;
}
void JSObject::allocateNewSlotStorage(
Handle<JSObject> selfHandle,
Runtime *runtime,
SlotIndex newSlotIndex,
Handle<> valueHandle) {
// If it is a direct property, just store the value and we are done.
if (LLVM_LIKELY(newSlotIndex < DIRECT_PROPERTY_SLOTS)) {
selfHandle->directProps()[newSlotIndex].set(
*valueHandle, &runtime->getHeap());
return;
}
// Make the slot index relative to the indirect storage.
newSlotIndex -= DIRECT_PROPERTY_SLOTS;
// Allocate a new property storage if not already allocated.
if (LLVM_UNLIKELY(!selfHandle->propStorage_)) {
// Allocate new storage.
assert(newSlotIndex == 0 && "allocated slot must be at end");
auto arrRes = runtime->ignoreAllocationFailure(
PropStorage::create(runtime, DEFAULT_PROPERTY_CAPACITY));
selfHandle->propStorage_.set(
runtime, vmcast<PropStorage>(arrRes), &runtime->getHeap());
} else if (LLVM_UNLIKELY(
newSlotIndex >=
selfHandle->propStorage_.get(runtime)->capacity())) {
// Reallocate the existing one.
assert(
newSlotIndex == selfHandle->propStorage_.get(runtime)->size() &&
"allocated slot must be at end");
auto hnd = runtime->makeMutableHandle(selfHandle->propStorage_);
PropStorage::resize(hnd, runtime, newSlotIndex + 1);
selfHandle->propStorage_.set(runtime, *hnd, &runtime->getHeap());
}
{
NoAllocScope scope{runtime};
auto *const propStorage = selfHandle->propStorage_.getNonNull(runtime);
if (newSlotIndex >= propStorage->size()) {
assert(
newSlotIndex == propStorage->size() &&
"allocated slot must be at end");
PropStorage::resizeWithinCapacity(propStorage, runtime, newSlotIndex + 1);
}
// If we don't need to resize, just store it directly.
propStorage->at(newSlotIndex).set(*valueHandle, &runtime->getHeap());
}
}
CallResult<PseudoHandle<>> JSObject::getNamedPropertyValue_RJS(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<JSObject> propObj,
NamedPropertyDescriptor desc) {
assert(
!selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&
"getNamedPropertyValue_RJS cannot be used with proxy objects");
if (LLVM_LIKELY(!desc.flags.accessor))
return createPseudoHandle(getNamedSlotValue(propObj.get(), runtime, desc));
auto *accessor =
vmcast<PropertyAccessor>(getNamedSlotValue(propObj.get(), runtime, desc));
if (!accessor->getter)
return createPseudoHandle(HermesValue::encodeUndefinedValue());
// Execute the accessor on this object.
return accessor->getter.get(runtime)->executeCall0(
runtime->makeHandle(accessor->getter), runtime, selfHandle);
}
CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<JSObject> propObj,
ComputedPropertyDescriptor desc) {
assert(
!selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&
"getComputedPropertyValue_RJS cannot be used with proxy objects");
if (LLVM_LIKELY(!desc.flags.accessor))
return createPseudoHandle(
getComputedSlotValue(propObj.get(), runtime, desc));
auto *accessor = vmcast<PropertyAccessor>(
getComputedSlotValue(propObj.get(), runtime, desc));
if (!accessor->getter)
return createPseudoHandle(HermesValue::encodeUndefinedValue());
// Execute the accessor on this object.
return accessor->getter.get(runtime)->executeCall0(
runtime->makeHandle(accessor->getter), runtime, selfHandle);
}
CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<JSObject> propObj,
ComputedPropertyDescriptor desc,
Handle<> nameValHandle) {
if (!propObj) {
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
if (LLVM_LIKELY(!desc.flags.proxyObject)) {
return JSObject::getComputedPropertyValue_RJS(
selfHandle, runtime, propObj, desc);
}
CallResult<Handle<>> keyRes = toPropertyKey(runtime, nameValHandle);
if (LLVM_UNLIKELY(keyRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
CallResult<bool> hasRes = JSProxy::hasComputed(propObj, runtime, *keyRes);
if (LLVM_UNLIKELY(hasRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (!*hasRes) {
return createPseudoHandle(HermesValue::encodeEmptyValue());
}
return JSProxy::getComputed(propObj, runtime, *keyRes, selfHandle);
}
CallResult<Handle<JSArray>> JSObject::getOwnPropertyKeys(
Handle<JSObject> selfHandle,
Runtime *runtime,
OwnKeysFlags okFlags) {
assert(
(okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) &&
"Can't exclude symbols and strings");
if (LLVM_UNLIKELY(
selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) {
if (selfHandle->flags_.proxyObject) {
CallResult<PseudoHandle<JSArray>> proxyRes =
JSProxy::ownPropertyKeys(selfHandle, runtime, okFlags);
if (LLVM_UNLIKELY(proxyRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return runtime->makeHandle(std::move(*proxyRes));
}
assert(selfHandle->flags_.lazyObject && "descriptor flags are impossible");
initializeLazyObject(runtime, selfHandle);
}
auto range = getOwnIndexedRange(selfHandle.get(), runtime);
// Estimate the capacity of the output array. This estimate is only
// reasonable for the non-symbol case.
uint32_t capacity = okFlags.getIncludeNonSymbols()
? (selfHandle->clazz_.get(runtime)->getNumProperties() + range.second -
range.first)
: 0;
auto arrayRes = JSArray::create(runtime, capacity, 0);
if (LLVM_UNLIKELY(arrayRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto array = runtime->makeHandle(std::move(*arrayRes));
// Optional array of SymbolIDs reported via host object API
llvh::Optional<Handle<JSArray>> hostObjectSymbols;
size_t hostObjectSymbolCount = 0;
// If current object is a host object we need to deduplicate its properties
llvh::SmallSet<SymbolID::RawType, 16> dedupSet;
// Output index.
uint32_t index = 0;
// Avoid allocating a new handle per element.
MutableHandle<> tmpHandle{runtime};
// Number of indexed properties.
uint32_t numIndexed = 0;
// Regular properties with names that are array indexes are stashed here, if
// encountered.
llvh::SmallVector<uint32_t, 8> indexNames{};
// Iterate the named properties excluding those which use Symbols.
if (okFlags.getIncludeNonSymbols()) {
// Get host object property names
if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {
assert(
range.first == range.second &&
"Host objects cannot own indexed range");
auto hostSymbolsRes =
vmcast<HostObject>(selfHandle.get())->getHostPropertyNames();
if (hostSymbolsRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if ((hostObjectSymbolCount = (**hostSymbolsRes)->getEndIndex()) != 0) {
Handle<JSArray> hostSymbols = *hostSymbolsRes;
hostObjectSymbols = std::move(hostSymbols);
capacity += hostObjectSymbolCount;
}
}
// Iterate the indexed properties.
GCScopeMarkerRAII marker{runtime};
for (auto i = range.first; i != range.second; ++i) {
auto res = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, i);
if (!res)
continue;
// If specified, check whether it is enumerable.
if (!okFlags.getIncludeNonEnumerable() && !res->enumerable)
continue;
tmpHandle = HermesValue::encodeDoubleValue(i);
JSArray::setElementAt(array, runtime, index++, tmpHandle);
marker.flush();
}
numIndexed = index;
HiddenClass::forEachProperty(
runtime->makeHandle(selfHandle->clazz_),
runtime,
[runtime,
okFlags,
array,
hostObjectSymbolCount,
&index,
&indexNames,
&tmpHandle,
&dedupSet](SymbolID id, NamedPropertyDescriptor desc) {
if (!isPropertyNamePrimitive(id)) {
return;
}
// If specified, check whether it is enumerable.
if (!okFlags.getIncludeNonEnumerable()) {
if (!desc.flags.enumerable)
return;
}
// Host properties might overlap with the ones recognized by the
// hidden class. If we're dealing with a host object then keep track
// of hidden class properties for the deduplication purposes.
if (LLVM_UNLIKELY(hostObjectSymbolCount > 0)) {
dedupSet.insert(id.unsafeGetRaw());
}
// Check if this property is an integer index. If it is, we stash it
// away to deal with it later. This check should be fast since most
// property names don't start with a digit.
auto propNameAsIndex = toArrayIndex(
runtime->getIdentifierTable().getStringView(runtime, id));
if (LLVM_UNLIKELY(propNameAsIndex)) {
indexNames.push_back(*propNameAsIndex);
return;
}
tmpHandle = HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(id));
JSArray::setElementAt(array, runtime, index++, tmpHandle);
});
// Iterate over HostObject properties and append them to the array. Do not
// append duplicates.
if (LLVM_UNLIKELY(hostObjectSymbols)) {
for (size_t i = 0; i < hostObjectSymbolCount; ++i) {
assert(
(*hostObjectSymbols)->at(runtime, i).isSymbol() &&
"Host object needs to return array of SymbolIDs");
marker.flush();
SymbolID id = (*hostObjectSymbols)->at(runtime, i).getSymbol();
if (dedupSet.count(id.unsafeGetRaw()) == 0) {
dedupSet.insert(id.unsafeGetRaw());
assert(
!InternalProperty::isInternal(id) &&
"host object returned reserved symbol");
auto propNameAsIndex = toArrayIndex(
runtime->getIdentifierTable().getStringView(runtime, id));
if (LLVM_UNLIKELY(propNameAsIndex)) {
indexNames.push_back(*propNameAsIndex);
continue;
}
tmpHandle = HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(id));
JSArray::setElementAt(array, runtime, index++, tmpHandle);
}
}
}
}
// Now iterate the named properties again, including only Symbols.
// We could iterate only once, if we chose to ignore (and disallow)
// own properties on HostObjects, as we do with Proxies.
if (okFlags.getIncludeSymbols()) {
MutableHandle<SymbolID> idHandle{runtime};
HiddenClass::forEachProperty(
runtime->makeHandle(selfHandle->clazz_),
runtime,
[runtime, okFlags, array, &index, &idHandle](
SymbolID id, NamedPropertyDescriptor desc) {
if (!isSymbolPrimitive(id)) {
return;
}
// If specified, check whether it is enumerable.
if (!okFlags.getIncludeNonEnumerable()) {
if (!desc.flags.enumerable)
return;
}
idHandle = id;
JSArray::setElementAt(array, runtime, index++, idHandle);
});
}
// The end (exclusive) of the named properties.
uint32_t endNamed = index;
// Properly set the length of the array.
auto cr = JSArray::setLength(
array, runtime, endNamed + indexNames.size(), PropOpFlags{});
(void)cr;
assert(
cr != ExecutionStatus::EXCEPTION && *cr && "JSArray::setLength() failed");
// If we have no index-like names, we are done.
if (LLVM_LIKELY(indexNames.empty()))
return array;
// In the unlikely event that we encountered index-like names, we need to sort
// them and merge them with the real indexed properties. Note that it is
// guaranteed that there are no clashes.
std::sort(indexNames.begin(), indexNames.end());
// Also make space for the new elements by shifting all the named properties
// to the right. First, resize the array.
JSArray::setStorageEndIndex(array, runtime, endNamed + indexNames.size());
// Shift the non-index property names. The region [numIndexed..endNamed) is
// moved to [numIndexed+indexNames.size()..array->size()).
// TODO: optimize this by implementing memcpy-like functionality in ArrayImpl.
for (uint32_t last = endNamed, toLast = array->getEndIndex();
last != numIndexed;) {
--last;
--toLast;
tmpHandle = array->at(runtime, last);
JSArray::setElementAt(array, runtime, toLast, tmpHandle);
}
// Now we need to merge the indexes in indexNames and the array
// [0..numIndexed). We start from the end and copy the larger element from
// either array.
// 1+ the destination position to copy into.
for (uint32_t toLast = numIndexed + indexNames.size(),
indexNamesLast = indexNames.size();
toLast != 0;) {
if (numIndexed) {
uint32_t a = (uint32_t)array->at(runtime, numIndexed - 1).getNumber();
uint32_t b;
if (indexNamesLast && (b = indexNames[indexNamesLast - 1]) > a) {
tmpHandle = HermesValue::encodeDoubleValue(b);
--indexNamesLast;
} else {
tmpHandle = HermesValue::encodeDoubleValue(a);
--numIndexed;
}
} else {
assert(indexNamesLast && "prematurely ran out of source values");
tmpHandle =
HermesValue::encodeDoubleValue(indexNames[indexNamesLast - 1]);
--indexNamesLast;
}
--toLast;
JSArray::setElementAt(array, runtime, toLast, tmpHandle);
}
return array;
}
/// Convert a value to string unless already converted
/// \param nameValHandle [Handle<>] the value to convert
/// \param str [MutableHandle<StringPrimitive>] the string is stored
/// there. Must be initialized to null initially.
#define LAZY_TO_STRING(runtime, nameValHandle, str) \
do { \
if (!str) { \
auto status = toString_RJS(runtime, nameValHandle); \
assert( \
status != ExecutionStatus::EXCEPTION && \
"toString() of primitive cannot fail"); \
str = status->get(); \
} \
} while (0)
/// Convert a value to an identifier unless already converted
/// \param nameValHandle [Handle<>] the value to convert
/// \param id [SymbolID] the identifier is stored there. Must be initialized
/// to INVALID_IDENTIFIER_ID initially.
#define LAZY_TO_IDENTIFIER(runtime, nameValHandle, id) \
do { \
if (id.isInvalid()) { \
CallResult<Handle<SymbolID>> idRes = \
valueToSymbolID(runtime, nameValHandle); \
if (LLVM_UNLIKELY(idRes == ExecutionStatus::EXCEPTION)) { \
return ExecutionStatus::EXCEPTION; \
} \
id = **idRes; \
} \
} while (0)
/// Convert a value to array index, if possible.
/// \param nameValHandle [Handle<>] the value to convert
/// \param str [MutableHandle<StringPrimitive>] the string is stored
/// there. Must be initialized to null initially.
/// \param arrayIndex [OptValue<uint32_t>] the array index is stored
/// there.
#define TO_ARRAY_INDEX(runtime, nameValHandle, str, arrayIndex) \
do { \
arrayIndex = toArrayIndexFastPath(*nameValHandle); \
if (!arrayIndex && !nameValHandle->isSymbol()) { \
LAZY_TO_STRING(runtime, nameValHandle, str); \
arrayIndex = toArrayIndex(runtime, str); \
} \
} while (0)
/// \return true if the flags of a new property make it suitable for indexed
/// storage. All new indexed properties are enumerable, writable and
/// configurable and have no accessors.
static bool canNewPropertyBeIndexed(DefinePropertyFlags dpf) {
return dpf.setEnumerable && dpf.enumerable && dpf.setWritable &&
dpf.writable && dpf.setConfigurable && dpf.configurable &&
!dpf.setSetter && !dpf.setGetter;
}
struct JSObject::Helper {
public:
LLVM_ATTRIBUTE_ALWAYS_INLINE
static ObjectFlags &flags(JSObject *self) {
return self->flags_;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
static OptValue<PropertyFlags>
getOwnIndexedPropertyFlags(JSObject *self, Runtime *runtime, uint32_t index) {
return JSObject::getOwnIndexedPropertyFlags(self, runtime, index);
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
static NamedPropertyDescriptor &castToNamedPropertyDescriptorRef(
ComputedPropertyDescriptor &desc) {
return desc.castToNamedPropertyDescriptorRef();
}
};
namespace {
/// ES5.1 8.12.1.
/// A helper which takes a SymbolID which caches the conversion of
/// nameValHandle if it's needed. It should be default constructed,
/// and may or may not be set. This has been measured to be a useful
/// perf win. Note that always_inline seems to be ignored on static
/// methods, so this function has to be local to the cpp file in order
/// to be inlined for the perf win.
LLVM_ATTRIBUTE_ALWAYS_INLINE
CallResult<bool> getOwnComputedPrimitiveDescriptorImpl(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
JSObject::IgnoreProxy ignoreProxy,
SymbolID &id,
ComputedPropertyDescriptor &desc) {
assert(
!nameValHandle->isObject() &&
"nameValHandle passed to "
"getOwnComputedPrimitiveDescriptor "
"cannot be an object");
// Try the fast paths first if we have "fast" index properties and the
// property name is an obvious index.
if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {
if (JSObject::Helper::flags(*selfHandle).fastIndexProperties) {
auto res = JSObject::Helper::getOwnIndexedPropertyFlags(
selfHandle.get(), runtime, *arrayIndex);
if (res) {
// This a valid array index, residing in our indexed storage.
desc.flags = *res;
desc.flags.indexed = 1;
desc.slot = *arrayIndex;
return true;
}
// This a valid array index, but we don't have it in our indexed storage,
// and we don't have index-like named properties.
return false;
}
if (!selfHandle->getClass(runtime)->getHasIndexLikeProperties() &&
!selfHandle->isHostObject() && !selfHandle->isLazy() &&
!selfHandle->isProxyObject()) {
// Early return to handle the case where an object definitely has no
// index-like properties. This avoids allocating a new StringPrimitive and
// uniquing it below.
return false;
}
}
// Convert the string to a SymbolID
LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);
// Look for a named property with this name.
if (JSObject::getOwnNamedDescriptor(
selfHandle,
runtime,
id,
JSObject::Helper::castToNamedPropertyDescriptorRef(desc))) {
return true;
}
if (LLVM_LIKELY(
!JSObject::Helper::flags(*selfHandle).indexedStorage &&
!selfHandle->isLazy() && !selfHandle->isProxyObject())) {
return false;
}
MutableHandle<StringPrimitive> strPrim{runtime};
// If we have indexed storage, perform potentially expensive conversions
// to array index and check it.
if (JSObject::Helper::flags(*selfHandle).indexedStorage) {
// If the name is a valid integer array index, store it here.
OptValue<uint32_t> arrayIndex;
// Try to convert the property name to an array index.
TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex);
if (arrayIndex) {
auto res = JSObject::Helper::getOwnIndexedPropertyFlags(
selfHandle.get(), runtime, *arrayIndex);
if (res) {
desc.flags = *res;
desc.flags.indexed = 1;
desc.slot = *arrayIndex;
return true;
}
}
return false;
}
if (selfHandle->isLazy()) {
JSObject::initializeLazyObject(runtime, selfHandle);
return JSObject::getOwnComputedPrimitiveDescriptor(
selfHandle, runtime, nameValHandle, ignoreProxy, desc);
}
assert(selfHandle->isProxyObject() && "descriptor flags are impossible");
if (ignoreProxy == JSObject::IgnoreProxy::Yes) {
return false;
}
return JSProxy::getOwnProperty(
selfHandle, runtime, nameValHandle, desc, nullptr);
}
} // namespace
CallResult<bool> JSObject::getOwnComputedPrimitiveDescriptor(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
JSObject::IgnoreProxy ignoreProxy,
ComputedPropertyDescriptor &desc) {
SymbolID id{};
return getOwnComputedPrimitiveDescriptorImpl(
selfHandle, runtime, nameValHandle, ignoreProxy, id, desc);
}
CallResult<bool> JSObject::getOwnComputedDescriptor(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
ComputedPropertyDescriptor &desc) {
auto converted = toPropertyKeyIfObject(runtime, nameValHandle);
if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return JSObject::getOwnComputedPrimitiveDescriptor(
selfHandle, runtime, *converted, IgnoreProxy::No, desc);
}
CallResult<bool> JSObject::getOwnComputedDescriptor(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
ComputedPropertyDescriptor &desc,
MutableHandle<> &valueOrAccessor) {
auto converted = toPropertyKeyIfObject(runtime, nameValHandle);
if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// The proxy is ignored here so we can avoid calling
// JSProxy::getOwnProperty twice on proxies, since
// getOwnComputedPrimitiveDescriptor doesn't pass back the
// valueOrAccessor.
CallResult<bool> res = JSObject::getOwnComputedPrimitiveDescriptor(
selfHandle, runtime, *converted, IgnoreProxy::Yes, desc);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (*res) {
valueOrAccessor = getComputedSlotValue(selfHandle.get(), runtime, desc);
return true;
}
if (LLVM_UNLIKELY(selfHandle->isProxyObject())) {
return JSProxy::getOwnProperty(
selfHandle, runtime, nameValHandle, desc, &valueOrAccessor);
}
return false;
}
JSObject *JSObject::getNamedDescriptor(
Handle<JSObject> selfHandle,
Runtime *runtime,
SymbolID name,
PropertyFlags expectedFlags,
NamedPropertyDescriptor &desc) {
if (findProperty(selfHandle, runtime, name, expectedFlags, desc))
return *selfHandle;
// Check here for host object flag. This means that "normal" own
// properties above win over host-defined properties, but there's no
// cost imposed on own property lookups. This should do what we
// need in practice, and we can define host vs js property
// disambiguation however we want. This is here in order to avoid
// impacting perf for the common case where an own property exists
// in normal storage.
if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {
desc.flags.hostObject = true;
desc.flags.writable = true;
return *selfHandle;
}
if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) {
assert(
!selfHandle->flags_.proxyObject &&
"Proxy objects should never be lazy");
// Initialize the object and perform the lookup again.
JSObject::initializeLazyObject(runtime, selfHandle);
if (findProperty(selfHandle, runtime, name, expectedFlags, desc))
return *selfHandle;
}
if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) {
desc.flags.proxyObject = true;
return *selfHandle;
}
if (selfHandle->parent_) {
MutableHandle<JSObject> mutableSelfHandle{
runtime, selfHandle->parent_.getNonNull(runtime)};
do {
// Check the most common case first, at the cost of some code duplication.
if (LLVM_LIKELY(
!mutableSelfHandle->flags_.lazyObject &&
!mutableSelfHandle->flags_.hostObject &&
!mutableSelfHandle->flags_.proxyObject)) {
findProp:
if (findProperty(
mutableSelfHandle,
runtime,
name,
PropertyFlags::invalid(),
desc)) {
assert(
!selfHandle->flags_.proxyObject &&
"Proxy object parents should never have own properties");
return *mutableSelfHandle;
}
} else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.lazyObject)) {
JSObject::initializeLazyObject(runtime, mutableSelfHandle);
goto findProp;
} else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.hostObject)) {
desc.flags.hostObject = true;
desc.flags.writable = true;
return *mutableSelfHandle;
} else {
assert(
mutableSelfHandle->flags_.proxyObject &&
"descriptor flags are impossible");
desc.flags.proxyObject = true;
return *mutableSelfHandle;
}
} while ((mutableSelfHandle = mutableSelfHandle->parent_.get(runtime)));
}
return nullptr;
}
ExecutionStatus JSObject::getComputedPrimitiveDescriptor(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
MutableHandle<JSObject> &propObj,
ComputedPropertyDescriptor &desc) {
assert(
!nameValHandle->isObject() &&
"nameValHandle passed to "
"getComputedPrimitiveDescriptor cannot "
"be an object");
propObj = selfHandle.get();
SymbolID id{};
GCScopeMarkerRAII marker{runtime};
do {
// A proxy is ignored here so we can check the bit later and
// return it back to the caller for additional processing.
Handle<JSObject> loopHandle = propObj;
CallResult<bool> res = getOwnComputedPrimitiveDescriptorImpl(
loopHandle, runtime, nameValHandle, IgnoreProxy::Yes, id, desc);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {