forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathheap-refs.cc
More file actions
2439 lines (2075 loc) · 87 KB
/
heap-refs.cc
File metadata and controls
2439 lines (2075 loc) · 87 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 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/heap-refs.h"
#include "src/compiler/js-heap-broker.h"
#include "src/objects/elements-kind.h"
#ifdef ENABLE_SLOW_DCHECKS
#include <algorithm>
#endif
#include "src/api/api-inl.h"
#include "src/base/optional.h"
#include "src/compiler/compilation-dependencies.h"
#include "src/compiler/js-heap-broker-inl.h"
#include "src/execution/protectors-inl.h"
#include "src/objects/allocation-site-inl.h"
#include "src/objects/descriptor-array.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/literal-objects-inl.h"
#include "src/objects/property-cell.h"
#include "src/objects/template-objects-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
#define TRACE(broker, x) TRACE_BROKER(broker, x)
#define TRACE_MISSING(broker, x) TRACE_BROKER_MISSING(broker, x)
// There are several kinds of ObjectData values.
//
// kSmi: The underlying V8 object is a Smi and the data is an instance of the
// base class (ObjectData), i.e. it's basically just the handle. Because the
// object is a Smi, it's safe to access the handle in order to extract the
// number value, and AsSmi() does exactly that.
//
// kBackgroundSerializedHeapObject: The underlying V8 object is a HeapObject
// and the data is an instance of the corresponding (most-specific) subclass,
// e.g. JSFunctionData, which provides serialized information about the
// object. Allows serialization from the background thread.
//
// kUnserializedHeapObject: The underlying V8 object is a HeapObject and the
// data is an instance of the base class (ObjectData), i.e. it basically
// carries no information other than the handle.
//
// kNeverSerializedHeapObject: The underlying V8 object is a (potentially
// mutable) HeapObject and the data is an instance of ObjectData. Its handle
// must be persistent so that the GC can update it at a safepoint. Via this
// handle, the object can be accessed concurrently to the main thread.
//
// kUnserializedReadOnlyHeapObject: The underlying V8 object is a read-only
// HeapObject and the data is an instance of ObjectData. For
// ReadOnlyHeapObjects, it is OK to access heap even from off-thread, so
// these objects need not be serialized.
enum ObjectDataKind {
kSmi,
kBackgroundSerializedHeapObject,
kUnserializedHeapObject,
kNeverSerializedHeapObject,
kUnserializedReadOnlyHeapObject
};
namespace {
bool Is64() { return kSystemPointerSize == 8; }
} // namespace
class ObjectData : public ZoneObject {
public:
ObjectData(JSHeapBroker* broker, ObjectData** storage, Handle<Object> object,
ObjectDataKind kind)
: object_(object),
kind_(kind)
#ifdef DEBUG
,
broker_(broker)
#endif // DEBUG
{
// This assignment ensures we don't end up inserting the same object
// in an endless recursion.
*storage = this;
TRACE(broker, "Creating data " << this << " for handle " << object.address()
<< " (" << Brief(*object) << ")");
// It is safe to access read only heap objects and builtins from a
// background thread. When we read fields of these objects, we may create
// ObjectData on the background thread.
// This is safe too since we don't create handles but just get handles from
// read only root table or builtins table.
// All other objects need to be canonicalized in a persistent handle scope.
// See CanonicalPersistentHandle().
Isolate* isolate = broker->isolate();
USE(isolate);
DCHECK_IMPLIES(broker->mode() == JSHeapBroker::kDisabled ||
broker->mode() == JSHeapBroker::kSerializing,
PersistentHandlesScope::IsActive(isolate) &&
broker->IsCanonicalHandle(object));
DCHECK_IMPLIES(broker->mode() == JSHeapBroker::kSerialized,
kind == kUnserializedReadOnlyHeapObject || kind == kSmi ||
kind == kNeverSerializedHeapObject ||
kind == kBackgroundSerializedHeapObject);
DCHECK_IMPLIES(kind == kUnserializedReadOnlyHeapObject,
i::IsHeapObject(*object) &&
ReadOnlyHeap::Contains(HeapObject::cast(*object)));
}
#define DECLARE_IS(Name) bool Is##Name() const;
HEAP_BROKER_OBJECT_LIST(DECLARE_IS)
#undef DECLARE_IS
#define DECLARE_AS(Name) Name##Data* As##Name();
HEAP_BROKER_BACKGROUND_SERIALIZED_OBJECT_LIST(DECLARE_AS)
#undef DECLARE_AS
Handle<Object> object() const { return object_; }
ObjectDataKind kind() const { return kind_; }
bool is_smi() const { return kind_ == kSmi; }
bool should_access_heap() const {
return kind_ == kUnserializedHeapObject ||
kind_ == kNeverSerializedHeapObject ||
kind_ == kUnserializedReadOnlyHeapObject;
}
bool IsNull() const { return i::IsNull(*object_); }
#ifdef DEBUG
JSHeapBroker* broker() const { return broker_; }
#endif // DEBUG
private:
Handle<Object> const object_;
ObjectDataKind const kind_;
#ifdef DEBUG
JSHeapBroker* const broker_; // For DCHECKs.
#endif // DEBUG
};
class HeapObjectData : public ObjectData {
public:
HeapObjectData(JSHeapBroker* broker, ObjectData** storage,
Handle<HeapObject> object, ObjectDataKind kind);
base::Optional<bool> TryGetBooleanValue(JSHeapBroker* broker) const;
ObjectData* map() const { return map_; }
InstanceType GetMapInstanceType() const;
private:
base::Optional<bool> TryGetBooleanValueImpl(JSHeapBroker* broker) const;
ObjectData* const map_;
};
class PropertyCellData : public HeapObjectData {
public:
PropertyCellData(JSHeapBroker* broker, ObjectData** storage,
Handle<PropertyCell> object, ObjectDataKind kind);
bool Cache(JSHeapBroker* broker);
PropertyDetails property_details() const {
CHECK(serialized());
return property_details_;
}
ObjectData* value() const {
DCHECK(serialized());
return value_;
}
private:
PropertyDetails property_details_ = PropertyDetails::Empty();
ObjectData* value_ = nullptr;
bool serialized() const { return value_ != nullptr; }
};
namespace {
ZoneVector<Address> GetCFunctions(Tagged<FixedArray> function_overloads,
Zone* zone) {
const int len = function_overloads->length() /
FunctionTemplateInfo::kFunctionOverloadEntrySize;
ZoneVector<Address> c_functions = ZoneVector<Address>(len, zone);
for (int i = 0; i < len; i++) {
c_functions[i] = v8::ToCData<Address>(function_overloads->get(
FunctionTemplateInfo::kFunctionOverloadEntrySize * i));
}
return c_functions;
}
ZoneVector<const CFunctionInfo*> GetCSignatures(
Tagged<FixedArray> function_overloads, Zone* zone) {
const int len = function_overloads->length() /
FunctionTemplateInfo::kFunctionOverloadEntrySize;
ZoneVector<const CFunctionInfo*> c_signatures =
ZoneVector<const CFunctionInfo*>(len, zone);
for (int i = 0; i < len; i++) {
c_signatures[i] = v8::ToCData<const CFunctionInfo*>(function_overloads->get(
FunctionTemplateInfo::kFunctionOverloadEntrySize * i + 1));
}
return c_signatures;
}
} // namespace
PropertyCellData::PropertyCellData(JSHeapBroker* broker, ObjectData** storage,
Handle<PropertyCell> object,
ObjectDataKind kind)
: HeapObjectData(broker, storage, object, kind) {}
bool PropertyCellData::Cache(JSHeapBroker* broker) {
if (serialized()) return true;
TraceScope tracer(broker, this, "PropertyCellData::Serialize");
auto cell = Handle<PropertyCell>::cast(object());
// While this code runs on a background thread, the property cell might
// undergo state transitions via calls to PropertyCell::Transition. These
// transitions follow a certain protocol on which we rely here to ensure that
// we only report success when we can guarantee consistent data. A key
// property is that after transitioning from cell type A to B (A != B), there
// will never be a transition back to A, unless A is kConstant and the new
// value is the hole (i.e. the property cell was invalidated, which is a final
// state).
PropertyDetails property_details = cell->property_details(kAcquireLoad);
Handle<Object> value =
broker->CanonicalPersistentHandle(cell->value(kAcquireLoad));
if (broker->ObjectMayBeUninitialized(value)) {
DCHECK(!broker->IsMainThread());
return false;
}
{
PropertyDetails property_details_again =
cell->property_details(kAcquireLoad);
if (property_details != property_details_again) {
DCHECK(!broker->IsMainThread());
return false;
}
}
if (property_details.cell_type() == PropertyCellType::kInTransition) {
DCHECK(!broker->IsMainThread());
return false;
}
ObjectData* value_data = broker->TryGetOrCreateData(value);
if (value_data == nullptr) {
DCHECK(!broker->IsMainThread());
return false;
}
PropertyCell::CheckDataIsCompatible(property_details, *value);
DCHECK(!serialized());
property_details_ = property_details;
value_ = value_data;
DCHECK(serialized());
return true;
}
class JSReceiverData : public HeapObjectData {
public:
JSReceiverData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSReceiver> object, ObjectDataKind kind)
: HeapObjectData(broker, storage, object, kind) {}
};
class JSObjectData : public JSReceiverData {
public:
JSObjectData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSObject> object, ObjectDataKind kind)
: JSReceiverData(broker, storage, object, kind) {}
};
namespace {
// Separate function for racy HeapNumber value read, so that we can explicitly
// suppress it in TSAN (see tools/sanitizers/tsan_suppressions.txt).
uint64_t RacyReadHeapNumberBits(Tagged<HeapNumber> value) {
return value->value_as_bits();
}
base::Optional<Tagged<Object>> GetOwnFastConstantDataPropertyFromHeap(
JSHeapBroker* broker, JSObjectRef holder, Representation representation,
FieldIndex field_index) {
base::Optional<Tagged<Object>> constant;
{
DisallowGarbageCollection no_gc;
PtrComprCageBase cage_base = broker->cage_base();
// This check to ensure the live map is the same as the cached map to
// to protect us against reads outside the bounds of the heap. This could
// happen if the Ref was created in a prior GC epoch, and the object
// shrunk in size. It might end up at the edge of a heap boundary. If
// we see that the map is the same in this GC epoch, we are safe.
Tagged<Map> map = holder.object()->map(cage_base, kAcquireLoad);
if (*holder.map(broker).object() != map) {
TRACE_BROKER_MISSING(broker, "Map changed for " << holder);
return {};
}
if (field_index.is_inobject()) {
constant =
holder.object()->RawInobjectPropertyAt(cage_base, map, field_index);
if (!constant.has_value()) {
TRACE_BROKER_MISSING(
broker, "Constant field in " << holder << " is unsafe to read");
return {};
}
} else {
Tagged<Object> raw_properties_or_hash =
holder.object()->raw_properties_or_hash(cage_base, kRelaxedLoad);
// Ensure that the object is safe to inspect.
if (broker->ObjectMayBeUninitialized(raw_properties_or_hash)) {
return {};
}
if (!IsPropertyArray(raw_properties_or_hash, cage_base)) {
TRACE_BROKER_MISSING(
broker,
"Expected PropertyArray for backing store in " << holder << ".");
return {};
}
Tagged<PropertyArray> properties =
PropertyArray::cast(raw_properties_or_hash);
const int array_index = field_index.outobject_array_index();
if (array_index < properties->length(kAcquireLoad)) {
constant = properties->get(array_index);
} else {
TRACE_BROKER_MISSING(
broker, "Backing store for " << holder << " not long enough.");
return {};
}
}
// We might read the uninitialized sentinel, if we race with the main
// thread adding a new property to the object (having set the map, but not
// yet initialised the property value). Since this is a tight race, it won't
// happen very often, so we can just abort the load.
// TODO(leszeks): We could instead sleep/yield and spin the load, since the
// timing on this is tight enough that we wouldn't delay the compiler thread
// by much.
if (IsUninitialized(constant.value())) {
TRACE_BROKER_MISSING(broker, "Read uninitialized property.");
return {};
}
// {constant} needs to pass the gc predicate before we can introspect on it.
if (broker->ObjectMayBeUninitialized(constant.value())) return {};
// Ensure that {constant} matches the {representation} we expect for the
// field.
if (!Object::FitsRepresentation(*constant, representation, false)) {
const char* repString = IsSmi(*constant) ? "Smi"
: IsHeapNumber(*constant) ? "HeapNumber"
: "HeapObject";
TRACE_BROKER_MISSING(broker, "Mismatched representation for "
<< holder << ". Expected "
<< representation << ", but object is a "
<< repString);
return {};
}
}
return constant;
}
// Tries to get the property at {dict_index}. If we are within bounds of the
// object, we are guaranteed to see valid heap words even if the data is wrong.
OptionalObjectRef GetOwnDictionaryPropertyFromHeap(JSHeapBroker* broker,
Handle<JSObject> receiver,
InternalIndex dict_index) {
Handle<Object> constant;
{
DisallowGarbageCollection no_gc;
// DictionaryPropertyAt will check that we are within the bounds of the
// object.
base::Optional<Tagged<Object>> maybe_constant =
JSObject::DictionaryPropertyAt(receiver, dict_index,
broker->isolate()->heap());
DCHECK_IMPLIES(broker->IsMainThread(), maybe_constant);
if (!maybe_constant) return {};
constant = broker->CanonicalPersistentHandle(maybe_constant.value());
}
return TryMakeRef(broker, constant);
}
} // namespace
class JSTypedArrayData : public JSObjectData {
public:
JSTypedArrayData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSTypedArray> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSDataViewData : public JSObjectData {
public:
JSDataViewData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSDataView> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSPrimitiveWrapperData : public JSObjectData {
public:
JSPrimitiveWrapperData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSPrimitiveWrapper> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSBoundFunctionData : public JSObjectData {
public:
JSBoundFunctionData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSBoundFunction> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSFunctionData : public JSObjectData {
public:
JSFunctionData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSFunction> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {
Cache(broker);
}
bool IsConsistentWithHeapState(JSHeapBroker* broker) const;
bool has_initial_map() const {
DCHECK(serialized_);
return has_initial_map_;
}
bool has_instance_prototype() const {
DCHECK(serialized_);
return has_instance_prototype_;
}
bool PrototypeRequiresRuntimeLookup() const {
DCHECK(serialized_);
return PrototypeRequiresRuntimeLookup_;
}
ObjectData* context() const {
DCHECK(serialized_);
return context_;
}
ObjectData* initial_map() const {
DCHECK(serialized_);
return initial_map_;
}
ObjectData* instance_prototype() const {
DCHECK(serialized_);
return instance_prototype_;
}
ObjectData* shared() const {
DCHECK(serialized_);
return shared_;
}
ObjectData* raw_feedback_cell() const {
DCHECK(serialized_);
return feedback_cell_;
}
int initial_map_instance_size_with_min_slack() const {
DCHECK(serialized_);
return initial_map_instance_size_with_min_slack_;
}
// Track serialized fields that are actually used, in order to relax
// ConsistentJSFunctionView dependency validation as much as possible.
enum UsedField {
kHasFeedbackVector = 1 << 0,
kPrototypeOrInitialMap = 1 << 1,
kHasInitialMap = 1 << 2,
kHasInstancePrototype = 1 << 3,
kPrototypeRequiresRuntimeLookup = 1 << 4,
kInitialMap = 1 << 5,
kInstancePrototype = 1 << 6,
kFeedbackVector = 1 << 7,
kFeedbackCell = 1 << 8,
kInitialMapInstanceSizeWithMinSlack = 1 << 9,
};
bool has_any_used_field() const { return used_fields_ != 0; }
bool has_used_field(UsedField used_field) const {
return (used_fields_ & used_field) != 0;
}
void set_used_field(UsedField used_field) { used_fields_ |= used_field; }
private:
void Cache(JSHeapBroker* broker);
#ifdef DEBUG
bool serialized_ = false;
#endif // DEBUG
using UsedFields = base::Flags<UsedField>;
UsedFields used_fields_;
ObjectData* prototype_or_initial_map_ = nullptr;
bool has_initial_map_ = false;
bool has_instance_prototype_ = false;
bool PrototypeRequiresRuntimeLookup_ = false;
ObjectData* context_ = nullptr;
ObjectData* initial_map_ =
nullptr; // Derives from prototype_or_initial_map_.
ObjectData* instance_prototype_ =
nullptr; // Derives from prototype_or_initial_map_.
ObjectData* shared_ = nullptr;
ObjectData* feedback_cell_ = nullptr;
int initial_map_instance_size_with_min_slack_; // Derives from
// prototype_or_initial_map_.
};
class BigIntData : public HeapObjectData {
public:
BigIntData(JSHeapBroker* broker, ObjectData** storage, Handle<BigInt> object,
ObjectDataKind kind)
: HeapObjectData(broker, storage, object, kind),
as_uint64_(object->AsUint64(nullptr)),
as_int64_(object->AsInt64(&lossless_)) {}
uint64_t AsUint64() const { return as_uint64_; }
int64_t AsInt64(bool* lossless) const {
*lossless = lossless_;
return as_int64_;
}
private:
const uint64_t as_uint64_;
const int64_t as_int64_;
bool lossless_;
};
struct PropertyDescriptor {
FieldIndex field_index;
ObjectData* field_owner = nullptr;
};
class MapData : public HeapObjectData {
public:
MapData(JSHeapBroker* broker, ObjectData** storage, Handle<Map> object,
ObjectDataKind kind);
InstanceType instance_type() const { return instance_type_; }
int instance_size() const { return instance_size_; }
uint32_t bit_field3() const { return bit_field3_; }
int in_object_properties() const {
CHECK(InstanceTypeChecker::IsJSObject(instance_type()));
return in_object_properties_;
}
int UnusedPropertyFields() const { return unused_property_fields_; }
bool is_abandoned_prototype_map() const {
return is_abandoned_prototype_map_;
}
private:
// The following fields should be const in principle, but construction
// requires locking the MapUpdater lock. For this reason, it's easier to
// initialize these inside the constructor body, not in the initializer list.
InstanceType instance_type_;
int instance_size_;
uint32_t bit_field3_;
int unused_property_fields_;
bool is_abandoned_prototype_map_;
int in_object_properties_;
};
namespace {
int InstanceSizeWithMinSlack(JSHeapBroker* broker, MapRef map) {
// This operation is split into two phases (1. map collection, 2. map
// processing). This is to avoid having to take two locks
// (full_transition_array_access and map_updater_access) at once and thus
// having to deal with related deadlock issues.
ZoneVector<Handle<Map>> maps(broker->zone());
maps.push_back(map.object());
{
DisallowGarbageCollection no_gc;
// Has to be an initial map.
DCHECK(IsUndefined(map.object()->GetBackPointer(), broker->isolate()));
static constexpr bool kConcurrentAccess = true;
TransitionsAccessor(broker->isolate(), *map.object(), kConcurrentAccess)
.TraverseTransitionTree([&](Tagged<Map> m) {
maps.push_back(broker->CanonicalPersistentHandle(m));
});
}
// The lock is needed for UnusedPropertyFields and InstanceSizeFromSlack.
JSHeapBroker::MapUpdaterGuardIfNeeded mumd_scope(broker);
int slack = std::numeric_limits<int>::max();
for (Handle<Map> m : maps) {
slack = std::min(slack, m->UnusedPropertyFields());
}
return map.object()->InstanceSizeFromSlack(slack);
}
} // namespace
// IMPORTANT: Keep this sync'd with JSFunctionData::IsConsistentWithHeapState.
void JSFunctionData::Cache(JSHeapBroker* broker) {
DCHECK(!serialized_);
TraceScope tracer(broker, this, "JSFunctionData::Cache");
Handle<JSFunction> function = Handle<JSFunction>::cast(object());
// This function may run on the background thread and thus must be individual
// fields in a thread-safe manner. Consistency between fields is *not*
// guaranteed here, instead we verify it in `IsConsistentWithHeapState`,
// called during job finalization. Relaxed loads are thus okay: we're
// guaranteed to see an initialized JSFunction object, and after
// initialization fields remain in a valid state.
ContextRef context =
MakeRefAssumeMemoryFence(broker, function->context(kRelaxedLoad));
context_ = context.data();
SharedFunctionInfoRef shared =
MakeRefAssumeMemoryFence(broker, function->shared(kRelaxedLoad));
shared_ = shared.data();
if (function->has_prototype_slot()) {
prototype_or_initial_map_ = broker->GetOrCreateData(
function->prototype_or_initial_map(kAcquireLoad), kAssumeMemoryFence);
has_initial_map_ = prototype_or_initial_map_->IsMap();
if (has_initial_map_) {
// MapData is not used for initial_map_ because some
// AlwaysSharedSpaceJSObject subclass constructors (e.g. SharedArray) have
// initial maps in RO space, which can be accessed directly.
initial_map_ = prototype_or_initial_map_;
MapRef initial_map_ref = TryMakeRef<Map>(broker, initial_map_).value();
if (initial_map_ref.IsInobjectSlackTrackingInProgress()) {
initial_map_instance_size_with_min_slack_ =
InstanceSizeWithMinSlack(broker, initial_map_ref);
} else {
initial_map_instance_size_with_min_slack_ =
initial_map_ref.instance_size();
}
CHECK_GT(initial_map_instance_size_with_min_slack_, 0);
}
if (has_initial_map_) {
has_instance_prototype_ = true;
instance_prototype_ =
MakeRefAssumeMemoryFence(
broker, Handle<Map>::cast(initial_map_->object())->prototype())
.data();
} else if (prototype_or_initial_map_->IsHeapObject() &&
!IsTheHole(*Handle<HeapObject>::cast(
prototype_or_initial_map_->object()))) {
has_instance_prototype_ = true;
instance_prototype_ = prototype_or_initial_map_;
}
}
PrototypeRequiresRuntimeLookup_ = function->PrototypeRequiresRuntimeLookup();
FeedbackCellRef feedback_cell = MakeRefAssumeMemoryFence(
broker, function->raw_feedback_cell(kAcquireLoad));
feedback_cell_ = feedback_cell.data();
#ifdef DEBUG
serialized_ = true;
#endif // DEBUG
}
// IMPORTANT: Keep this sync'd with JSFunctionData::Cache.
bool JSFunctionData::IsConsistentWithHeapState(JSHeapBroker* broker) const {
DCHECK(serialized_);
Handle<JSFunction> f = Handle<JSFunction>::cast(object());
if (*context_->object() != f->context()) {
TRACE_BROKER_MISSING(broker, "JSFunction::context");
return false;
}
CHECK_EQ(*shared_->object(), f->shared());
if (f->has_prototype_slot()) {
if (has_used_field(kPrototypeOrInitialMap) &&
*prototype_or_initial_map_->object() !=
f->prototype_or_initial_map(kAcquireLoad)) {
TRACE_BROKER_MISSING(broker, "JSFunction::prototype_or_initial_map");
return false;
}
if (has_used_field(kHasInitialMap) &&
has_initial_map_ != f->has_initial_map()) {
TRACE_BROKER_MISSING(broker, "JSFunction::has_initial_map");
return false;
}
if (has_used_field(kHasInstancePrototype) &&
has_instance_prototype_ != f->has_instance_prototype()) {
TRACE_BROKER_MISSING(broker, "JSFunction::has_instance_prototype");
return false;
}
} else {
DCHECK(!has_initial_map_);
DCHECK(!has_instance_prototype_);
}
if (has_initial_map()) {
if (has_used_field(kInitialMap) &&
*initial_map_->object() != f->initial_map()) {
TRACE_BROKER_MISSING(broker, "JSFunction::initial_map");
return false;
}
if (has_used_field(kInitialMapInstanceSizeWithMinSlack) &&
initial_map_instance_size_with_min_slack_ !=
f->ComputeInstanceSizeWithMinSlack(f->GetIsolate())) {
TRACE_BROKER_MISSING(broker,
"JSFunction::ComputeInstanceSizeWithMinSlack");
return false;
}
} else {
DCHECK_NULL(initial_map_);
}
if (has_instance_prototype_) {
if (has_used_field(kInstancePrototype) &&
*instance_prototype_->object() != f->instance_prototype()) {
TRACE_BROKER_MISSING(broker, "JSFunction::instance_prototype");
return false;
}
} else {
DCHECK_NULL(instance_prototype_);
}
if (has_used_field(kPrototypeRequiresRuntimeLookup) &&
PrototypeRequiresRuntimeLookup_ != f->PrototypeRequiresRuntimeLookup()) {
TRACE_BROKER_MISSING(broker, "JSFunction::PrototypeRequiresRuntimeLookup");
return false;
}
if (has_used_field(kFeedbackCell) &&
*feedback_cell_->object() != f->raw_feedback_cell()) {
TRACE_BROKER_MISSING(broker, "JSFunction::raw_feedback_cell");
return false;
}
return true;
}
bool JSFunctionRef::IsConsistentWithHeapState(JSHeapBroker* broker) const {
DCHECK(broker->IsMainThread());
return data()->AsJSFunction()->IsConsistentWithHeapState(broker);
}
HeapObjectData::HeapObjectData(JSHeapBroker* broker, ObjectData** storage,
Handle<HeapObject> object, ObjectDataKind kind)
: ObjectData(broker, storage, object, kind),
map_(broker->GetOrCreateData(
object->map(broker->cage_base(), kAcquireLoad), kAssumeMemoryFence)) {
CHECK_IMPLIES(broker->mode() == JSHeapBroker::kSerialized,
kind == kBackgroundSerializedHeapObject);
}
base::Optional<bool> HeapObjectData::TryGetBooleanValue(
JSHeapBroker* broker) const {
// Keep in sync with Object::BooleanValue.
auto result = TryGetBooleanValueImpl(broker);
DCHECK_IMPLIES(
broker->IsMainThread() && result.has_value(),
result.value() == Object::BooleanValue(*object(), broker->isolate()));
return result;
}
base::Optional<bool> HeapObjectData::TryGetBooleanValueImpl(
JSHeapBroker* broker) const {
DisallowGarbageCollection no_gc;
Tagged<Object> o = *object();
Isolate* isolate = broker->isolate();
const InstanceType t = GetMapInstanceType();
if (IsTrue(o, isolate)) {
return true;
} else if (IsFalse(o, isolate)) {
return false;
} else if (IsNullOrUndefined(o, isolate)) {
return false;
} else if (MapRef{map()}.is_undetectable()) {
return false; // Undetectable object is false.
} else if (InstanceTypeChecker::IsString(t)) {
// TODO(jgruber): Implement in possible cases.
return {};
} else if (InstanceTypeChecker::IsHeapNumber(t)) {
return {};
} else if (InstanceTypeChecker::IsBigInt(t)) {
return {};
}
return true;
}
InstanceType HeapObjectData::GetMapInstanceType() const {
ObjectData* map_data = map();
if (map_data->should_access_heap()) {
return Handle<Map>::cast(map_data->object())->instance_type();
}
if (this == map_data) {
// Handle infinite recursion in case this object is a contextful meta map.
return MAP_TYPE;
}
return map_data->AsMap()->instance_type();
}
namespace {
bool IsReadOnlyLengthDescriptor(Isolate* isolate, Handle<Map> jsarray_map) {
DCHECK(!jsarray_map->is_dictionary_map());
Tagged<DescriptorArray> descriptors =
jsarray_map->instance_descriptors(isolate, kRelaxedLoad);
static_assert(
JSArray::kLengthOffset == JSObject::kHeaderSize,
"The length should be the first property on the descriptor array");
InternalIndex offset(0);
return descriptors->GetDetails(offset).IsReadOnly();
}
// Important: this predicate does not check Protectors::IsNoElementsIntact. The
// compiler checks protectors through the compilation dependency mechanism; it
// doesn't make sense to do that here as part of every MapData construction.
// Callers *must* take care to take the correct dependency themselves.
bool SupportsFastArrayIteration(JSHeapBroker* broker, Handle<Map> map) {
return map->instance_type() == JS_ARRAY_TYPE &&
IsFastElementsKind(map->elements_kind()) &&
IsJSArray(map->prototype()) &&
broker->IsArrayOrObjectPrototype(broker->CanonicalPersistentHandle(
JSArray::cast(map->prototype())));
}
bool SupportsFastArrayResize(JSHeapBroker* broker, Handle<Map> map) {
return SupportsFastArrayIteration(broker, map) && map->is_extensible() &&
!map->is_dictionary_map() &&
!IsReadOnlyLengthDescriptor(broker->isolate(), map);
}
} // namespace
MapData::MapData(JSHeapBroker* broker, ObjectData** storage, Handle<Map> object,
ObjectDataKind kind)
: HeapObjectData(broker, storage, object, kind) {
// This lock ensure that MapData can always be background-serialized, i.e.
// while the lock is held the Map object may not be modified (except in
// benign ways).
// TODO(jgruber): Consider removing this lock by being smrt.
JSHeapBroker::MapUpdaterGuardIfNeeded mumd_scope(broker);
// When background serializing the map, we can perform a lite serialization
// since the MapRef will read some of the Map's fields can be read directly.
// Even though MapRefs can read {instance_type} directly, other classes depend
// on {instance_type} being serialized.
instance_type_ = object->instance_type();
instance_size_ = object->instance_size();
// Both bit_field3 (and below bit_field) are special fields: Even though most
// of the individual bits inside of the bitfield could be read / written
// non-atomically, the bitfield itself has to use atomic relaxed accessors
// since some fields since can be modified in live objects.
// TODO(solanes, v8:7790): Assess if adding the exclusive lock in more places
// (e.g for set_has_non_instance_prototype) makes sense. Pros: these fields
// can use the non-atomic accessors. Cons: We would be acquiring an exclusive
// lock in more places.
bit_field3_ = object->relaxed_bit_field3();
unused_property_fields_ = object->UnusedPropertyFields();
is_abandoned_prototype_map_ = object->is_abandoned_prototype_map();
in_object_properties_ =
IsJSObjectMap(*object) ? object->GetInObjectProperties() : 0;
}
class FixedArrayBaseData : public HeapObjectData {
public:
FixedArrayBaseData(JSHeapBroker* broker, ObjectData** storage,
Handle<FixedArrayBase> object, ObjectDataKind kind)
: HeapObjectData(broker, storage, object, kind),
length_(object->length(kAcquireLoad)) {}
int length() const { return length_; }
private:
int const length_;
};
class FixedArrayData : public FixedArrayBaseData {
public:
FixedArrayData(JSHeapBroker* broker, ObjectData** storage,
Handle<FixedArray> object, ObjectDataKind kind)
: FixedArrayBaseData(broker, storage, object, kind) {}
};
// Only used in JSNativeContextSpecialization.
class ScriptContextTableData : public FixedArrayBaseData {
public:
ScriptContextTableData(JSHeapBroker* broker, ObjectData** storage,
Handle<ScriptContextTable> object, ObjectDataKind kind)
: FixedArrayBaseData(broker, storage, object, kind) {}
};
class JSArrayData : public JSObjectData {
public:
JSArrayData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSArray> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSGlobalObjectData : public JSObjectData {
public:
JSGlobalObjectData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSGlobalObject> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
class JSGlobalProxyData : public JSObjectData {
public:
JSGlobalProxyData(JSHeapBroker* broker, ObjectData** storage,
Handle<JSGlobalProxy> object, ObjectDataKind kind)
: JSObjectData(broker, storage, object, kind) {}
};
#define DEFINE_IS(Name) \
bool ObjectData::Is##Name() const { \
if (should_access_heap()) { \
return i::Is##Name(*object()); \
} \
if (is_smi()) return false; \
InstanceType instance_type = \
static_cast<const HeapObjectData*>(this)->GetMapInstanceType(); \
return InstanceTypeChecker::Is##Name(instance_type); \
}
HEAP_BROKER_OBJECT_LIST(DEFINE_IS)
#undef DEFINE_IS
#define DEFINE_AS(Name) \
Name##Data* ObjectData::As##Name() { \
CHECK(Is##Name()); \
CHECK(kind_ == kBackgroundSerializedHeapObject); \
return static_cast<Name##Data*>(this); \
}
HEAP_BROKER_BACKGROUND_SERIALIZED_OBJECT_LIST(DEFINE_AS)
#undef DEFINE_AS
bool ObjectRef::equals(ObjectRef other) const { return data_ == other.data_; }
ContextRef ContextRef::previous(JSHeapBroker* broker, size_t* depth) const {
DCHECK_NOT_NULL(depth);
if (*depth == 0) return *this;
Tagged<Context> current = *object();
while (*depth != 0 && i::IsContext(current->unchecked_previous())) {
current = Context::cast(current->unchecked_previous());
(*depth)--;
}
// The `previous` field is immutable after initialization and the
// context itself is read through an atomic load.
return MakeRefAssumeMemoryFence(broker, current);
}
OptionalObjectRef ContextRef::get(JSHeapBroker* broker, int index) const {
CHECK_LE(0, index);
// Length is immutable after initialization.
if (index >= object()->length(kRelaxedLoad)) return {};
return TryMakeRef(broker, object()->get(index));
}
OptionalObjectRef ContextRef::TryGetSideData(JSHeapBroker* broker,
int index) const {
if (!object()->IsScriptContext()) {
return {};
}
// No side data for slots which are not variables in the context.
if (index < Context::MIN_CONTEXT_EXTENDED_SLOTS) {
return {};
}
OptionalObjectRef maybe_side_data =
get(broker, Context::CONST_TRACKING_LET_SIDE_DATA_INDEX);
if (!maybe_side_data.has_value()) return {};
// The FixedArray itself will stay constant, but its contents may change while
// we compile in the background.
FixedArrayRef side_data_fixed_array = maybe_side_data.value().AsFixedArray();
return side_data_fixed_array.TryGet(
broker, index - Context::MIN_CONTEXT_EXTENDED_SLOTS);
}
void JSHeapBroker::InitializeAndStartSerializing(
Handle<NativeContext> target_native_context) {
TraceScope tracer(this, "JSHeapBroker::InitializeAndStartSerializing");