forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntime.cpp
More file actions
2390 lines (2108 loc) · 81.2 KB
/
Runtime.cpp
File metadata and controls
2390 lines (2108 loc) · 81.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#define DEBUG_TYPE "vm"
#include "hermes/VM/Runtime.h"
#include "hermes/AST/SemValidate.h"
#include "hermes/BCGen/HBC/BytecodeDataProvider.h"
#include "hermes/BCGen/HBC/BytecodeProviderFromSrc.h"
#include "hermes/BCGen/HBC/SimpleBytecodeBuilder.h"
#include "hermes/FrontEndDefs/Builtins.h"
#include "hermes/InternalBytecode/InternalBytecode.h"
#include "hermes/Platform/Logging.h"
#include "hermes/Support/OSCompat.h"
#include "hermes/Support/PerfSection.h"
#include "hermes/VM/AlignedStorage.h"
#include "hermes/VM/BuildMetadata.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/CodeBlock.h"
#include "hermes/VM/Domain.h"
#include "hermes/VM/FillerCell.h"
#include "hermes/VM/IdentifierTable.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSError.h"
#include "hermes/VM/JSLib.h"
#include "hermes/VM/JSLib/RuntimeCommonStorage.h"
#include "hermes/VM/MockedEnvironment.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/PredefinedStringIDs.h"
#include "hermes/VM/Profiler/CodeCoverageProfiler.h"
#include "hermes/VM/Profiler/SamplingProfiler.h"
#include "hermes/VM/StackFrame-inline.h"
#include "hermes/VM/StackTracesTree.h"
#include "hermes/VM/StringView.h"
#ifndef HERMESVM_LEAN
#include "hermes/Support/MemoryBuffer.h"
#endif
#include "llvh/ADT/Hashing.h"
#include "llvh/Support/Debug.h"
#include "llvh/Support/raw_ostream.h"
#ifdef HERMESVM_PROFILER_BB
#include "hermes/VM/IterationKind.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/Profiler/InlineCacheProfiler.h"
#include "llvh/ADT/DenseMap.h"
#endif
namespace hermes {
namespace vm {
namespace {
/// The maximum number of registers that can be requested in a RuntimeConfig.
static constexpr uint32_t kMaxSupportedNumRegisters =
UINT32_MAX / sizeof(PinnedHermesValue);
// Only track I/O for buffers > 64 kB (which excludes things like
// Runtime::generateSpecialRuntimeBytecode).
static constexpr size_t MIN_IO_TRACKING_SIZE = 64 * 1024;
static const Predefined::Str fixedPropCacheNames[(size_t)PropCacheID::_COUNT] =
{
#define V(id, predef) predef,
PROP_CACHE_IDS(V)
#undef V
};
} // namespace
/* static */
std::shared_ptr<Runtime> Runtime::create(const RuntimeConfig &runtimeConfig) {
return std::shared_ptr<Runtime>{
new Runtime(StorageProvider::mmapProvider(), runtimeConfig)};
}
CallResult<PseudoHandle<>> Runtime::getNamed(
Handle<JSObject> obj,
PropCacheID id) {
CompressedPointer clazzPtr{obj->getClassGCPtr()};
auto *cacheEntry = &fixedPropCache_[static_cast<int>(id)];
if (LLVM_LIKELY(cacheEntry->clazz == clazzPtr)) {
// The slot is cached, so it is safe to use the Internal function.
return createPseudoHandle(
JSObject::getNamedSlotValueUnsafe<PropStorage::Inline::Yes>(
*obj, this, cacheEntry->slot)
.unboxToHV(this));
}
auto sym = Predefined::getSymbolID(fixedPropCacheNames[static_cast<int>(id)]);
NamedPropertyDescriptor desc;
// Check writable and internalSetter flags since the cache slot is shared for
// get/put.
if (LLVM_LIKELY(
JSObject::tryGetOwnNamedDescriptorFast(*obj, this, sym, desc)) &&
!desc.flags.accessor && desc.flags.writable &&
!desc.flags.internalSetter) {
HiddenClass *clazz = vmcast<HiddenClass>(clazzPtr.getNonNull(this));
if (LLVM_LIKELY(!clazz->isDictionary())) {
// Cache the class, id and property slot.
cacheEntry->clazz = clazzPtr;
cacheEntry->slot = desc.slot;
}
return JSObject::getNamedSlotValue(createPseudoHandle(*obj), this, desc);
}
return JSObject::getNamed_RJS(obj, this, sym);
}
ExecutionStatus Runtime::putNamedThrowOnError(
Handle<JSObject> obj,
PropCacheID id,
SmallHermesValue shv) {
CompressedPointer clazzPtr{obj->getClassGCPtr()};
auto *cacheEntry = &fixedPropCache_[static_cast<int>(id)];
if (LLVM_LIKELY(cacheEntry->clazz == clazzPtr)) {
JSObject::setNamedSlotValueUnsafe<PropStorage::Inline::Yes>(
*obj, this, cacheEntry->slot, shv);
return ExecutionStatus::RETURNED;
}
auto sym = Predefined::getSymbolID(fixedPropCacheNames[static_cast<int>(id)]);
NamedPropertyDescriptor desc;
if (LLVM_LIKELY(
JSObject::tryGetOwnNamedDescriptorFast(*obj, this, sym, desc)) &&
!desc.flags.accessor && desc.flags.writable &&
!desc.flags.internalSetter) {
HiddenClass *clazz = vmcast<HiddenClass>(clazzPtr.getNonNull(this));
if (LLVM_LIKELY(!clazz->isDictionary())) {
// Cache the class and property slot.
cacheEntry->clazz = clazzPtr;
cacheEntry->slot = desc.slot;
}
JSObject::setNamedSlotValueUnsafe(*obj, this, desc.slot, shv);
return ExecutionStatus::RETURNED;
}
Handle<> value = makeHandle(shv.unboxToHV(this));
return JSObject::putNamed_RJS(
obj, this, sym, value, PropOpFlags().plusThrowOnError())
.getStatus();
}
Runtime::Runtime(
std::shared_ptr<StorageProvider> provider,
const RuntimeConfig &runtimeConfig)
// The initial heap size can't be larger than the max.
: enableEval(runtimeConfig.getEnableEval()),
verifyEvalIR(runtimeConfig.getVerifyEvalIR()),
optimizedEval(runtimeConfig.getOptimizedEval()),
asyncBreakCheckInEval(runtimeConfig.getAsyncBreakCheckInEval()),
heapStorage_(
this,
this,
runtimeConfig.getGCConfig(),
runtimeConfig.getCrashMgr(),
std::move(provider),
runtimeConfig.getVMExperimentFlags()),
hasES6Promise_(runtimeConfig.getES6Promise()),
hasES6Proxy_(runtimeConfig.getES6Proxy()),
hasIntl_(runtimeConfig.getIntl()),
shouldRandomizeMemoryLayout_(runtimeConfig.getRandomizeMemoryLayout()),
bytecodeWarmupPercent_(runtimeConfig.getBytecodeWarmupPercent()),
trackIO_(runtimeConfig.getTrackIO()),
vmExperimentFlags_(runtimeConfig.getVMExperimentFlags()),
runtimeStats_(runtimeConfig.getEnableSampledStats()),
commonStorage_(
createRuntimeCommonStorage(runtimeConfig.getTraceEnabled())),
stackPointer_(),
crashMgr_(runtimeConfig.getCrashMgr()),
crashCallbackKey_(
crashMgr_->registerCallback([this](int fd) { crashCallback(fd); })),
codeCoverageProfiler_(std::make_unique<CodeCoverageProfiler>(this)),
gcEventCallback_(runtimeConfig.getGCConfig().getCallback()) {
assert(
(void *)this == (void *)(HandleRootOwner *)this &&
"cast to HandleRootOwner should be no-op");
#ifdef HERMES_FACEBOOK_BUILD
const bool isSnapshot = std::strstr(__FILE__, "hermes-snapshot");
crashMgr_->setCustomData("HermesIsSnapshot", isSnapshot ? "true" : "false");
#endif
auto maxNumRegisters = runtimeConfig.getMaxNumRegisters();
if (LLVM_UNLIKELY(maxNumRegisters > kMaxSupportedNumRegisters)) {
hermes_fatal("RuntimeConfig maxNumRegisters too big");
}
registerStackStart_ = runtimeConfig.getRegisterStack();
if (!registerStackStart_) {
// registerStackAllocation_ should not be allocated with new, because then
// default constructors would run for the whole stack space.
// Round up to page size as required by vm_allocate.
const uint32_t numBytesForRegisters = llvh::alignTo(
sizeof(PinnedHermesValue) * maxNumRegisters, oscompat::page_size());
auto result = oscompat::vm_allocate(numBytesForRegisters);
if (!result) {
hermes_fatal("Failed to allocate register stack", result.getError());
}
registerStackStart_ = static_cast<PinnedHermesValue *>(result.get());
registerStackAllocation_ = {registerStackStart_, numBytesForRegisters};
crashMgr_->registerMemory(registerStackStart_, numBytesForRegisters);
}
registerStackEnd_ = registerStackStart_ + maxNumRegisters;
if (shouldRandomizeMemoryLayout_) {
const unsigned bytesOff = std::random_device()() % oscompat::page_size();
registerStackEnd_ -= bytesOff / sizeof(PinnedHermesValue);
assert(
registerStackEnd_ >= registerStackStart_ && "register stack too small");
}
stackPointer_ = registerStackEnd_;
// Setup the "root" stack frame.
setCurrentFrameToTopOfStack();
// Allocate the "reserved" registers in the root frame.
allocStack(
StackFrameLayout::CalleeExtraRegistersAtStart,
HermesValue::encodeUndefinedValue());
#ifdef HERMESVM_SERIALIZE
if (runtimeConfig.getDeserializeFile()) {
assert(
runtimeConfig.getExternalPointersVectorCallBack() &&
"missing function pointer to map external pointers.");
// If there is a serialized heap file available, use that to initialize
// Runtime instead of re-creating the Runtime.
Deserializer d(
runtimeConfig.getDeserializeFile(),
this,
runtimeConfig.getExternalPointersVectorCallBack());
deserializeImpl(d, runtimeConfig.getGCConfig().getAllocInYoung());
LLVM_DEBUG(llvh::dbgs() << "Runtime initialized\n");
if (runtimeConfig.getEnableSampleProfiling())
samplingProfiler = std::make_unique<SamplingProfiler>(this);
return;
}
#endif // HERMESVM_SERIALIZE
// Initialize Predefined Strings.
// This function does not do any allocations.
initPredefinedStrings();
// Initialize special code blocks pointing to their own runtime module.
// specialCodeBlockRuntimeModule_ will be owned by runtimeModuleList_.
RuntimeModuleFlags flags;
flags.hidesEpilogue = true;
specialCodeBlockDomain_ = Domain::create(this).getHermesValue();
specialCodeBlockRuntimeModule_ = RuntimeModule::createUninitialized(
this, Handle<Domain>::vmcast(&specialCodeBlockDomain_), flags);
assert(
&runtimeModuleList_.back() == specialCodeBlockRuntimeModule_ &&
"specialCodeBlockRuntimeModule_ not added to runtimeModuleList_");
// At this point, allocations can begin, as all the roots are markable.
// Initialize the pre-allocated character strings.
initCharacterStrings();
GCScope scope(this);
// Explicitly initialize the specialCodeBlockRuntimeModule_ without CJS
// modules.
specialCodeBlockRuntimeModule_->initializeWithoutCJSModulesMayAllocate(
hbc::BCProviderFromBuffer::createBCProviderFromBuffer(
generateSpecialRuntimeBytecode())
.first);
emptyCodeBlock_ = specialCodeBlockRuntimeModule_->getCodeBlockMayAllocate(0);
returnThisCodeBlock_ =
specialCodeBlockRuntimeModule_->getCodeBlockMayAllocate(1);
// Initialize the root hidden class and its variants.
{
MutableHandle<HiddenClass> clazz(
this,
vmcast<HiddenClass>(
ignoreAllocationFailure(HiddenClass::createRoot(this))));
rootClazzes_[0] = clazz.getHermesValue();
for (unsigned i = 1; i <= InternalProperty::NumInternalProperties; ++i) {
auto addResult = HiddenClass::reserveSlot(clazz, this);
assert(
addResult != ExecutionStatus::EXCEPTION &&
"Could not possibly grow larger than the limit");
clazz = *addResult->first;
rootClazzes_[i] = clazz.getHermesValue();
}
}
global_ =
JSObject::create(this, Handle<JSObject>(this, nullptr)).getHermesValue();
JSLibFlags jsLibFlags{};
jsLibFlags.enableHermesInternal = runtimeConfig.getEnableHermesInternal();
jsLibFlags.enableHermesInternalTestMethods =
runtimeConfig.getEnableHermesInternalTestMethods();
initGlobalObject(this, jsLibFlags);
// Once the global object has been initialized, populate native builtins to
// the builtins table.
initNativeBuiltins();
// Set the prototype of the global object to the standard object prototype,
// which has now been defined.
ignoreAllocationFailure(JSObject::setParent(
vmcast<JSObject>(global_),
this,
vmcast<JSObject>(objectPrototype),
PropOpFlags().plusThrowOnError()));
symbolRegistry_.init(this);
#ifdef HERMESVM_SERIALIZE
if (runtimeConfig.getSerializeAfterInitFile()) {
assert(
runtimeConfig.getExternalPointersVectorCallBack() &&
"missing function pointer to map external pointers.");
Serializer s(
*runtimeConfig.getSerializeAfterInitFile(),
this,
runtimeConfig.getExternalPointersVectorCallBack());
serialize(s);
}
#endif // HERMESVM_SERIALIZE
// BB Profiler need to be ready before running internal bytecode.
#ifdef HERMESVM_PROFILER_BB
inlineCacheProfiler_.setHiddenClassArray(
ignoreAllocationFailure(JSArray::create(this, 4, 4)).get());
#endif
codeCoverageProfiler_->disable();
// Execute our internal bytecode.
auto jsBuiltinsObj = runInternalBytecode();
codeCoverageProfiler_->restore();
// Populate JS builtins returned from internal bytecode to the builtins table.
initJSBuiltins(builtins_, jsBuiltinsObj);
if (runtimeConfig.getEnableSampleProfiling())
samplingProfiler = std::make_unique<SamplingProfiler>(this);
LLVM_DEBUG(llvh::dbgs() << "Runtime initialized\n");
}
Runtime::~Runtime() {
samplingProfiler.reset();
getHeap().finalizeAll();
// Now that all objects are finalized, there shouldn't be any native memory
// keys left in the ID tracker for memory profiling. Assert that the only IDs
// left are JS heap pointers.
assert(
!getHeap().getIDTracker().hasNativeIDs() &&
"A pointer is left in the ID tracker that is from non-JS memory. "
"Was untrackNative called?");
crashMgr_->unregisterCallback(crashCallbackKey_);
if (!registerStackAllocation_.empty()) {
crashMgr_->unregisterMemory(registerStackAllocation_.data());
oscompat::vm_free(
registerStackAllocation_.data(), registerStackAllocation_.size());
}
// Remove inter-module dependencies so we can delete them in any order.
for (auto &module : runtimeModuleList_) {
module.prepareForRuntimeShutdown();
}
while (!runtimeModuleList_.empty()) {
// Calling delete will automatically remove it from the list.
delete &runtimeModuleList_.back();
}
for (auto callback : destructionCallbacks_) {
callback(this);
}
}
/// A helper class used to measure the duration of GC marking different roots.
/// It accumulates the times in \c Runtime::markRootsPhaseTimes[] and \c
/// Runtime::totalMarkRootsTime.
class Runtime::MarkRootsPhaseTimer {
public:
MarkRootsPhaseTimer(Runtime *rt, RootAcceptor::Section section)
: rt_(rt), section_(section), start_(std::chrono::steady_clock::now()) {
if (static_cast<unsigned>(section) == 0) {
// The first phase; record the start as the start of markRoots.
rt_->startOfMarkRoots_ = start_;
}
}
~MarkRootsPhaseTimer() {
auto tp = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = (tp - start_);
start_ = tp;
unsigned index = static_cast<unsigned>(section_);
rt_->markRootsPhaseTimes_[index] += elapsed.count();
if (index + 1 ==
static_cast<unsigned>(RootAcceptor::Section::NumSections)) {
std::chrono::duration<double> totalElapsed =
(tp - rt_->startOfMarkRoots_);
rt_->totalMarkRootsTime_ += totalElapsed.count();
}
}
private:
Runtime *rt_;
RootAcceptor::Section section_;
std::chrono::time_point<std::chrono::steady_clock> start_;
};
void Runtime::markRoots(
RootAndSlotAcceptorWithNames &acceptor,
bool markLongLived) {
// The body of markRoots should be sequence of blocks, each of which starts
// with the declaration of an appropriate RootSection instance.
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::Registers);
acceptor.beginRootSection(RootAcceptor::Section::Registers);
for (auto *p = stackPointer_, *e = registerStackEnd_; p != e; ++p)
acceptor.accept(*p);
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::RuntimeInstanceVars);
acceptor.beginRootSection(RootAcceptor::Section::RuntimeInstanceVars);
for (auto &clazz : rootClazzes_)
acceptor.accept(clazz, "rootClass");
#define RUNTIME_HV_FIELD_INSTANCE(name) acceptor.accept((name), #name);
#include "hermes/VM/RuntimeHermesValueFields.def"
#undef RUNTIME_HV_FIELD_INSTANCE
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::RuntimeModules);
acceptor.beginRootSection(RootAcceptor::Section::RuntimeModules);
#define RUNTIME_HV_FIELD_RUNTIMEMODULE(name) acceptor.accept(name);
#include "hermes/VM/RuntimeHermesValueFields.def"
#undef RUNTIME_HV_FIELD_RUNTIMEMODULE
for (auto &rm : runtimeModuleList_)
rm.markRoots(acceptor, markLongLived);
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::CharStrings);
acceptor.beginRootSection(RootAcceptor::Section::CharStrings);
if (markLongLived) {
for (auto &hv : charStrings_)
acceptor.accept(hv);
}
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(
this, RootAcceptor::Section::StringCycleCheckVisited);
acceptor.beginRootSection(RootAcceptor::Section::StringCycleCheckVisited);
for (auto *&ptr : stringCycleCheckVisited_)
acceptor.acceptPtr(ptr);
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::Builtins);
acceptor.beginRootSection(RootAcceptor::Section::Builtins);
for (Callable *&f : builtins_)
acceptor.acceptPtr(f);
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::Jobs);
acceptor.beginRootSection(RootAcceptor::Section::Jobs);
for (Callable *&f : jobQueue_)
acceptor.acceptPtr(f);
acceptor.endRootSection();
}
#ifdef MARK
#error "Shouldn't have defined mark already"
#endif
#define MARK(field) acceptor.accept((field), #field)
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::Prototypes);
acceptor.beginRootSection(RootAcceptor::Section::Prototypes);
// Prototypes.
#define RUNTIME_HV_FIELD_PROTOTYPE(name) MARK(name);
#include "hermes/VM/RuntimeHermesValueFields.def"
#undef RUNTIME_HV_FIELD_PROTOTYPE
acceptor.acceptPtr(objectPrototypeRawPtr, "objectPrototype");
acceptor.acceptPtr(functionPrototypeRawPtr, "functionPrototype");
#undef MARK
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::IdentifierTable);
if (markLongLived) {
// Need to add nodes before the root section, and edges during the root
// section.
acceptor.provideSnapshot([this](HeapSnapshot &snap) {
identifierTable_.snapshotAddNodes(snap);
});
acceptor.beginRootSection(RootAcceptor::Section::IdentifierTable);
identifierTable_.markIdentifiers(acceptor, &getHeap());
acceptor.provideSnapshot([this](HeapSnapshot &snap) {
identifierTable_.snapshotAddEdges(snap);
});
acceptor.endRootSection();
}
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::GCScopes);
acceptor.beginRootSection(RootAcceptor::Section::GCScopes);
markGCScopes(acceptor);
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::SymbolRegistry);
acceptor.beginRootSection(RootAcceptor::Section::SymbolRegistry);
symbolRegistry_.markRoots(acceptor);
acceptor.endRootSection();
}
// Mark the alternative roots during the normal mark roots call.
markRootsForCompleteMarking(acceptor);
{
MarkRootsPhaseTimer timer(
this, RootAcceptor::Section::CodeCoverageProfiler);
acceptor.beginRootSection(RootAcceptor::Section::CodeCoverageProfiler);
if (codeCoverageProfiler_) {
codeCoverageProfiler_->markRoots(acceptor);
}
#ifdef HERMESVM_PROFILER_BB
auto *&hiddenClassArray = inlineCacheProfiler_.getHiddenClassArray();
if (hiddenClassArray) {
acceptor.acceptPtr(hiddenClassArray);
}
#endif
acceptor.endRootSection();
}
{
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::Custom);
// Define nodes before the root section starts.
for (auto &fn : customSnapshotNodeFuncs_) {
acceptor.provideSnapshot(fn);
}
acceptor.beginRootSection(RootAcceptor::Section::Custom);
for (auto &fn : customMarkRootFuncs_)
fn(&getHeap(), acceptor);
// Define edges while inside the root section.
for (auto &fn : customSnapshotEdgeFuncs_) {
acceptor.provideSnapshot(fn);
}
acceptor.endRootSection();
}
}
void Runtime::markWeakRoots(WeakRootAcceptor &acceptor, bool markLongLived) {
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::WeakRefs);
acceptor.beginRootSection(RootAcceptor::Section::WeakRefs);
if (markLongLived) {
for (auto &entry : fixedPropCache_) {
acceptor.acceptWeak(entry.clazz);
}
for (auto &rm : runtimeModuleList_)
rm.markWeakRoots(acceptor);
}
for (auto &fn : customMarkWeakRootFuncs_)
fn(&getHeap(), acceptor);
acceptor.endRootSection();
}
void Runtime::markRootsForCompleteMarking(
RootAndSlotAcceptorWithNames &acceptor) {
MarkRootsPhaseTimer timer(this, RootAcceptor::Section::SamplingProfiler);
acceptor.beginRootSection(RootAcceptor::Section::SamplingProfiler);
if (samplingProfiler) {
samplingProfiler->markRoots(acceptor);
}
acceptor.endRootSection();
}
void Runtime::visitIdentifiers(
const std::function<void(SymbolID, const StringPrimitive *)> &acceptor) {
identifierTable_.visitIdentifiers(acceptor);
}
std::string Runtime::convertSymbolToUTF8(SymbolID id) {
return identifierTable_.convertSymbolToUTF8(id);
}
void Runtime::printRuntimeGCStats(JSONEmitter &json) const {
const unsigned kNumPhases =
static_cast<unsigned>(RootAcceptor::Section::NumSections);
#define ROOT_SECTION(phase) "MarkRoots_" #phase,
static const char *markRootsPhaseNames[kNumPhases] = {
#include "hermes/VM/RootSections.def"
};
#undef ROOT_SECTION
json.emitKey("runtime");
json.openDict();
json.emitKeyValue("totalMarkRootsTime", formatSecs(totalMarkRootsTime_).secs);
for (unsigned phaseNum = 0; phaseNum < kNumPhases; phaseNum++) {
json.emitKeyValue(
std::string(markRootsPhaseNames[phaseNum]) + "Time",
formatSecs(markRootsPhaseTimes_[phaseNum]).secs);
}
json.closeDict();
}
void Runtime::printHeapStats(llvh::raw_ostream &os) {
// Printing the timings is unstable.
if (shouldStabilizeInstructionCount())
return;
getHeap().printAllCollectedStats(os);
#ifndef NDEBUG
printArrayCensus(llvh::outs());
#endif
if (trackIO_) {
getIOTrackingInfoJSON(os);
}
}
void Runtime::getIOTrackingInfoJSON(llvh::raw_ostream &os) {
JSONEmitter json(os);
json.openArray();
for (auto &module : getRuntimeModules()) {
auto tracker = module.getBytecode()->getPageAccessTracker();
if (tracker) {
json.openDict();
json.emitKeyValue("url", module.getSourceURL());
json.emitKey("tracking_info");
tracker->getJSONStats(json);
json.closeDict();
}
}
json.closeArray();
}
void Runtime::removeRuntimeModule(RuntimeModule *rm) {
#ifdef HERMES_ENABLE_DEBUGGER
debugger_.willUnloadModule(rm);
#endif
runtimeModuleList_.remove(*rm);
}
#ifndef NDEBUG
void Runtime::printArrayCensus(llvh::raw_ostream &os) {
// Do array capacity histogram.
// Map from array size to number of arrays that are that size.
// Arrays includes ArrayStorage and SegmentedArray.
std::map<std::pair<size_t, size_t>, std::pair<size_t, size_t>>
arraySizeToCountAndWastedSlots;
auto printTable = [&os](const std::map<
std::pair<size_t, size_t>,
std::pair<size_t, size_t>>
&arraySizeToCountAndWastedSlots) {
os << llvh::format(
"%8s %8s %8s %10s %15s %15s %15s %20s %25s\n",
(const char *)"Capacity",
(const char *)"Sizeof",
(const char *)"Count",
(const char *)"Count %",
(const char *)"Cum Count %",
(const char *)"Bytes %",
(const char *)"Cum Bytes %",
(const char *)"Wasted Slots %",
(const char *)"Cum Wasted Slots %");
size_t totalBytes = 0;
size_t totalCount = 0;
size_t totalWastedSlots = 0;
for (const auto &p : arraySizeToCountAndWastedSlots) {
totalBytes += p.first.second * p.second.first;
totalCount += p.second.first;
totalWastedSlots += p.second.second;
}
size_t cumulativeBytes = 0;
size_t cumulativeCount = 0;
size_t cumulativeWastedSlots = 0;
for (const auto &p : arraySizeToCountAndWastedSlots) {
cumulativeBytes += p.first.second * p.second.first;
cumulativeCount += p.second.first;
cumulativeWastedSlots += p.second.second;
os << llvh::format(
"%8d %8d %8d %9.2f%% %14.2f%% %14.2f%% %14.2f%% %19.2f%% %24.2f%%\n",
p.first.first,
p.first.second,
p.second.first,
p.second.first * 100.0 / totalCount,
cumulativeCount * 100.0 / totalCount,
p.first.second * p.second.first * 100.0 / totalBytes,
cumulativeBytes * 100.0 / totalBytes,
totalWastedSlots ? p.second.second * 100.0 / totalWastedSlots : 100.0,
totalWastedSlots ? cumulativeWastedSlots * 100.0 / totalWastedSlots
: 100.0);
}
os << "\n";
};
os << "Array Census for ArrayStorage:\n";
getHeap().forAllObjs([&arraySizeToCountAndWastedSlots](GCCell *cell) {
if (cell->getKind() == CellKind::ArrayStorageKind) {
ArrayStorage *arr = vmcast<ArrayStorage>(cell);
const auto key = std::make_pair(arr->capacity(), arr->getAllocatedSize());
arraySizeToCountAndWastedSlots[key].first++;
arraySizeToCountAndWastedSlots[key].second +=
arr->capacity() - arr->size();
}
});
if (arraySizeToCountAndWastedSlots.empty()) {
os << "\tNo ArrayStorages\n\n";
} else {
printTable(arraySizeToCountAndWastedSlots);
}
os << "Array Census for SegmentedArray:\n";
arraySizeToCountAndWastedSlots.clear();
getHeap().forAllObjs([&arraySizeToCountAndWastedSlots](GCCell *cell) {
if (cell->getKind() == CellKind::SegmentedArrayKind) {
SegmentedArray *arr = vmcast<SegmentedArray>(cell);
const auto key =
std::make_pair(arr->totalCapacityOfSpine(), arr->getAllocatedSize());
arraySizeToCountAndWastedSlots[key].first++;
arraySizeToCountAndWastedSlots[key].second +=
arr->totalCapacityOfSpine() - arr->size();
}
});
if (arraySizeToCountAndWastedSlots.empty()) {
os << "\tNo SegmentedArrays\n\n";
} else {
printTable(arraySizeToCountAndWastedSlots);
}
os << "Array Census for Segment:\n";
arraySizeToCountAndWastedSlots.clear();
getHeap().forAllObjs([&arraySizeToCountAndWastedSlots](GCCell *cell) {
if (cell->getKind() == CellKind::SegmentKind) {
SegmentedArray::Segment *seg = vmcast<SegmentedArray::Segment>(cell);
const auto key = std::make_pair(seg->length(), seg->getAllocatedSize());
arraySizeToCountAndWastedSlots[key].first++;
arraySizeToCountAndWastedSlots[key].second +=
SegmentedArray::Segment::kMaxLength - seg->length();
}
});
if (arraySizeToCountAndWastedSlots.empty()) {
os << "\tNo Segments\n\n";
} else {
printTable(arraySizeToCountAndWastedSlots);
}
os << "Array Census for JSArray:\n";
arraySizeToCountAndWastedSlots.clear();
getHeap().forAllObjs([&arraySizeToCountAndWastedSlots, this](GCCell *cell) {
if (cell->getKind() == CellKind::ArrayKind) {
JSArray *arr = vmcast<JSArray>(cell);
JSArray::StorageType *storage = arr->getIndexedStorage(this);
const auto capacity = storage ? storage->totalCapacityOfSpine() : 0;
const auto sz = storage ? storage->size() : 0;
const auto key = std::make_pair(capacity, arr->getAllocatedSize());
arraySizeToCountAndWastedSlots[key].first++;
arraySizeToCountAndWastedSlots[key].second += capacity - sz;
}
});
if (arraySizeToCountAndWastedSlots.empty()) {
os << "\tNo JSArrays\n\n";
} else {
printTable(arraySizeToCountAndWastedSlots);
}
os << "\n";
}
#endif
unsigned Runtime::getSymbolsEnd() const {
return identifierTable_.getSymbolsEnd();
}
void Runtime::unmarkSymbols() {
identifierTable_.unmarkSymbols();
}
void Runtime::freeSymbols(const llvh::BitVector &markedSymbols) {
identifierTable_.freeUnmarkedSymbols(markedSymbols, getHeap().getIDTracker());
}
#ifdef HERMES_SLOW_DEBUG
bool Runtime::isSymbolLive(SymbolID id) {
return identifierTable_.isSymbolLive(id);
}
const void *Runtime::getStringForSymbol(SymbolID id) {
return identifierTable_.getStringForSymbol(id);
}
#endif
size_t Runtime::mallocSize() const {
// Register stack uses mmap and RuntimeModules are tracked by their owning
// Domains. So this only considers IdentifierTable size.
return sizeof(IdentifierTable) + identifierTable_.additionalMemorySize();
}
#ifdef HERMESVM_SANITIZE_HANDLES
void Runtime::potentiallyMoveHeap() {
// Do a dummy allocation which could force a heap move if handle sanitization
// is on.
FillerCell::create(
this,
std::max<size_t>(
heapAlignSize(sizeof(FillerCell)), GC::minAllocationSize()));
}
#endif
bool Runtime::shouldStabilizeInstructionCount() {
return getCommonStorage()->env &&
getCommonStorage()->env->stabilizeInstructionCount;
}
void Runtime::setMockedEnvironment(const MockedEnvironment &env) {
getCommonStorage()->env = env;
}
LLVM_ATTRIBUTE_NOINLINE
static CallResult<HermesValue> interpretFunctionWithRandomStack(
Runtime *runtime,
CodeBlock *globalCode) {
static void *volatile dummy;
const unsigned amount = std::random_device()() % oscompat::page_size();
// Prevent compiler from optimizing alloca away by assigning to volatile
dummy = alloca(amount);
(void)dummy;
return runtime->interpretFunction(globalCode);
}
CallResult<HermesValue> Runtime::run(
llvh::StringRef code,
llvh::StringRef sourceURL,
const hbc::CompileFlags &compileFlags) {
#ifdef HERMESVM_LEAN
return raiseEvalUnsupported(code);
#else
std::unique_ptr<hermes::Buffer> buffer;
if (compileFlags.lazy) {
buffer.reset(new hermes::OwnedMemoryBuffer(
llvh::MemoryBuffer::getMemBufferCopy(code)));
} else {
buffer.reset(
new hermes::OwnedMemoryBuffer(llvh::MemoryBuffer::getMemBuffer(code)));
}
return run(std::move(buffer), sourceURL, compileFlags);
#endif
}
CallResult<HermesValue> Runtime::run(
std::unique_ptr<hermes::Buffer> code,
llvh::StringRef sourceURL,
const hbc::CompileFlags &compileFlags) {
#ifdef HERMESVM_LEAN
auto buffer = code.get();
return raiseEvalUnsupported(llvh::StringRef(
reinterpret_cast<const char *>(buffer->data()), buffer->size()));
#else
std::unique_ptr<hbc::BCProviderFromSrc> bytecode;
{
PerfSection loading("Loading new JavaScript code");
loading.addArg("url", sourceURL);
auto bytecode_err = hbc::BCProviderFromSrc::createBCProviderFromSrc(
std::move(code), sourceURL, compileFlags);
if (!bytecode_err.first) {
return raiseSyntaxError(TwineChar16(bytecode_err.second));
}
bytecode = std::move(bytecode_err.first);
}
PerfSection loading("Executing global function");
RuntimeModuleFlags rmflags;
rmflags.persistent = true;
return runBytecode(
std::move(bytecode), rmflags, sourceURL, makeNullHandle<Environment>());
#endif
}
CallResult<HermesValue> Runtime::runBytecode(
std::shared_ptr<hbc::BCProvider> &&bytecode,
RuntimeModuleFlags flags,
llvh::StringRef sourceURL,
Handle<Environment> environment,
Handle<> thisArg) {
clearThrownValue();
#ifdef HERMESVM_SERIALIZE
// If we are constructed from serialize data with a ClosureFunction, execute
// the function.
if (!serializeClosure.isUndefined()) {
ScopedNativeCallFrame newFrame{
this,
0,
serializeClosure,
HermesValue::encodeUndefinedValue(),
*thisArg};
if (LLVM_UNLIKELY(newFrame.overflowed()))
return raiseStackOverflow(StackOverflowKind::NativeStack);
return shouldRandomizeMemoryLayout_
? interpretFunctionWithRandomStack(
this, vmcast<JSFunction>(serializeClosure)->getCodeBlock())
: interpretFunction(
vmcast<JSFunction>(serializeClosure)->getCodeBlock());
}
#endif
auto globalFunctionIndex = bytecode->getGlobalFunctionIndex();
if (bytecode->getBytecodeOptions().staticBuiltins && !builtinsFrozen_) {
if (assertBuiltinsUnmodified() == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
freezeBuiltins();
assert(builtinsFrozen_ && "Builtins must be frozen by now.");
}
if (bytecode->getBytecodeOptions().hasAsync && !hasES6Promise_) {
return raiseTypeError(
"Cannot execute a bytecode having async functions when Promise is disabled.");
}
if (flags.persistent) {
persistentBCProviders_.push_back(bytecode);
if (bytecodeWarmupPercent_ > 0) {
// Start the warmup thread for this bytecode if it's a buffer.
bytecode->startWarmup(bytecodeWarmupPercent_);
}
if (getVMExperimentFlags() & experiments::MAdviseRandom) {
bytecode->madvise(oscompat::MAdvice::Random);
} else if (getVMExperimentFlags() & experiments::MAdviseSequential) {
bytecode->madvise(oscompat::MAdvice::Sequential);
}
if (getVMExperimentFlags() & experiments::VerifyBytecodeChecksum) {
llvh::ArrayRef<uint8_t> buf = bytecode->getRawBuffer();
// buf is empty for non-buffer providers
if (!buf.empty()) {
if (!hbc::BCProviderFromBuffer::bytecodeHashIsValid(buf)) {
const char *msg = "Bytecode checksum verification failed";
hermesLog("Hermes", "%s", msg);
hermes_fatal(msg);
}
}
}
}
// Only track I/O for buffers > 64 kB (which excludes things like
// Runtime::generateSpecialRuntimeBytecode).
if (flags.persistent && trackIO_ &&
bytecode->getRawBuffer().size() > MIN_IO_TRACKING_SIZE) {
bytecode->startPageAccessTracker();
if (!bytecode->getPageAccessTracker()) {
hermesLog(
"Hermes",
"Failed to start bytecode I/O instrumentation, "
"maybe not supported on this platform.");
}
}
GCScope scope(this);
Handle<Domain> domain = makeHandle(Domain::create(this));
auto runtimeModuleRes = RuntimeModule::create(
this, domain, nextScriptId_++, std::move(bytecode), flags, sourceURL);
if (LLVM_UNLIKELY(runtimeModuleRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto runtimeModule = *runtimeModuleRes;
auto globalCode = runtimeModule->getCodeBlockMayAllocate(globalFunctionIndex);
#ifdef HERMES_ENABLE_DEBUGGER
// If the debugger is configured to pause on load, give it a chance to pause.
getDebugger().willExecuteModule(runtimeModule, globalCode);
#endif
if (runtimeModule->hasCJSModules()) {
auto requireContext = RequireContext::create(
this, domain, getPredefinedStringHandle(Predefined::dotSlash));
return runRequireCall(
this,
requireContext,
domain,
*domain->getCJSModuleOffset(this, domain->getCJSEntryModuleID()));
} else if (runtimeModule->hasCJSModulesStatic()) {
return runRequireCall(
this,
makeNullHandle<RequireContext>(),
domain,
*domain->getCJSModuleOffset(this, domain->getCJSEntryModuleID()));
} else {
// Create a JSFunction which will reference count the runtime module.
// Note that its handle gets registered in the scope, so we don't need to
// save it. Also note that environment will often be null here, except if