forked from microsoft/hermes-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GCBase.cpp
1870 lines (1692 loc) · 61.2 KB
/
GCBase.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
/*
* 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.
*/
#define DEBUG_TYPE "gc"
#include "hermes/VM/GC.h"
#include "hermes/Platform/Logging.h"
#include "hermes/Support/ErrorHandling.h"
#include "hermes/Support/OSCompat.h"
#include "hermes/VM/CellKind.h"
#include "hermes/VM/JSWeakMapImpl.h"
#include "hermes/VM/RootAndSlotAcceptorDefault.h"
#include "hermes/VM/Runtime.h"
#include "hermes/VM/SmallHermesValue-inline.h"
#include "hermes/VM/VTable.h"
#include "llvh/Support/Debug.h"
#include "llvh/Support/FileSystem.h"
#include "llvh/Support/Format.h"
#include "llvh/Support/raw_os_ostream.h"
#include "llvh/Support/raw_ostream.h"
#include <inttypes.h>
#include <clocale>
#include <stdexcept>
#include <system_error>
using llvh::dbgs;
using llvh::format;
namespace hermes {
namespace vm {
const char GCBase::kNaturalCauseForAnalytics[] = "natural";
const char GCBase::kHandleSanCauseForAnalytics[] = "handle-san";
GCBase::GCBase(
GCCallbacks *gcCallbacks,
PointerBase *pointerBase,
const GCConfig &gcConfig,
std::shared_ptr<CrashManager> crashMgr,
HeapKind kind)
: gcCallbacks_(gcCallbacks),
pointerBase_(pointerBase),
crashMgr_(crashMgr),
heapKind_(kind),
analyticsCallback_(gcConfig.getAnalyticsCallback()),
recordGcStats_(gcConfig.getShouldRecordStats()),
// Start off not in GC.
inGC_(false),
name_(gcConfig.getName()),
allocationLocationTracker_(this),
samplingAllocationTracker_(this),
#ifdef HERMESVM_SANITIZE_HANDLES
sanitizeRate_(gcConfig.getSanitizeConfig().getSanitizeRate()),
#endif
tripwireCallback_(gcConfig.getTripwireConfig().getCallback()),
tripwireLimit_(gcConfig.getTripwireConfig().getLimit())
#ifndef NDEBUG
,
randomizeAllocSpace_(gcConfig.getShouldRandomizeAllocSpace())
#endif
{
buildMetadataTable();
#ifdef HERMESVM_PLATFORM_LOGGING
hermesLog(
"HermesGC",
"Initialisation (Init: %dMB, Max: %dMB, Tripwire: %dMB)",
gcConfig.getInitHeapSize() >> 20,
gcConfig.getMaxHeapSize() >> 20,
gcConfig.getTripwireConfig().getLimit() >> 20);
#endif // HERMESVM_PLATFORM_LOGGING
#ifdef HERMESVM_SANITIZE_HANDLES
const std::minstd_rand::result_type seed =
gcConfig.getSanitizeConfig().getRandomSeed() >= 0
? gcConfig.getSanitizeConfig().getRandomSeed()
: std::random_device()();
if (sanitizeRate_ > 0.0 && sanitizeRate_ < 1.0) {
llvh::errs()
<< "Warning: you are using handle sanitization with random sampling.\n"
<< "Sanitize Rate: ";
llvh::write_double(llvh::errs(), sanitizeRate_, llvh::FloatStyle::Percent);
llvh::errs() << "\n"
<< "Sanitize Rate Seed: " << seed << "\n"
<< "Re-run with -gc-sanitize-handles-random-seed=" << seed
<< " for deterministic crashes.\n";
}
randomEngine_.seed(seed);
#endif
}
GCBase::GCCycle::GCCycle(
GCBase *gc,
OptValue<GCCallbacks *> gcCallbacksOpt,
std::string extraInfo)
: gc_(gc),
gcCallbacksOpt_(gcCallbacksOpt),
extraInfo_(std::move(extraInfo)),
previousInGC_(gc_->inGC_) {
if (!previousInGC_) {
if (gcCallbacksOpt_.hasValue()) {
gcCallbacksOpt_.getValue()->onGCEvent(
GCEventKind::CollectionStart, extraInfo_);
}
gc_->inGC_ = true;
}
}
GCBase::GCCycle::~GCCycle() {
if (!previousInGC_) {
gc_->inGC_ = false;
if (gcCallbacksOpt_.hasValue()) {
gcCallbacksOpt_.getValue()->onGCEvent(
GCEventKind::CollectionEnd, extraInfo_);
}
}
}
void GCBase::runtimeWillExecute() {
if (recordGcStats_ && !execStartTimeRecorded_) {
execStartTime_ = std::chrono::steady_clock::now();
execStartCPUTime_ = oscompat::thread_cpu_time();
oscompat::num_context_switches(
startNumVoluntaryContextSwitches_, startNumInvoluntaryContextSwitches_);
execStartTimeRecorded_ = true;
}
}
std::error_code GCBase::createSnapshotToFile(const std::string &fileName) {
std::error_code code;
llvh::raw_fd_ostream os(fileName, code, llvh::sys::fs::FileAccess::FA_Write);
if (code) {
return code;
}
createSnapshot(os);
return std::error_code{};
}
namespace {
constexpr HeapSnapshot::NodeID objectIDForRootSection(
RootAcceptor::Section section) {
// Since root sections start at zero, and in IDTracker the root sections
// start one past the reserved GC root, this number can be added to
// do conversions.
return GCBase::IDTracker::reserved(
static_cast<GCBase::IDTracker::ReservedObjectID>(
static_cast<HeapSnapshot::NodeID>(
GCBase::IDTracker::ReservedObjectID::GCRoots) +
1 + static_cast<HeapSnapshot::NodeID>(section)));
}
// Abstract base class for all snapshot acceptors.
struct SnapshotAcceptor : public RootAndSlotAcceptorWithNamesDefault {
using RootAndSlotAcceptorWithNamesDefault::accept;
SnapshotAcceptor(PointerBase *base, HeapSnapshot &snap)
: RootAndSlotAcceptorWithNamesDefault(base), snap_(snap) {}
void acceptHV(HermesValue &hv, const char *name) override {
if (hv.isPointer()) {
GCCell *ptr = static_cast<GCCell *>(hv.getPointer());
accept(ptr, name);
}
}
void acceptSHV(SmallHermesValue &hv, const char *name) override {
if (hv.isPointer()) {
GCCell *ptr = static_cast<GCCell *>(hv.getPointer(pointerBase_));
accept(ptr, name);
}
}
protected:
HeapSnapshot &snap_;
};
struct PrimitiveNodeAcceptor : public SnapshotAcceptor {
using SnapshotAcceptor::accept;
PrimitiveNodeAcceptor(
PointerBase *base,
HeapSnapshot &snap,
GCBase::IDTracker &tracker)
: SnapshotAcceptor(base, snap), tracker_(tracker) {}
// Do nothing for any value except a number.
void accept(GCCell *&ptr, const char *name) override {}
void acceptHV(HermesValue &hv, const char *) override {
if (hv.isNumber()) {
seenNumbers_.insert(hv.getNumber());
}
}
void acceptSHV(SmallHermesValue &hv, const char *) override {
if (hv.isNumber()) {
seenNumbers_.insert(hv.getNumber(pointerBase_));
}
}
void writeAllNodes() {
// Always write out the nodes for singletons.
snap_.beginNode();
snap_.endNode(
HeapSnapshot::NodeType::Object,
"undefined",
GCBase::IDTracker::reserved(
GCBase::IDTracker::ReservedObjectID::Undefined),
0,
0);
snap_.beginNode();
snap_.endNode(
HeapSnapshot::NodeType::Object,
"null",
GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::Null),
0,
0);
snap_.beginNode();
snap_.endNode(
HeapSnapshot::NodeType::Object,
"true",
GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::True),
0,
0);
snap_.beginNode();
snap_.endNode(
HeapSnapshot::NodeType::Object,
"false",
GCBase::IDTracker::reserved(GCBase::IDTracker::ReservedObjectID::False),
0,
0);
for (double num : seenNumbers_) {
// A number never has any edges, so just make a node for it.
snap_.beginNode();
// Convert the number value to a string, according to the JS conversion
// routines.
char buf[hermes::NUMBER_TO_STRING_BUF_SIZE];
size_t len = hermes::numberToString(num, buf, sizeof(buf));
snap_.endNode(
HeapSnapshot::NodeType::Number,
llvh::StringRef{buf, len},
tracker_.getNumberID(num),
// Numbers are zero-sized in the heap because they're stored inline.
0,
0);
}
}
private:
GCBase::IDTracker &tracker_;
// Track all numbers that are seen in a heap pass, and only emit one node for
// each of them.
llvh::DenseSet<double, GCBase::IDTracker::DoubleComparator> seenNumbers_;
};
struct EdgeAddingAcceptor : public SnapshotAcceptor, public WeakRefAcceptor {
using SnapshotAcceptor::accept;
EdgeAddingAcceptor(GCBase &gc, HeapSnapshot &snap)
: SnapshotAcceptor(gc.getPointerBase(), snap), gc_(gc) {}
void accept(GCCell *&ptr, const char *name) override {
if (!ptr) {
return;
}
snap_.addNamedEdge(
HeapSnapshot::EdgeType::Internal,
llvh::StringRef::withNullAsEmpty(name),
gc_.getObjectID(ptr));
}
void acceptHV(HermesValue &hv, const char *name) override {
if (auto id = gc_.getSnapshotID(hv)) {
snap_.addNamedEdge(
HeapSnapshot::EdgeType::Internal,
llvh::StringRef::withNullAsEmpty(name),
id.getValue());
}
}
void acceptSHV(SmallHermesValue &shv, const char *name) override {
HermesValue hv = shv.toHV(pointerBase_);
acceptHV(hv, name);
}
void accept(WeakRefBase &wr) override {
WeakRefSlot *slot = wr.unsafeGetSlot();
if (slot->state() == WeakSlotState::Free) {
// If the slot is free, there's no edge to add.
return;
}
if (!slot->hasPointer()) {
// Filter out empty refs from adding edges.
return;
}
// Assume all weak pointers have no names, and are stored in an array-like
// structure.
std::string indexName = std::to_string(nextEdge_++);
snap_.addNamedEdge(
HeapSnapshot::EdgeType::Weak,
indexName,
gc_.getObjectID(slot->getPointer()));
}
void acceptSym(SymbolID sym, const char *name) override {
if (sym.isInvalid()) {
return;
}
snap_.addNamedEdge(
HeapSnapshot::EdgeType::Internal,
llvh::StringRef::withNullAsEmpty(name),
gc_.getObjectID(sym));
}
private:
GCBase &gc_;
// For unnamed edges, use indices instead.
unsigned nextEdge_{0};
};
struct SnapshotRootSectionAcceptor : public SnapshotAcceptor,
public WeakAcceptorDefault {
using SnapshotAcceptor::accept;
using WeakRootAcceptor::acceptWeak;
SnapshotRootSectionAcceptor(PointerBase *base, HeapSnapshot &snap)
: SnapshotAcceptor(base, snap), WeakAcceptorDefault(base) {}
void accept(GCCell *&, const char *) override {
// While adding edges to root sections, there's no need to do anything for
// pointers.
}
void accept(WeakRefBase &wr) override {
// Same goes for weak refs.
}
void acceptWeak(GCCell *&ptr) override {
// Same goes for weak pointers.
}
void beginRootSection(Section section) override {
// Make an element edge from the super root to each root section.
snap_.addIndexedEdge(
HeapSnapshot::EdgeType::Element,
rootSectionNum_++,
objectIDForRootSection(section));
}
void endRootSection() override {
// Do nothing for the end of the root section.
}
private:
// v8's roots start numbering at 1.
int rootSectionNum_{1};
};
struct SnapshotRootAcceptor : public SnapshotAcceptor,
public WeakAcceptorDefault {
using SnapshotAcceptor::accept;
using WeakRootAcceptor::acceptWeak;
SnapshotRootAcceptor(GCBase &gc, HeapSnapshot &snap)
: SnapshotAcceptor(gc.getPointerBase(), snap),
WeakAcceptorDefault(gc.getPointerBase()),
gc_(gc) {}
void accept(GCCell *&ptr, const char *name) override {
pointerAccept(ptr, name, false);
}
void acceptWeak(GCCell *&ptr) override {
pointerAccept(ptr, nullptr, true);
}
void accept(WeakRefBase &wr) override {
WeakRefSlot *slot = wr.unsafeGetSlot();
if (slot->state() == WeakSlotState::Free) {
// If the slot is free, there's no edge to add.
return;
}
if (!slot->hasPointer()) {
// Filter out empty refs from adding edges.
return;
}
pointerAccept(slot->getPointer(), nullptr, true);
}
void acceptSym(SymbolID sym, const char *name) override {
if (sym.isInvalid()) {
return;
}
auto nameRef = llvh::StringRef::withNullAsEmpty(name);
const auto id = gc_.getObjectID(sym);
if (!nameRef.empty()) {
snap_.addNamedEdge(HeapSnapshot::EdgeType::Internal, nameRef, id);
} else {
// Unnamed edges get indices.
snap_.addIndexedEdge(HeapSnapshot::EdgeType::Element, nextEdge_++, id);
}
}
void provideSnapshot(
const std::function<void(HeapSnapshot &)> &func) override {
func(snap_);
}
void beginRootSection(Section section) override {
assert(
currentSection_ == Section::InvalidSection &&
"beginRootSection called while previous section is open");
snap_.beginNode();
currentSection_ = section;
}
void endRootSection() override {
// A root section creates a synthetic node with that name and makes edges
// come from that root.
static const char *rootNames[] = {
// Parentheses around the name is adopted from V8's roots.
#define ROOT_SECTION(name) "(" #name ")",
#include "hermes/VM/RootSections.def"
};
snap_.endNode(
HeapSnapshot::NodeType::Synthetic,
rootNames[static_cast<unsigned>(currentSection_)],
objectIDForRootSection(currentSection_),
// The heap visualizer doesn't like it when these synthetic nodes have a
// size (it describes them as living in the heap).
0,
0);
currentSection_ = Section::InvalidSection;
// Reset the edge counter, so each root section's unnamed edges start at
// zero.
nextEdge_ = 0;
}
private:
GCBase &gc_;
llvh::DenseSet<HeapSnapshot::NodeID> seenIDs_;
// For unnamed edges, use indices instead.
unsigned nextEdge_{0};
Section currentSection_{Section::InvalidSection};
void pointerAccept(GCCell *ptr, const char *name, bool weak) {
assert(
currentSection_ != Section::InvalidSection &&
"accept called outside of begin/end root section pair");
if (!ptr) {
return;
}
const auto id = gc_.getObjectID(ptr);
if (!seenIDs_.insert(id).second) {
// Already seen this node, don't add another edge.
return;
}
auto nameRef = llvh::StringRef::withNullAsEmpty(name);
if (!nameRef.empty()) {
snap_.addNamedEdge(
weak ? HeapSnapshot::EdgeType::Weak
: HeapSnapshot::EdgeType::Internal,
nameRef,
id);
} else if (weak) {
std::string numericName = std::to_string(nextEdge_++);
snap_.addNamedEdge(HeapSnapshot::EdgeType::Weak, numericName.c_str(), id);
} else {
// Unnamed edges get indices.
snap_.addIndexedEdge(HeapSnapshot::EdgeType::Element, nextEdge_++, id);
}
}
};
} // namespace
void GCBase::createSnapshot(GC *gc, llvh::raw_ostream &os) {
JSONEmitter json(os);
HeapSnapshot snap(json, gcCallbacks_->getStackTracesTree());
const auto rootScan = [gc, &snap, this]() {
{
// Make the super root node and add edges to each root section.
SnapshotRootSectionAcceptor rootSectionAcceptor(getPointerBase(), snap);
// The super root has a single element pointing to the "(GC roots)"
// synthetic node. v8 also has some "shortcut" edges to things like the
// global object, but those don't seem necessary for correctness.
snap.beginNode();
snap.addIndexedEdge(
HeapSnapshot::EdgeType::Element,
1,
IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots));
snap.endNode(
HeapSnapshot::NodeType::Synthetic,
"",
IDTracker::reserved(IDTracker::ReservedObjectID::SuperRoot),
0,
0);
snapshotAddGCNativeNodes(snap);
snap.beginNode();
markRoots(rootSectionAcceptor, true);
markWeakRoots(rootSectionAcceptor, /*markLongLived*/ true);
snapshotAddGCNativeEdges(snap);
snap.endNode(
HeapSnapshot::NodeType::Synthetic,
"(GC roots)",
static_cast<HeapSnapshot::NodeID>(
IDTracker::reserved(IDTracker::ReservedObjectID::GCRoots)),
0,
0);
}
{
// Make a node for each root section and add edges into the actual heap.
// Within a root section, there might be duplicates. The root acceptor
// filters out duplicate edges because there cannot be duplicate edges to
// nodes reachable from the super root.
SnapshotRootAcceptor rootAcceptor(*gc, snap);
markRoots(rootAcceptor, true);
markWeakRoots(rootAcceptor, /*markLongLived*/ true);
}
gcCallbacks_->visitIdentifiers([&snap, this](
SymbolID sym,
const StringPrimitive *str) {
snap.beginNode();
if (str) {
snap.addNamedEdge(
HeapSnapshot::EdgeType::Internal, "description", getObjectID(str));
}
snap.endNode(
HeapSnapshot::NodeType::Symbol,
convertSymbolToUTF8(sym),
idTracker_.getObjectID(sym),
sizeof(SymbolID),
0);
});
};
snap.beginSection(HeapSnapshot::Section::Nodes);
rootScan();
// Add all primitive values as nodes if they weren't added before.
// This must be done as a step before adding any edges to these nodes.
// In particular, custom edge adders might try to add edges to primitives that
// haven't been recorded yet.
// The acceptor is recording some state between objects, so define it outside
// the loop.
PrimitiveNodeAcceptor primitiveAcceptor(
getPointerBase(), snap, getIDTracker());
SlotVisitorWithNames<PrimitiveNodeAcceptor> primitiveVisitor{
primitiveAcceptor};
// Add a node for each object in the heap.
const auto snapshotForObject =
[&snap, &primitiveVisitor, gc, this](GCCell *cell) {
auto &allocationLocationTracker = getAllocationLocationTracker();
// First add primitive nodes.
markCellWithNames(primitiveVisitor, cell);
EdgeAddingAcceptor acceptor(*gc, snap);
SlotVisitorWithNames<EdgeAddingAcceptor> visitor(acceptor);
// Allow nodes to add extra nodes not in the JS heap.
cell->getVT()->snapshotMetaData.addNodes(cell, gc, snap);
snap.beginNode();
// Add all internal edges first.
markCellWithNames(visitor, cell);
// Allow nodes to add custom edges not represented by metadata.
cell->getVT()->snapshotMetaData.addEdges(cell, gc, snap);
auto stackTracesTreeNode =
allocationLocationTracker.getStackTracesTreeNodeForAlloc(
gc->getObjectID(cell));
snap.endNode(
cell->getVT()->snapshotMetaData.nodeType(),
cell->getVT()->snapshotMetaData.nameForNode(cell, gc),
gc->getObjectID(cell),
cell->getAllocatedSize(),
stackTracesTreeNode ? stackTracesTreeNode->id : 0);
};
gc->forAllObjs(snapshotForObject);
// Write the singleton number nodes into the snapshot.
primitiveAcceptor.writeAllNodes();
snap.endSection(HeapSnapshot::Section::Nodes);
snap.beginSection(HeapSnapshot::Section::Edges);
rootScan();
// No need to run the primitive scan again, as it only adds nodes, not edges.
// Add edges between objects in the heap.
forAllObjs(snapshotForObject);
snap.endSection(HeapSnapshot::Section::Edges);
snap.emitAllocationTraceInfo();
snap.beginSection(HeapSnapshot::Section::Samples);
getAllocationLocationTracker().addSamplesToSnapshot(snap);
snap.endSection(HeapSnapshot::Section::Samples);
snap.beginSection(HeapSnapshot::Section::Locations);
forAllObjs([&snap, gc](GCCell *cell) {
cell->getVT()->snapshotMetaData.addLocations(cell, gc, snap);
});
snap.endSection(HeapSnapshot::Section::Locations);
}
void GCBase::snapshotAddGCNativeNodes(HeapSnapshot &snap) {
snap.beginNode();
snap.endNode(
HeapSnapshot::NodeType::Native,
"std::deque<WeakRefSlot>",
IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage),
weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type),
0);
}
void GCBase::snapshotAddGCNativeEdges(HeapSnapshot &snap) {
snap.addNamedEdge(
HeapSnapshot::EdgeType::Internal,
"weakRefSlots",
IDTracker::reserved(IDTracker::ReservedObjectID::WeakRefSlotStorage));
}
void GCBase::enableHeapProfiler(
std::function<void(
uint64_t,
std::chrono::microseconds,
std::vector<GCBase::AllocationLocationTracker::HeapStatsUpdate>)>
fragmentCallback) {
getAllocationLocationTracker().enable(std::move(fragmentCallback));
}
void GCBase::disableHeapProfiler() {
getAllocationLocationTracker().disable();
}
void GCBase::enableSamplingHeapProfiler(size_t samplingInterval, int64_t seed) {
getSamplingAllocationTracker().enable(samplingInterval, seed);
}
void GCBase::disableSamplingHeapProfiler(llvh::raw_ostream &os) {
getSamplingAllocationTracker().disable(os);
}
void GCBase::checkTripwire(size_t dataSize) {
if (LLVM_LIKELY(!tripwireCallback_) ||
LLVM_LIKELY(dataSize < tripwireLimit_) || tripwireCalled_) {
return;
}
class Ctx : public GCTripwireContext {
public:
Ctx(GCBase *gc) : gc_(gc) {}
std::error_code createSnapshotToFile(const std::string &path) override {
return gc_->createSnapshotToFile(path);
}
std::error_code createSnapshot(std::ostream &os) override {
llvh::raw_os_ostream ros(os);
gc_->createSnapshot(ros);
return std::error_code{};
}
private:
GCBase *gc_;
} ctx(this);
tripwireCalled_ = true;
tripwireCallback_(ctx);
}
void GCBase::printAllCollectedStats(llvh::raw_ostream &os) {
if (!recordGcStats_)
return;
dump(os);
os << "GC stats:\n";
JSONEmitter json{os, /*pretty*/ true};
json.openDict();
printStats(json);
json.closeDict();
os << "\n";
}
void GCBase::getHeapInfo(HeapInfo &info) {
info.numCollections = cumStats_.numCollections;
}
void GCBase::getHeapInfoWithMallocSize(HeapInfo &info) {
// Assign to overwrite anything previously in the heap info.
// A deque doesn't have a capacity, so the size is the lower bound.
info.mallocSizeEstimate =
weakSlots_.size() * sizeof(decltype(weakSlots_)::value_type);
}
#ifndef NDEBUG
void GCBase::getDebugHeapInfo(DebugHeapInfo &info) {
recordNumAllocatedObjects();
info.numAllocatedObjects = numAllocatedObjects_;
info.numReachableObjects = numReachableObjects_;
info.numCollectedObjects = numCollectedObjects_;
info.numFinalizedObjects = numFinalizedObjects_;
info.numMarkedSymbols = numMarkedSymbols_;
info.numHiddenClasses = numHiddenClasses_;
info.numLeafHiddenClasses = numLeafHiddenClasses_;
}
size_t GCBase::countUsedWeakRefs() const {
size_t count = 0;
for (auto &slot : weakSlots_) {
if (slot.state() != WeakSlotState::Free) {
++count;
}
}
return count;
}
#endif
#ifndef NDEBUG
void GCBase::DebugHeapInfo::assertInvariants() const {
// The number of allocated objects at any time is at least the number
// found reachable in the last collection.
assert(numAllocatedObjects >= numReachableObjects);
// The number of objects finalized in the last collection is at most the
// number of objects collected.
assert(numCollectedObjects >= numFinalizedObjects);
}
#endif
void GCBase::dump(llvh::raw_ostream &, bool) { /* nop */
}
void GCBase::printStats(JSONEmitter &json) {
json.emitKeyValue("type", "hermes");
json.emitKeyValue("version", 0);
gcCallbacks_->printRuntimeGCStats(json);
std::chrono::duration<double> elapsedTime =
std::chrono::steady_clock::now() - execStartTime_;
auto elapsedCPUSeconds =
std::chrono::duration_cast<std::chrono::duration<double>>(
oscompat::thread_cpu_time())
.count() -
std::chrono::duration_cast<std::chrono::duration<double>>(
execStartCPUTime_)
.count();
HeapInfo info;
getHeapInfoWithMallocSize(info);
getHeapInfo(info);
#ifndef NDEBUG
DebugHeapInfo debugInfo;
getDebugHeapInfo(debugInfo);
#endif
json.emitKey("heapInfo");
json.openDict();
#ifndef NDEBUG
json.emitKeyValue("Num allocated cells", debugInfo.numAllocatedObjects);
json.emitKeyValue("Num reachable cells", debugInfo.numReachableObjects);
json.emitKeyValue("Num collected cells", debugInfo.numCollectedObjects);
json.emitKeyValue("Num finalized cells", debugInfo.numFinalizedObjects);
json.emitKeyValue("Num marked symbols", debugInfo.numMarkedSymbols);
json.emitKeyValue("Num hidden classes", debugInfo.numHiddenClasses);
json.emitKeyValue("Num leaf classes", debugInfo.numLeafHiddenClasses);
json.emitKeyValue("Num weak references", ((GC *)this)->countUsedWeakRefs());
#endif
json.emitKeyValue("Peak RSS", oscompat::peak_rss());
json.emitKeyValue("Current RSS", oscompat::current_rss());
json.emitKeyValue("Current Dirty", oscompat::current_private_dirty());
json.emitKeyValue("Heap size", info.heapSize);
json.emitKeyValue("Allocated bytes", info.allocatedBytes);
json.emitKeyValue("Num collections", info.numCollections);
json.emitKeyValue("Malloc size", info.mallocSizeEstimate);
json.closeDict();
long vol = -1;
long invol = -1;
if (oscompat::num_context_switches(vol, invol)) {
vol -= startNumVoluntaryContextSwitches_;
invol -= startNumInvoluntaryContextSwitches_;
}
json.emitKey("general");
json.openDict();
json.emitKeyValue("numCollections", cumStats_.numCollections);
json.emitKeyValue("totalTime", elapsedTime.count());
json.emitKeyValue("totalCPUTime", elapsedCPUSeconds);
json.emitKeyValue("totalGCTime", formatSecs(cumStats_.gcWallTime.sum()).secs);
json.emitKeyValue("volCtxSwitch", vol);
json.emitKeyValue("involCtxSwitch", invol);
json.emitKeyValue(
"avgGCPause", formatSecs(cumStats_.gcWallTime.average()).secs);
json.emitKeyValue("maxGCPause", formatSecs(cumStats_.gcWallTime.max()).secs);
json.emitKeyValue(
"totalGCCPUTime", formatSecs(cumStats_.gcCPUTime.sum()).secs);
json.emitKeyValue(
"avgGCCPUPause", formatSecs(cumStats_.gcCPUTime.average()).secs);
json.emitKeyValue(
"maxGCCPUPause", formatSecs(cumStats_.gcCPUTime.max()).secs);
json.emitKeyValue("finalHeapSize", formatSize(cumStats_.finalHeapSize).bytes);
json.emitKeyValue(
"peakAllocatedBytes", formatSize(getPeakAllocatedBytes()).bytes);
json.emitKeyValue("peakLiveAfterGC", formatSize(getPeakLiveAfterGC()).bytes);
json.emitKeyValue(
"totalAllocatedBytes", formatSize(info.totalAllocatedBytes).bytes);
json.closeDict();
json.emitKey("collections");
json.openArray();
for (const auto &event : analyticsEvents_) {
json.openDict();
json.emitKeyValue("runtimeDescription", event.runtimeDescription);
json.emitKeyValue("gcKind", event.gcKind);
json.emitKeyValue("collectionType", event.collectionType);
json.emitKeyValue("cause", event.cause);
json.emitKeyValue("duration", event.duration.count());
json.emitKeyValue("cpuDuration", event.cpuDuration.count());
json.emitKeyValue("preAllocated", event.allocated.before);
json.emitKeyValue("postAllocated", event.allocated.after);
json.emitKeyValue("preSize", event.size.before);
json.emitKeyValue("postSize", event.size.after);
json.emitKeyValue("preExternal", event.external.before);
json.emitKeyValue("postExternal", event.external.after);
json.emitKeyValue("survivalRatio", event.survivalRatio);
json.emitKey("tags");
json.openArray();
for (const auto &tag : event.tags) {
json.emitValue(tag);
}
json.closeArray();
json.closeDict();
}
json.closeArray();
}
void GCBase::recordGCStats(
const GCAnalyticsEvent &event,
CumulativeHeapStats *stats,
bool onMutator) {
// Hades OG collections do not block the mutator, and so do not contribute to
// the max pause time or the total execution time.
if (onMutator)
stats->gcWallTime.record(
std::chrono::duration<double>(event.duration).count());
stats->gcCPUTime.record(
std::chrono::duration<double>(event.cpuDuration).count());
stats->finalHeapSize = event.size.after;
stats->usedBefore.record(event.allocated.before);
stats->usedAfter.record(event.allocated.after);
stats->numCollections++;
}
void GCBase::recordGCStats(const GCAnalyticsEvent &event, bool onMutator) {
if (analyticsCallback_) {
analyticsCallback_(event);
}
if (recordGcStats_) {
analyticsEvents_.push_back(event);
}
recordGCStats(event, &cumStats_, onMutator);
}
void GCBase::oom(std::error_code reason) {
#ifdef HERMESVM_EXCEPTION_ON_OOM
HeapInfo heapInfo;
getHeapInfo(heapInfo);
char detailBuffer[400];
snprintf(
detailBuffer,
sizeof(detailBuffer),
"Javascript heap memory exhausted: heap size = %d, allocated = %d.",
heapInfo.heapSize,
heapInfo.allocatedBytes);
// No need to run finalizeAll, the exception will propagate and eventually run
// ~Runtime.
throw JSOutOfMemoryError(
std::string(detailBuffer) + "\ncall stack:\n" +
gcCallbacks_->getCallStackNoAlloc());
#else
oomDetail(reason);
hermes_fatal("OOM", reason);
#endif
}
void GCBase::oomDetail(std::error_code reason) {
HeapInfo heapInfo;
getHeapInfo(heapInfo);
// Could use a stringstream here, but want to avoid dynamic allocation.
char detailBuffer[400];
snprintf(
detailBuffer,
sizeof(detailBuffer),
"[%.20s] reason = %.150s (%d from category: %.50s), numCollections = %d, heapSize = %d, allocated = %d, va = %" PRIu64,
name_.c_str(),
reason.message().c_str(),
reason.value(),
reason.category().name(),
heapInfo.numCollections,
heapInfo.heapSize,
heapInfo.allocatedBytes,
heapInfo.va);
hermesLog("HermesGC", "OOM: %s.", detailBuffer);
// Record the OOM custom data with the crash manager.
crashMgr_->setCustomData("HermesGCOOMDetailBasic", detailBuffer);
}
#ifndef NDEBUG
/*static*/
bool GCBase::isMostRecentCellInFinalizerVector(
const std::vector<GCCell *> &finalizables,
const GCCell *cell) {
return !finalizables.empty() && finalizables.back() == cell;
}
#endif
#ifdef HERMESVM_SANITIZE_HANDLES
bool GCBase::shouldSanitizeHandles() {
static std::uniform_real_distribution<> dist(0.0, 1.0);
return dist(randomEngine_) < sanitizeRate_;
}
#endif
#ifdef HERMESVM_GC_RUNTIME
#define GCBASE_BARRIER_1(name, type1) \
void GCBase::name(type1 arg1) { \
runtimeGCDispatch([&](auto *gc) { gc->name(arg1); }); \
}
#define GCBASE_BARRIER_2(name, type1, type2) \
void GCBase::name(type1 arg1, type2 arg2) { \
runtimeGCDispatch([&](auto *gc) { gc->name(arg1, arg2); }); \
}
GCBASE_BARRIER_2(writeBarrier, const GCHermesValue *, HermesValue);
GCBASE_BARRIER_2(writeBarrier, const GCSmallHermesValue *, SmallHermesValue);
GCBASE_BARRIER_2(writeBarrier, const GCPointerBase *, const GCCell *);
GCBASE_BARRIER_2(constructorWriteBarrier, const GCHermesValue *, HermesValue);
GCBASE_BARRIER_2(
constructorWriteBarrier,
const GCSmallHermesValue *,
SmallHermesValue);
GCBASE_BARRIER_2(
constructorWriteBarrier,
const GCPointerBase *,
const GCCell *);
GCBASE_BARRIER_2(writeBarrierRange, const GCHermesValue *, uint32_t);
GCBASE_BARRIER_2(writeBarrierRange, const GCSmallHermesValue *, uint32_t);
GCBASE_BARRIER_2(constructorWriteBarrierRange, const GCHermesValue *, uint32_t);
GCBASE_BARRIER_2(
constructorWriteBarrierRange,
const GCSmallHermesValue *,
uint32_t);
GCBASE_BARRIER_1(snapshotWriteBarrier, const GCHermesValue *);
GCBASE_BARRIER_1(snapshotWriteBarrier, const GCSmallHermesValue *);
GCBASE_BARRIER_1(snapshotWriteBarrier, const GCPointerBase *);
GCBASE_BARRIER_1(snapshotWriteBarrier, const GCSymbolID *);
GCBASE_BARRIER_2(snapshotWriteBarrierRange, const GCHermesValue *, uint32_t);
GCBASE_BARRIER_2(
snapshotWriteBarrierRange,
const GCSmallHermesValue *,
uint32_t);
GCBASE_BARRIER_1(weakRefReadBarrier, GCCell *);
GCBASE_BARRIER_1(weakRefReadBarrier, HermesValue);
#undef GCBASE_BARRIER_1
#undef GCBASE_BARRIER_2
#endif
/*static*/
std::vector<detail::WeakRefKey *> GCBase::buildKeyList(
GC *gc,
JSWeakMap *weakMap) {
std::vector<detail::WeakRefKey *> res;
for (auto iter = weakMap->keys_begin(), end = weakMap->keys_end();
iter != end;
iter++) {
if (iter->getObject(gc)) {
res.push_back(&(*iter));
}
}
return res;
}
HeapSnapshot::NodeID GCBase::getObjectID(const GCCell *cell) {
assert(cell && "Called getObjectID on a null pointer");
return getObjectID(
CompressedPointer{pointerBase_, const_cast<GCCell *>(cell)});
}
HeapSnapshot::NodeID GCBase::getObjectIDMustExist(const GCCell *cell) {
assert(cell && "Called getObjectID on a null pointer");
return idTracker_.getObjectIDMustExist(
CompressedPointer{pointerBase_, const_cast<GCCell *>(cell)});
}
HeapSnapshot::NodeID GCBase::getObjectID(CompressedPointer cell) {
assert(cell && "Called getObjectID on a null pointer");
return idTracker_.getObjectID(cell);
}