-
Notifications
You must be signed in to change notification settings - Fork 54
/
ObjectGroup.cpp
1845 lines (1557 loc) · 57.3 KB
/
ObjectGroup.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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/ObjectGroup.h"
#include "mozilla/Maybe.h"
#include "mozilla/Unused.h"
#include "jsexn.h"
#include "builtin/DataViewObject.h"
#include "gc/FreeOp.h"
#include "gc/HashUtil.h"
#include "gc/Policy.h"
#include "gc/StoreBuffer.h"
#include "js/CharacterEncoding.h"
#include "js/UniquePtr.h"
#include "vm/ArrayObject.h"
#include "vm/ErrorObject.h"
#include "vm/GlobalObject.h"
#include "vm/JSObject.h"
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/RegExpObject.h"
#include "vm/Shape.h"
#include "vm/TaggedProto.h"
#include "gc/Marking-inl.h"
#include "gc/ObjectKind-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/TypeInference-inl.h"
using namespace js;
/////////////////////////////////////////////////////////////////////
// ObjectGroup
/////////////////////////////////////////////////////////////////////
ObjectGroup::ObjectGroup(const JSClass* clasp, TaggedProto proto,
JS::Realm* realm, ObjectGroupFlags initialFlags)
: headerAndClasp_(clasp),
proto_(proto),
realm_(realm),
flags_(initialFlags) {
/* Windows may not appear on prototype chains. */
MOZ_ASSERT_IF(proto.isObject(), !IsWindow(proto.toObject()));
MOZ_ASSERT(JS::StringIsASCII(clasp->name));
#ifdef DEBUG
GlobalObject* global = realm->unsafeUnbarrieredMaybeGlobal();
if (global) {
AssertTargetIsNotGray(global);
}
#endif
setGeneration(zone()->types.generation);
}
void ObjectGroup::finalize(JSFreeOp* fop) {
if (auto newScript = newScriptDontCheckGeneration()) {
newScript->clear();
fop->delete_(this, newScript, newScript->gcMallocBytes(),
MemoryUse::ObjectGroupAddendum);
}
fop->delete_(this, maybePreliminaryObjectsDontCheckGeneration(),
MemoryUse::ObjectGroupAddendum);
}
void ObjectGroup::setProtoUnchecked(TaggedProto proto) {
proto_ = proto;
MOZ_ASSERT_IF(proto_.isObject() && proto_.toObject()->isNative(),
proto_.toObject()->isDelegate());
}
void ObjectGroup::setProto(TaggedProto proto) {
MOZ_ASSERT(singleton());
setProtoUnchecked(proto);
}
size_t ObjectGroup::sizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
size_t n = 0;
if (TypeNewScript* newScript = newScriptDontCheckGeneration()) {
n += newScript->sizeOfIncludingThis(mallocSizeOf);
}
return n;
}
static inline size_t AddendumAllocSize(ObjectGroup::AddendumKind kind,
void* addendum) {
if (kind == ObjectGroup::Addendum_NewScript) {
auto newScript = static_cast<TypeNewScript*>(addendum);
return newScript->gcMallocBytes();
}
if (kind == ObjectGroup::Addendum_PreliminaryObjects) {
return sizeof(PreliminaryObjectArrayWithTemplate);
}
// Other addendum kinds point to GC memory tracked elsewhere.
return 0;
}
void ObjectGroup::setAddendum(AddendumKind kind, void* addendum,
bool isSweeping /* = flase */) {
MOZ_ASSERT(!needsSweep());
MOZ_ASSERT(kind <= (OBJECT_FLAG_ADDENDUM_MASK >> OBJECT_FLAG_ADDENDUM_SHIFT));
RemoveCellMemory(this, AddendumAllocSize(addendumKind(), addendum_),
MemoryUse::ObjectGroupAddendum, isSweeping);
if (!isSweeping) {
// Trigger a write barrier if we are clearing new script or preliminary
// object information outside of sweeping. Other addendums are immutable.
AutoSweepObjectGroup sweep(this);
switch (addendumKind()) {
case Addendum_PreliminaryObjects:
PreliminaryObjectArrayWithTemplate::writeBarrierPre(
maybePreliminaryObjects(sweep));
break;
case Addendum_NewScript:
TypeNewScript::writeBarrierPre(newScript(sweep));
break;
case Addendum_None:
break;
default:
MOZ_ASSERT(addendumKind() == kind);
}
}
flags_ &= ~OBJECT_FLAG_ADDENDUM_MASK;
flags_ |= kind << OBJECT_FLAG_ADDENDUM_SHIFT;
addendum_ = addendum;
AddCellMemory(this, AddendumAllocSize(kind, addendum),
MemoryUse::ObjectGroupAddendum);
}
/* static */
bool ObjectGroup::useSingletonForClone(JSFunction* fun) {
if (!IsTypeInferenceEnabled()) {
return false;
}
if (!fun->isInterpreted()) {
return false;
}
if (fun->isArrow()) {
return false;
}
if (fun->isSingleton()) {
return false;
}
/*
* When a function is being used as a wrapper for another function, it
* improves precision greatly to distinguish between different instances of
* the wrapper; otherwise we will conflate much of the information about
* the wrapped functions.
*
* An important example is the Class.create function at the core of the
* Prototype.js library, which looks like:
*
* var Class = {
* create: function() {
* return function() {
* this.initialize.apply(this, arguments);
* }
* }
* };
*
* Each instance of the innermost function will have a different wrapped
* initialize method. We capture this, along with similar cases, by looking
* for short scripts which use both .apply and arguments. For such scripts,
* whenever creating a new instance of the function we both give that
* instance a singleton type and clone the underlying script.
*/
if (!fun->baseScript()->isLikelyConstructorWrapper()) {
return false;
}
uint32_t begin = fun->baseScript()->sourceStart();
uint32_t end = fun->baseScript()->sourceEnd();
return end - begin <= 100;
}
/* static */
bool ObjectGroup::useSingletonForNewObject(JSContext* cx, JSScript* script,
jsbytecode* pc) {
/*
* Make a heuristic guess at a use of JSOp::New that the constructed object
* should have a fresh group. We do this when the New is immediately
* followed by a simple assignment to an object's .prototype field.
* This is designed to catch common patterns for subclassing in JS:
*
* function Super() { ... }
* function Sub1() { ... }
* function Sub2() { ... }
*
* Sub1.prototype = new Super();
* Sub2.prototype = new Super();
*
* Using distinct groups for the particular prototypes of Sub1 and
* Sub2 lets us continue to distinguish the two subclasses and any extra
* properties added to those prototype objects.
*/
if (!IsTypeInferenceEnabled()) {
return false;
}
if (script->isGenerator() || script->isAsync()) {
return false;
}
if (JSOp(*pc) != JSOp::New) {
return false;
}
pc += JSOpLength_New;
if (JSOp(*pc) != JSOp::SetProp) {
return false;
}
return script->getName(pc) == cx->names().prototype;
}
/* static */
bool ObjectGroup::useSingletonForAllocationSite(JSScript* script,
jsbytecode* pc,
JSProtoKey key) {
/*
* Objects created outside loops in global and eval scripts should have
* singleton types. For now this is only done for plain objects, but not
* typed arrays or normal arrays.
*/
if (!IsTypeInferenceEnabled()) {
return false;
}
if (script->function() && !script->treatAsRunOnce()) {
return false;
}
if (key != JSProto_Object) {
return false;
}
// All loops in the script will have a try note indicating their boundary.
uint32_t offset = script->pcToOffset(pc);
for (const TryNote& tn : script->trynotes()) {
if (tn.kind() != TryNoteKind::ForIn && tn.kind() != TryNoteKind::ForOf &&
tn.kind() != TryNoteKind::Loop) {
continue;
}
if (tn.start <= offset && offset < tn.start + tn.length) {
return false;
}
}
return true;
}
/////////////////////////////////////////////////////////////////////
// JSObject
/////////////////////////////////////////////////////////////////////
bool GlobalObject::shouldSplicePrototype() {
// During bootstrapping, we need to make sure not to splice a new prototype in
// for the global object if its __proto__ had previously been set to non-null,
// as this will change the prototype for all other objects with the same type.
return staticPrototype() == nullptr;
}
/* static */
bool JSObject::splicePrototype(JSContext* cx, HandleObject obj,
Handle<TaggedProto> proto) {
MOZ_ASSERT(cx->compartment() == obj->compartment());
/*
* For singleton groups representing only a single JSObject, the proto
* can be rearranged as needed without destroying type information for
* the old or new types.
*/
MOZ_ASSERT(obj->isSingleton());
// Windows may not appear on prototype chains.
MOZ_ASSERT_IF(proto.isObject(), !IsWindow(proto.toObject()));
#ifdef DEBUG
const JSClass* oldClass = obj->getClass();
#endif
if (proto.isObject()) {
RootedObject protoObj(cx, proto.toObject());
if (!JSObject::setDelegate(cx, protoObj)) {
return false;
}
}
// Force type instantiation when splicing lazy group.
RootedObjectGroup group(cx, JSObject::getGroup(cx, obj));
if (!group) {
return false;
}
RootedObjectGroup protoGroup(cx, nullptr);
if (proto.isObject()) {
RootedObject protoObj(cx, proto.toObject());
protoGroup = JSObject::getGroup(cx, protoObj);
if (!protoGroup) {
return false;
}
}
MOZ_ASSERT(group->clasp() == oldClass,
"splicing a prototype doesn't change a group's class");
group->setProto(proto);
return true;
}
/* static */
ObjectGroup* JSObject::makeLazyGroup(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(obj->hasLazyGroup());
MOZ_ASSERT(cx->compartment() == obj->compartment());
// Find flags which need to be specified immediately on the object.
// Don't track whether singletons are packed.
ObjectGroupFlags initialFlags =
OBJECT_FLAG_SINGLETON | OBJECT_FLAG_NON_PACKED;
if (obj->isIteratedSingleton()) {
initialFlags |= OBJECT_FLAG_ITERATED;
}
if (obj->isNative() && obj->as<NativeObject>().isIndexed()) {
initialFlags |= OBJECT_FLAG_SPARSE_INDEXES;
}
if (obj->is<ArrayObject>() && obj->as<ArrayObject>().length() > INT32_MAX) {
initialFlags |= OBJECT_FLAG_LENGTH_OVERFLOW;
}
Rooted<TaggedProto> proto(cx, obj->taggedProto());
ObjectGroup* group = ObjectGroupRealm::makeGroup(
cx, obj->nonCCWRealm(), obj->getClass(), proto, initialFlags);
if (!group) {
return nullptr;
}
AutoEnterAnalysis enter(cx);
/* Fill in the type according to the state of this object. */
if (obj->is<JSFunction>() && obj->as<JSFunction>().isInterpreted()) {
group->setInterpretedFunction(&obj->as<JSFunction>());
}
obj->setGroupRaw(group);
return group;
}
/* static */
bool JSObject::setNewGroupUnknown(JSContext* cx, ObjectGroupRealm& realm,
const JSClass* clasp, JS::HandleObject obj) {
ObjectGroup::setDefaultNewGroupUnknown(cx, realm, clasp, obj);
return JSObject::setFlags(cx, obj, BaseShape::NEW_GROUP_UNKNOWN);
}
/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm NewTable
/////////////////////////////////////////////////////////////////////
/*
* Entries for the per-realm set of groups which are the default
* types to use for some prototype. An optional associated object is used which
* allows multiple groups to be created with the same prototype. The
* associated object may be a function (for types constructed with 'new') or a
* type descriptor (for typed objects). These entries are also used for the set
* of lazy groups in the realm, which use a null associated object
* (though there are only a few of these per realm).
*/
struct ObjectGroupRealm::NewEntry {
WeakHeapPtrObjectGroup group;
// Note: This pointer is only used for equality and does not need a read
// barrier.
JSObject* associated;
NewEntry(ObjectGroup* group, JSObject* associated)
: group(group), associated(associated) {}
struct Lookup {
const JSClass* clasp;
TaggedProto proto;
JSObject* associated;
Lookup(const JSClass* clasp, TaggedProto proto, JSObject* associated)
: clasp(clasp), proto(proto), associated(associated) {
MOZ_ASSERT(clasp);
MOZ_ASSERT_IF(associated && associated->is<JSFunction>(),
clasp == &PlainObject::class_);
}
explicit Lookup(const NewEntry& entry)
: clasp(entry.group.unbarrieredGet()->clasp()),
proto(entry.group.unbarrieredGet()->proto()),
associated(entry.associated) {
MOZ_ASSERT_IF(associated && associated->is<JSFunction>(),
clasp == &PlainObject::class_);
}
};
bool needsSweep() {
return IsAboutToBeFinalized(&group) ||
(associated && IsAboutToBeFinalizedUnbarriered(&associated));
}
bool operator==(const NewEntry& other) const {
return group == other.group && associated == other.associated;
}
};
namespace js {
template <>
struct MovableCellHasher<ObjectGroupRealm::NewEntry> {
using Key = ObjectGroupRealm::NewEntry;
using Lookup = ObjectGroupRealm::NewEntry::Lookup;
static bool hasHash(const Lookup& l) {
return MovableCellHasher<TaggedProto>::hasHash(l.proto) &&
MovableCellHasher<JSObject*>::hasHash(l.associated);
}
static bool ensureHash(const Lookup& l) {
return MovableCellHasher<TaggedProto>::ensureHash(l.proto) &&
MovableCellHasher<JSObject*>::ensureHash(l.associated);
}
static inline HashNumber hash(const Lookup& lookup) {
HashNumber hash = MovableCellHasher<TaggedProto>::hash(lookup.proto);
hash = mozilla::AddToHash(
hash, MovableCellHasher<JSObject*>::hash(lookup.associated));
return mozilla::AddToHash(hash, mozilla::HashGeneric(lookup.clasp));
}
static inline bool match(const ObjectGroupRealm::NewEntry& key,
const Lookup& lookup) {
if (key.group.unbarrieredGet()->clasp() != lookup.clasp) {
return false;
}
TaggedProto proto = key.group.unbarrieredGet()->proto();
if (!MovableCellHasher<TaggedProto>::match(proto, lookup.proto)) {
return false;
}
return MovableCellHasher<JSObject*>::match(key.associated,
lookup.associated);
}
};
} // namespace js
class ObjectGroupRealm::NewTable
: public JS::WeakCache<js::GCHashSet<NewEntry, MovableCellHasher<NewEntry>,
SystemAllocPolicy>> {
using Table =
js::GCHashSet<NewEntry, MovableCellHasher<NewEntry>, SystemAllocPolicy>;
using Base = JS::WeakCache<Table>;
public:
explicit NewTable(Zone* zone) : Base(zone) {}
};
/* static*/ ObjectGroupRealm& ObjectGroupRealm::get(const ObjectGroup* group) {
return group->realm()->objectGroups_;
}
/* static*/ ObjectGroupRealm& ObjectGroupRealm::getForNewObject(JSContext* cx) {
return cx->realm()->objectGroups_;
}
MOZ_ALWAYS_INLINE ObjectGroup* ObjectGroupRealm::DefaultNewGroupCache::lookup(
const JSClass* clasp, TaggedProto proto, JSObject* associated) {
if (group_ && associated_ == associated && group_->proto() == proto &&
group_->clasp() == clasp) {
return group_;
}
return nullptr;
}
/* static */
ObjectGroup* ObjectGroup::defaultNewGroup(JSContext* cx, const JSClass* clasp,
TaggedProto proto,
JSObject* associated) {
MOZ_ASSERT(clasp);
MOZ_ASSERT_IF(associated, proto.isObject());
MOZ_ASSERT_IF(proto.isObject(),
cx->isInsideCurrentCompartment(proto.toObject()));
if (associated && !associated->is<TypeDescr>() && !IsTypeInferenceEnabled()) {
associated = nullptr;
}
if (associated) {
if (associated->is<JSFunction>()) {
// Canonicalize new functions to use the original one associated with its
// script.
associated = associated->as<JSFunction>().maybeCanonicalFunction();
// If we have previously cleared the 'new' script information for this
// function, don't try to construct another one. Also, for simplicity,
// don't bother optimizing cross-realm constructors.
if (associated && (associated->as<JSFunction>().wasNewScriptCleared() ||
associated->as<JSFunction>().realm() != cx->realm())) {
associated = nullptr;
}
} else if (associated->is<TypeDescr>()) {
if (!IsTypedObjectClass(clasp)) {
// This can happen when we call Reflect.construct with a TypeDescr as
// newTarget argument. We're not creating a TypedObject in this case, so
// don't set the TypeDescr on the group.
associated = nullptr;
}
} else {
associated = nullptr;
}
}
ObjectGroupRealm& groups = ObjectGroupRealm::getForNewObject(cx);
if (ObjectGroup* group =
groups.defaultNewGroupCache.lookup(clasp, proto, associated)) {
return group;
}
AutoEnterAnalysis enter(cx);
ObjectGroupRealm::NewTable*& table = groups.defaultNewTable;
if (!table) {
table = cx->new_<ObjectGroupRealm::NewTable>(cx->zone());
if (!table) {
return nullptr;
}
}
if (proto.isObject() && !proto.toObject()->isDelegate()) {
RootedObject protoObj(cx, proto.toObject());
if (!JSObject::setDelegate(cx, protoObj)) {
return nullptr;
}
// Objects which are prototypes of one another should be singletons, so
// that their type information can be tracked more precisely. Limit
// this group change to plain objects, to avoid issues with other types
// of singletons like typed arrays.
if (protoObj->is<PlainObject>() && !protoObj->isSingleton()) {
if (!JSObject::changeToSingleton(cx, protoObj)) {
return nullptr;
}
// |ReshapeForProtoMutation| ensures singletons will reshape when
// prototype is mutated so clear the UNCACHEABLE_PROTO flag.
if (protoObj->hasUncacheableProto()) {
HandleNativeObject nobj = protoObj.as<NativeObject>();
if (!NativeObject::clearFlag(cx, nobj, BaseShape::UNCACHEABLE_PROTO)) {
return nullptr;
}
}
}
}
ObjectGroupRealm::NewTable::AddPtr p = table->lookupForAdd(
ObjectGroupRealm::NewEntry::Lookup(clasp, proto, associated));
if (p) {
ObjectGroup* group = p->group;
MOZ_ASSERT(group->clasp() == clasp);
MOZ_ASSERT(group->proto() == proto);
groups.defaultNewGroupCache.put(group, associated);
return group;
}
ObjectGroupFlags initialFlags = 0;
if (proto.isDynamic() ||
(proto.isObject() && proto.toObject()->isNewGroupUnknown())) {
initialFlags = OBJECT_FLAG_DYNAMIC_MASK;
}
Rooted<TaggedProto> protoRoot(cx, proto);
ObjectGroup* group = ObjectGroupRealm::makeGroup(cx, cx->realm(), clasp,
protoRoot, initialFlags);
if (!group) {
return nullptr;
}
if (!table->add(p, ObjectGroupRealm::NewEntry(group, associated))) {
ReportOutOfMemory(cx);
return nullptr;
}
if (associated) {
if (associated->is<JSFunction>()) {
if (!TypeNewScript::make(cx, group, &associated->as<JSFunction>())) {
return nullptr;
}
} else {
group->setTypeDescr(&associated->as<TypeDescr>());
}
}
/*
* Some builtin objects have slotful native properties baked in at
* creation via the Shape::{insert,get}initialShape mechanism. Since
* these properties are never explicitly defined on new objects, update
* the type information for them here.
*/
const JSAtomState& names = cx->names();
if (clasp == &RegExpObject::class_) {
AddTypePropertyId(cx, group, nullptr, NameToId(names.lastIndex),
TypeSet::Int32Type());
} else if (clasp == &StringObject::class_) {
AddTypePropertyId(cx, group, nullptr, NameToId(names.length),
TypeSet::Int32Type());
} else if (ErrorObject::isErrorClass(clasp)) {
AddTypePropertyId(cx, group, nullptr, NameToId(names.fileName),
TypeSet::StringType());
AddTypePropertyId(cx, group, nullptr, NameToId(names.lineNumber),
TypeSet::Int32Type());
AddTypePropertyId(cx, group, nullptr, NameToId(names.columnNumber),
TypeSet::Int32Type());
}
groups.defaultNewGroupCache.put(group, associated);
return group;
}
/* static */
ObjectGroup* ObjectGroup::lazySingletonGroup(JSContext* cx,
ObjectGroupRealm& realm,
JS::Realm* objectRealm,
const JSClass* clasp,
TaggedProto proto) {
MOZ_ASSERT_IF(proto.isObject(),
cx->compartment() == proto.toObject()->compartment());
ObjectGroupRealm::NewTable*& table = realm.lazyTable;
if (!table) {
table = cx->new_<ObjectGroupRealm::NewTable>(cx->zone());
if (!table) {
return nullptr;
}
}
ObjectGroupRealm::NewTable::AddPtr p = table->lookupForAdd(
ObjectGroupRealm::NewEntry::Lookup(clasp, proto, nullptr));
if (p) {
ObjectGroup* group = p->group;
MOZ_ASSERT(group->lazy());
return group;
}
AutoEnterAnalysis enter(cx);
Rooted<TaggedProto> protoRoot(cx, proto);
ObjectGroup* group = ObjectGroupRealm::makeGroup(
cx, objectRealm, clasp, protoRoot,
OBJECT_FLAG_SINGLETON | OBJECT_FLAG_LAZY_SINGLETON);
if (!group) {
return nullptr;
}
if (!table->add(p, ObjectGroupRealm::NewEntry(group, nullptr))) {
ReportOutOfMemory(cx);
return nullptr;
}
return group;
}
/* static */
void ObjectGroup::setDefaultNewGroupUnknown(JSContext* cx,
ObjectGroupRealm& realm,
const JSClass* clasp,
HandleObject obj) {
// If the object already has a new group, mark that group as unknown.
ObjectGroupRealm::NewTable* table = realm.defaultNewTable;
if (table) {
Rooted<TaggedProto> taggedProto(cx, TaggedProto(obj));
auto lookup =
ObjectGroupRealm::NewEntry::Lookup(clasp, taggedProto, nullptr);
auto p = table->lookup(lookup);
if (p) {
MarkObjectGroupUnknownProperties(cx, p->group);
}
}
}
inline const JSClass* GetClassForProtoKey(JSProtoKey key) {
switch (key) {
case JSProto_Null:
case JSProto_Object:
return &PlainObject::class_;
case JSProto_Array:
return &ArrayObject::class_;
case JSProto_Int8Array:
case JSProto_Uint8Array:
case JSProto_Int16Array:
case JSProto_Uint16Array:
case JSProto_Int32Array:
case JSProto_Uint32Array:
case JSProto_Float32Array:
case JSProto_Float64Array:
case JSProto_Uint8ClampedArray:
case JSProto_BigInt64Array:
case JSProto_BigUint64Array:
return &TypedArrayObject::classes[key - JSProto_Int8Array];
default:
// We only expect to see plain objects, arrays, and typed arrays here.
MOZ_CRASH("Bad proto key");
}
}
/* static */
ObjectGroup* ObjectGroup::defaultNewGroup(JSContext* cx, JSProtoKey key) {
JSObject* proto = nullptr;
if (key != JSProto_Null) {
proto = GlobalObject::getOrCreatePrototype(cx, key);
if (!proto) {
return nullptr;
}
}
return defaultNewGroup(cx, GetClassForProtoKey(key), TaggedProto(proto));
}
/////////////////////////////////////////////////////////////////////
// ObjectGroupRealm ArrayObjectTable
/////////////////////////////////////////////////////////////////////
struct ObjectGroupRealm::ArrayObjectKey : public DefaultHasher<ArrayObjectKey> {
TypeSet::Type type;
ArrayObjectKey() : type(TypeSet::UndefinedType()) {}
explicit ArrayObjectKey(TypeSet::Type type) : type(type) {}
static inline uint32_t hash(const ArrayObjectKey& v) { return v.type.raw(); }
static inline bool match(const ArrayObjectKey& v1, const ArrayObjectKey& v2) {
return v1.type == v2.type;
}
bool operator==(const ArrayObjectKey& other) { return type == other.type; }
bool operator!=(const ArrayObjectKey& other) { return !(*this == other); }
bool traceWeak(JSTracer* trc) {
MOZ_ASSERT(type.isUnknown() || !type.isSingleton());
if (!type.isUnknown() && type.isGroup()) {
ObjectGroup* group = type.groupNoBarrier();
if (!TraceManuallyBarrieredWeakEdge(trc, &group, "ObjectGroup")) {
return false;
}
if (group != type.groupNoBarrier()) {
type = TypeSet::ObjectType(group);
}
}
return true;
}
};
static inline bool NumberTypes(TypeSet::Type a, TypeSet::Type b) {
return (a.isPrimitive(ValueType::Int32) ||
a.isPrimitive(ValueType::Double)) &&
(b.isPrimitive(ValueType::Int32) || b.isPrimitive(ValueType::Double));
}
/*
* As for GetValueType, but requires object types to be non-singletons with
* their default prototype. These are the only values that should appear in
* arrays and objects whose type can be fixed.
*/
static inline TypeSet::Type GetValueTypeForTable(const Value& v) {
TypeSet::Type type = TypeSet::GetValueType(v);
MOZ_ASSERT(!type.isSingleton());
return type;
}
/* static */
ArrayObject* ObjectGroup::newArrayObject(JSContext* cx, const Value* vp,
size_t length, NewObjectKind newKind,
NewArrayKind arrayKind) {
MOZ_ASSERT(newKind != SingletonObject);
// If we are making a copy on write array, don't try to adjust the group as
// getOrFixupCopyOnWriteObject will do this before any objects are copied
// from this one.
if (arrayKind == NewArrayKind::CopyOnWrite) {
ArrayObject* obj = NewDenseCopiedArray(cx, length, vp, nullptr, newKind);
if (!obj || !ObjectElements::MakeElementsCopyOnWrite(cx, obj)) {
return nullptr;
}
return obj;
}
if (!IsTypeInferenceEnabled()) {
return NewDenseCopiedArray(cx, length, vp, nullptr, newKind);
}
// Get a type which captures all the elements in the array to be created.
Rooted<TypeSet::Type> elementType(cx, TypeSet::UnknownType());
if (arrayKind != NewArrayKind::UnknownIndex && length != 0) {
elementType = GetValueTypeForTable(vp[0]);
for (unsigned i = 1; i < length; i++) {
TypeSet::Type ntype = GetValueTypeForTable(vp[i]);
if (ntype != elementType) {
if (NumberTypes(elementType, ntype)) {
elementType = TypeSet::DoubleType();
} else {
elementType = TypeSet::UnknownType();
break;
}
}
}
}
ObjectGroupRealm& realm = ObjectGroupRealm::getForNewObject(cx);
ObjectGroupRealm::ArrayObjectTable*& table = realm.arrayObjectTable;
if (!table) {
table = cx->new_<ObjectGroupRealm::ArrayObjectTable>();
if (!table) {
return nullptr;
}
}
ObjectGroupRealm::ArrayObjectKey key(elementType);
DependentAddPtr<ObjectGroupRealm::ArrayObjectTable> p(cx, *table, key);
RootedObjectGroup group(cx);
if (p) {
group = p->value();
} else {
JSObject* proto = GlobalObject::getOrCreateArrayPrototype(cx, cx->global());
if (!proto) {
return nullptr;
}
Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
group = ObjectGroupRealm::makeGroup(cx, cx->realm(), &ArrayObject::class_,
taggedProto);
if (!group) {
return nullptr;
}
AddTypePropertyId(cx, group, nullptr, JSID_VOID, elementType);
if (!p.add(cx, *table, ObjectGroupRealm::ArrayObjectKey(elementType),
group)) {
return nullptr;
}
}
// The type of the elements being added will already be reflected in type
// information.
ShouldUpdateTypes updateTypes = ShouldUpdateTypes::DontUpdate;
return NewCopiedArrayTryUseGroup(cx, group, vp, length, newKind, updateTypes);
}
// Try to change the group of |source| to match that of |target|.
static bool GiveObjectGroup(JSContext* cx, JSObject* source, JSObject* target) {
MOZ_ASSERT(source->group() != target->group());
if (!target->is<ArrayObject>() || !source->is<ArrayObject>()) {
return true;
}
source->setGroup(target->group());
for (size_t i = 0; i < source->as<ArrayObject>().getDenseInitializedLength();
i++) {
Value v = source->as<ArrayObject>().getDenseElement(i);
AddTypePropertyId(cx, source->group(), source, JSID_VOID, v);
}
return true;
}
static bool SameGroup(JSObject* first, JSObject* second) {
return first->group() == second->group();
}
// When generating a multidimensional array of literals, such as
// [[1,2],[3,4],[5.5,6.5]], try to ensure that each element of the array has
// the same group. This is mainly important when the elements might have
// different native vs. unboxed layouts, or different unboxed layouts, and
// accessing the heterogenous layouts from JIT code will be much slower than
// if they were homogenous.
//
// To do this, with each new array element we compare it with one of the
// previous ones, and try to mutate the group of the new element to fit that
// of the old element. If this isn't possible, the groups for all old elements
// are mutated to fit that of the new element.
bool js::CombineArrayElementTypes(JSContext* cx, JSObject* newObj,
const Value* compare, size_t ncompare) {
if (!ncompare || !compare[0].isObject()) {
return true;
}
JSObject* oldObj = &compare[0].toObject();
if (SameGroup(oldObj, newObj)) {
return true;
}
if (!GiveObjectGroup(cx, newObj, oldObj)) {
return false;
}
if (SameGroup(oldObj, newObj)) {
return true;
}
if (!GiveObjectGroup(cx, oldObj, newObj)) {
return false;
}
if (SameGroup(oldObj, newObj)) {
for (size_t i = 1; i < ncompare; i++) {
if (compare[i].isObject() && !SameGroup(&compare[i].toObject(), newObj)) {
if (!GiveObjectGroup(cx, &compare[i].toObject(), newObj)) {
return false;
}
}
}
}
return true;
}
// Similarly to CombineArrayElementTypes, if we are generating an array of
// plain objects with a consistent property layout, such as
// [{p:[1,2]},{p:[3,4]},{p:[5.5,6.5]}], where those plain objects in
// turn have arrays as their own properties, try to ensure that a consistent
// group is given to each array held by the same property of the plain objects.
bool js::CombinePlainObjectPropertyTypes(JSContext* cx, JSObject* newObj,
const Value* compare,
size_t ncompare) {
if (!ncompare || !compare[0].isObject()) {
return true;
}
JSObject* oldObj = &compare[0].toObject();
if (!SameGroup(oldObj, newObj)) {
return true;
}
if (newObj->is<PlainObject>()) {
if (newObj->as<PlainObject>().lastProperty() !=
oldObj->as<PlainObject>().lastProperty()) {
return true;
}
for (size_t slot = 0; slot < newObj->as<PlainObject>().slotSpan(); slot++) {
Value newValue = newObj->as<PlainObject>().getSlot(slot);
Value oldValue = oldObj->as<PlainObject>().getSlot(slot);
if (!newValue.isObject() || !oldValue.isObject()) {
continue;
}
JSObject* newInnerObj = &newValue.toObject();
JSObject* oldInnerObj = &oldValue.toObject();
if (SameGroup(oldInnerObj, newInnerObj)) {
continue;
}
if (!GiveObjectGroup(cx, newInnerObj, oldInnerObj)) {
return false;
}
if (SameGroup(oldInnerObj, newInnerObj)) {
continue;
}
if (!GiveObjectGroup(cx, oldInnerObj, newInnerObj)) {
return false;
}
if (SameGroup(oldInnerObj, newInnerObj)) {
for (size_t i = 1; i < ncompare; i++) {
if (compare[i].isObject() &&