-
Notifications
You must be signed in to change notification settings - Fork 663
/
Copy pathhermes.cpp
2410 lines (2114 loc) · 79.8 KB
/
hermes.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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes.h"
#include "llvh/Support/Compiler.h"
#include "hermes/BCGen/HBC/BytecodeDataProvider.h"
#include "hermes/BCGen/HBC/BytecodeFileFormat.h"
#include "hermes/BCGen/HBC/BytecodeProviderFromSrc.h"
#include "hermes/DebuggerAPI.h"
#include "hermes/Platform/Logging.h"
#include "hermes/Public/JSOutOfMemoryError.h"
#include "hermes/Public/RuntimeConfig.h"
#include "hermes/SourceMap/SourceMapParser.h"
#include "hermes/Support/SimpleDiagHandler.h"
#include "hermes/Support/UTF16Stream.h"
#include "hermes/Support/UTF8.h"
#include "hermes/VM/CallResult.h"
#include "hermes/VM/Debugger/Debugger.h"
#include "hermes/VM/GC.h"
#include "hermes/VM/HostModel.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSArrayBuffer.h"
#include "hermes/VM/JSLib.h"
#include "hermes/VM/JSLib/RuntimeCommonStorage.h"
#include "hermes/VM/JSLib/RuntimeJSONUtils.h"
#include "hermes/VM/NativeState.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/Profiler/CodeCoverageProfiler.h"
#include "hermes/VM/Profiler/SamplingProfiler.h"
#include "hermes/VM/Runtime.h"
#include "hermes/VM/StringPrimitive.h"
#include "hermes/VM/StringView.h"
#include "hermes/VM/SymbolID.h"
#include "hermes/VM/TimeLimitMonitor.h"
#include "hermes/VM/WeakRoot-inline.h"
#include "llvh/Support/ErrorHandling.h"
#include "llvh/Support/FileSystem.h"
#include "llvh/Support/SHA1.h"
#include "llvh/Support/raw_os_ostream.h"
#include <algorithm>
#include <atomic>
#include <limits>
#include <list>
#include <mutex>
#include <system_error>
#include <unordered_map>
#include <jsi/instrumentation.h>
#include <jsi/threadsafe.h>
#ifdef HERMESVM_LLVM_PROFILE_DUMP
extern "C" {
int __llvm_profile_dump(void);
}
#endif
// Android OSS has a bug where exception data can get mangled when going via
// fbjni. This macro can be used to expose the root cause in adb log. It serves
// no purpose other than as a backup.
#ifdef __ANDROID__
#define LOG_EXCEPTION_CAUSE(...) hermesLog("HermesVM", __VA_ARGS__)
#else
#define LOG_EXCEPTION_CAUSE(...) \
do { \
} while (0)
#endif
namespace vm = hermes::vm;
namespace hbc = hermes::hbc;
using ::hermes::hermesLog;
namespace facebook {
namespace hermes {
namespace detail {
#if !defined(NDEBUG) && !defined(ASSERT_ON_DANGLING_VM_REFS)
#define ASSERT_ON_DANGLING_VM_REFS
#endif
static void (*sApiFatalHandler)(const std::string &) = nullptr;
/// Handler called by HermesVM to report unrecoverable errors.
/// This is a forward declaration to prevent a compiler warning.
void hermesFatalErrorHandler(
void *user_data,
const std::string &reason,
bool gen_crash_diag);
void hermesFatalErrorHandler(
void * /*user_data*/,
const std::string &reason,
bool /*gen_crash_diag*/) {
// Actually crash and let breakpad handle the reporting.
if (sApiFatalHandler) {
sApiFatalHandler(reason);
} else {
*((volatile int *)nullptr) = 42;
}
}
} // namespace detail
namespace {
// Max size of the runtime's register stack.
// The runtime register stack needs to be small enough to be allocated on the
// native thread stack in Android (1MiB) and on MacOS's thread stack (512 KiB)
// Calculated by: (thread stack size - size of runtime -
// 8 memory pages for other stuff in the thread)
static constexpr unsigned kMaxNumRegisters =
(512 * 1024 - sizeof(::hermes::vm::Runtime) - 4096 * 8) /
sizeof(::hermes::vm::PinnedHermesValue);
void raw_ostream_append(llvh::raw_ostream &os) {}
template <typename Arg0, typename... Args>
void raw_ostream_append(llvh::raw_ostream &os, Arg0 &&arg0, Args &&...args) {
os << arg0;
raw_ostream_append(os, args...);
}
template <typename... Args>
jsi::JSError makeJSError(jsi::Runtime &rt, Args &&...args) {
std::string s;
llvh::raw_string_ostream os(s);
raw_ostream_append(os, std::forward<Args>(args)...);
LOG_EXCEPTION_CAUSE("JSError: %s", os.str().c_str());
return jsi::JSError(rt, os.str());
}
/// HermesVM uses the LLVM fatal error handle to report fatal errors. This
/// wrapper helps us install the handler at construction time, before any
/// HermesVM code has been invoked.
class InstallHermesFatalErrorHandler {
public:
InstallHermesFatalErrorHandler() {
// The LLVM fatal error handler can only be installed once. Use a Meyer's
// singleton to guarantee it - the static "dummy" is guaranteed by the
// compiler to be initialized no more than once.
static int dummy = ([]() {
llvh::install_fatal_error_handler(detail::hermesFatalErrorHandler);
return 0;
})();
(void)dummy;
}
};
} // namespace
class HermesRuntimeImpl final : public HermesRuntime,
private InstallHermesFatalErrorHandler,
private jsi::Instrumentation {
public:
static constexpr uint32_t kSentinelNativeValue = 0x6ef71fe1;
HermesRuntimeImpl(const vm::RuntimeConfig &runtimeConfig)
: hermesValues_(runtimeConfig.getGCConfig().getOccupancyTarget()),
weakHermesValues_(runtimeConfig.getGCConfig().getOccupancyTarget()),
rt_(::hermes::vm::Runtime::create(
runtimeConfig.rebuild()
.withRegisterStack(nullptr)
.withMaxNumRegisters(kMaxNumRegisters)
.build())),
runtime_(*rt_),
vmExperimentFlags_(runtimeConfig.getVMExperimentFlags()) {
#ifdef HERMES_ENABLE_DEBUGGER
compileFlags_.debug = true;
#endif
switch (runtimeConfig.getCompilationMode()) {
case vm::SmartCompilation:
compileFlags_.lazy = true;
// (Leaves thresholds at default values)
break;
case vm::ForceEagerCompilation:
compileFlags_.lazy = false;
break;
case vm::ForceLazyCompilation:
compileFlags_.lazy = true;
compileFlags_.preemptiveFileCompilationThreshold = 0;
compileFlags_.preemptiveFunctionCompilationThreshold = 0;
break;
}
compileFlags_.enableGenerator = runtimeConfig.getEnableGenerator();
compileFlags_.emitAsyncBreakCheck = defaultEmitAsyncBreakCheck_ =
runtimeConfig.getAsyncBreakCheckInEval();
runtime_.addCustomRootsFunction(
[this](vm::GC *, vm::RootAcceptor &acceptor) {
for (auto &val : hermesValues_)
if (val.get() > 0)
acceptor.accept(const_cast<vm::PinnedHermesValue &>(val.phv));
});
runtime_.addCustomWeakRootsFunction(
[this](vm::GC *, vm::WeakRootAcceptor &acceptor) {
for (auto &val : weakHermesValues_)
if (val.get() > 0)
acceptor.acceptWeak(val.wr);
});
#ifdef HERMES_MEMORY_INSTRUMENTATION
runtime_.addCustomSnapshotFunction(
[this](vm::HeapSnapshot &snap) {
snap.beginNode();
snap.endNode(
vm::HeapSnapshot::NodeType::Native,
"ManagedValues",
vm::GCBase::IDTracker::reserved(
vm::GCBase::IDTracker::ReservedObjectID::JSIHermesValueList),
hermesValues_.size() * sizeof(HermesPointerValue),
0);
snap.beginNode();
snap.endNode(
vm::HeapSnapshot::NodeType::Native,
"ManagedValues",
vm::GCBase::IDTracker::reserved(
vm::GCBase::IDTracker::ReservedObjectID::
JSIWeakHermesValueList),
weakHermesValues_.size() * sizeof(WeakRefPointerValue),
0);
},
[](vm::HeapSnapshot &snap) {
snap.addNamedEdge(
vm::HeapSnapshot::EdgeType::Internal,
"hermesValues",
vm::GCBase::IDTracker::reserved(
vm::GCBase::IDTracker::ReservedObjectID::JSIHermesValueList));
snap.addNamedEdge(
vm::HeapSnapshot::EdgeType::Internal,
"weakHermesValues",
vm::GCBase::IDTracker::reserved(
vm::GCBase::IDTracker::ReservedObjectID::
JSIWeakHermesValueList));
});
#endif // HERMES_MEMORY_INSTRUMENTATION
}
public:
~HermesRuntimeImpl() override {
#ifdef HERMES_ENABLE_DEBUGGER
// Deallocate the debugger so it frees any HermesPointerValues it may hold.
// This must be done before we check hermesValues_ below.
debugger_.reset();
#endif
}
#ifdef HERMES_ENABLE_DEBUGGER
// This should only be called once by the factory.
void setDebugger(std::unique_ptr<debugger::Debugger> d) {
debugger_ = std::move(d);
}
#endif
struct CountedPointerValue : PointerValue {
CountedPointerValue() : refCount(1) {}
void invalidate() override {
#ifdef ASSERT_ON_DANGLING_VM_REFS
assert(
((1 << 31) & refCount) == 0 &&
"This PointerValue was left dangling after the Runtime was destroyed.");
#endif
dec();
}
void inc() {
// It is always safe to use relaxed operations for incrementing the
// reference count, because the only operation that may occur concurrently
// with it is decrementing the reference count, and we do not need to
// enforce any ordering between the two.
auto oldCount = refCount.fetch_add(1, std::memory_order_relaxed);
assert(oldCount && "Cannot resurrect a pointer");
assert(oldCount + 1 != 0 && "Ref count overflow");
(void)oldCount;
}
void dec() {
// It is safe to use relaxed operations here because decrementing the
// reference count is the only access that may be performed without proper
// synchronisation. As a result, the only ordering we need to enforce when
// decrementing is that the vtable pointer used to call \c invalidate is
// loaded from before the decrement, in case the decrement ends up causing
// this value to be freed. We get this ordering from the fact that the
// vtable read and the reference count update form a load-store control
// dependency, which preserves their ordering on any reasonable hardware.
auto oldCount = refCount.fetch_sub(1, std::memory_order_relaxed);
assert(oldCount > 0 && "Ref count underflow");
(void)oldCount;
}
uint32_t get() const {
return refCount.load(std::memory_order_relaxed);
}
#ifdef ASSERT_ON_DANGLING_VM_REFS
void markDangling() {
// Mark this PointerValue as dangling by setting the top bit AND the
// second-top bit. The top bit is used to determine if the pointer is
// dangling. Setting the second-top bit ensures that accidental
// over-calling the dec() function doesn't clear the top bit without
// complicating the implementation of dec().
refCount |= 0b11 << 30;
}
#endif
private:
std::atomic<uint32_t> refCount;
};
struct HermesPointerValue final : CountedPointerValue {
HermesPointerValue(vm::HermesValue hv) : phv(hv) {}
// This should only ever be modified by the GC. We const_cast the
// reference before passing it to the GC.
const vm::PinnedHermesValue phv;
};
struct WeakRefPointerValue final : CountedPointerValue {
WeakRefPointerValue(vm::WeakRoot<vm::JSObject> _wr) : wr(_wr) {}
vm::WeakRoot<vm::JSObject> wr;
};
HermesPointerValue *clone(const Runtime::PointerValue *pv) {
if (!pv) {
return nullptr;
}
// These are only ever allocated by us, so we can remove their constness
auto result = static_cast<HermesPointerValue *>(
const_cast<Runtime::PointerValue *>(pv));
result->inc();
return result;
}
template <typename T>
T add(::hermes::vm::HermesValue hv) {
static_assert(
std::is_base_of<jsi::Pointer, T>::value, "this type cannot be added");
return make<T>(&hermesValues_.add(hv));
}
jsi::WeakObject addWeak(::hermes::vm::WeakRoot<vm::JSObject> wr) {
return make<jsi::WeakObject>(&weakHermesValues_.add(wr));
}
// overriden from jsi::Instrumentation
std::string getRecordedGCStats() override {
std::string s;
llvh::raw_string_ostream os(s);
runtime_.printHeapStats(os);
return os.str();
}
// Overridden from jsi::Instrumentation
// See include/hermes/VM/GCBase.h for documentation of the fields
std::unordered_map<std::string, int64_t> getHeapInfo(
bool includeExpensive) override {
vm::GCBase::HeapInfo info;
if (includeExpensive) {
runtime_.getHeap().getHeapInfoWithMallocSize(info);
} else {
runtime_.getHeap().getHeapInfo(info);
}
#ifndef NDEBUG
vm::GCBase::DebugHeapInfo debugInfo;
runtime_.getHeap().getDebugHeapInfo(debugInfo);
#endif
std::unordered_map<std::string, int64_t> jsInfo;
#define BRIDGE_INFO(TYPE, HOLDER, NAME) \
jsInfo["hermes_" #NAME] = static_cast<TYPE>(HOLDER.NAME);
BRIDGE_INFO(int, info, numCollections);
BRIDGE_INFO(double, info, totalAllocatedBytes);
BRIDGE_INFO(double, info, allocatedBytes);
BRIDGE_INFO(double, info, heapSize);
BRIDGE_INFO(double, info, va);
BRIDGE_INFO(double, info, externalBytes);
BRIDGE_INFO(int, info, numMarkStackOverflows);
if (includeExpensive) {
BRIDGE_INFO(double, info, mallocSizeEstimate);
}
#ifndef NDEBUG
BRIDGE_INFO(int, debugInfo, numAllocatedObjects);
BRIDGE_INFO(int, debugInfo, numReachableObjects);
BRIDGE_INFO(int, debugInfo, numCollectedObjects);
BRIDGE_INFO(int, debugInfo, numFinalizedObjects);
BRIDGE_INFO(int, debugInfo, numMarkedSymbols);
BRIDGE_INFO(int, debugInfo, numHiddenClasses);
BRIDGE_INFO(int, debugInfo, numLeafHiddenClasses);
#endif
#undef BRIDGE_INFO
jsInfo["hermes_peakAllocatedBytes"] =
runtime_.getHeap().getPeakAllocatedBytes();
jsInfo["hermes_peakLiveAfterGC"] = runtime_.getHeap().getPeakLiveAfterGC();
#define BRIDGE_GEN_INFO(NAME, STAT_EXPR, FACTOR) \
jsInfo["hermes_full_" #NAME] = info.fullStats.STAT_EXPR * FACTOR; \
jsInfo["hermes_yg_" #NAME] = info.youngGenStats.STAT_EXPR * FACTOR;
BRIDGE_GEN_INFO(numCollections, numCollections, 1.0);
// Times are converted from seconds to milliseconds for the logging pipeline
// ...
BRIDGE_GEN_INFO(gcTime, gcWallTime.sum(), 1000);
BRIDGE_GEN_INFO(maxPause, gcWallTime.max(), 1000);
BRIDGE_GEN_INFO(gcCPUTime, gcCPUTime.sum(), 1000);
BRIDGE_GEN_INFO(gcMaxCPUPause, gcCPUTime.max(), 1000);
// ... and since this is square seconds, we must square the 1000 too.
BRIDGE_GEN_INFO(gcTimeSquares, gcWallTime.sumOfSquares(), 1000 * 1000);
BRIDGE_GEN_INFO(gcCPUTimeSquares, gcCPUTime.sumOfSquares(), 1000 * 1000);
#undef BRIDGE_GEN_INFO
return jsInfo;
}
// Overridden from jsi::Instrumentation
void collectGarbage(std::string cause) override {
if ((vmExperimentFlags_ & vm::experiments::IgnoreMemoryWarnings) &&
cause == "TRIM_MEMORY_RUNNING_CRITICAL") {
// Do nothing if the GC is a memory warning.
// TODO(T79835917): Remove this after proving this is the cause of OOMs
// and finding a better resolution.
return;
}
runtime_.collect(std::move(cause));
}
// Overridden from jsi::Instrumentation
void startTrackingHeapObjectStackTraces(
std::function<void(
uint64_t,
std::chrono::microseconds,
std::vector<HeapStatsUpdate>)> fragmentCallback) override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
runtime_.enableAllocationLocationTracker(std::move(fragmentCallback));
#else
throw std::logic_error(
"Cannot track heap object stack traces if Hermes isn't "
"built with memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
void stopTrackingHeapObjectStackTraces() override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
runtime_.disableAllocationLocationTracker();
#else
throw std::logic_error(
"Cannot track heap object stack traces if Hermes isn't "
"built with memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
void startHeapSampling(size_t samplingInterval) override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
runtime_.enableSamplingHeapProfiler(samplingInterval);
#else
throw std::logic_error(
"Cannot perform heap sampling if Hermes isn't built with "
"memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
void stopHeapSampling(std::ostream &os) override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
llvh::raw_os_ostream ros(os);
runtime_.disableSamplingHeapProfiler(ros);
#else
throw std::logic_error(
"Cannot perform heap sampling if Hermes isn't built with "
" memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
void createSnapshotToFile(const std::string &path) override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
std::error_code code;
llvh::raw_fd_ostream os(path, code, llvh::sys::fs::FileAccess::FA_Write);
if (code) {
throw std::system_error(code);
}
runtime_.getHeap().createSnapshot(os);
#else
throw std::logic_error(
"Cannot create heap snapshots if Hermes isn't built with "
"memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
void createSnapshotToStream(std::ostream &os) override {
#ifdef HERMES_MEMORY_INSTRUMENTATION
llvh::raw_os_ostream ros(os);
runtime_.getHeap().createSnapshot(ros);
#else
throw std::logic_error(
"Cannot create heap snapshots if Hermes isn't built with "
"memory instrumentation.");
#endif
}
// Overridden from jsi::Instrumentation
std::string flushAndDisableBridgeTrafficTrace() override {
throw std::logic_error(
"Bridge traffic trace is only supported by TracingRuntime");
}
// Overridden from jsi::Instrumentation
void writeBasicBlockProfileTraceToFile(
const std::string &fileName) const override {
#ifdef HERMESVM_PROFILER_BB
std::error_code ec;
llvh::raw_fd_ostream os(fileName.c_str(), ec, llvh::sys::fs::F_Text);
if (ec) {
throw std::system_error(ec);
}
runtime_.dumpBasicBlockProfileTrace(os);
#else
throw std::logic_error(
"Cannot write the basic block profile trace out if Hermes wasn't built with "
"hermes.profiler=BB");
#endif
}
void dumpProfilerSymbolsToFile(const std::string &fileName) const override {
throw std::logic_error(
"Cannot dump profiler symbols out if Hermes wasn't built with "
"hermes.profiler=EXTERN");
}
// These are all methods which do pointer type gymnastics and should
// mostly inline and optimize away.
static const ::hermes::vm::PinnedHermesValue &phv(
const jsi::Pointer &pointer) {
assert(
dynamic_cast<const HermesPointerValue *>(getPointerValue(pointer)) &&
"Pointer does not contain a HermesPointerValue");
return static_cast<const HermesPointerValue *>(getPointerValue(pointer))
->phv;
}
static const ::hermes::vm::PinnedHermesValue &phv(const jsi::Value &value) {
assert(
dynamic_cast<const HermesPointerValue *>(getPointerValue(value)) &&
"Pointer does not contain a HermesPointerValue");
return static_cast<const HermesPointerValue *>(getPointerValue(value))->phv;
}
static ::hermes::vm::Handle<::hermes::vm::HermesValue> stringHandle(
const jsi::String &str) {
return ::hermes::vm::Handle<::hermes::vm::HermesValue>::vmcast(&phv(str));
}
static ::hermes::vm::Handle<::hermes::vm::JSObject> handle(
const jsi::Object &obj) {
return ::hermes::vm::Handle<::hermes::vm::JSObject>::vmcast(&phv(obj));
}
static ::hermes::vm::Handle<::hermes::vm::JSArray> arrayHandle(
const jsi::Array &arr) {
return ::hermes::vm::Handle<::hermes::vm::JSArray>::vmcast(&phv(arr));
}
static ::hermes::vm::Handle<::hermes::vm::JSArrayBuffer> arrayBufferHandle(
const jsi::ArrayBuffer &arr) {
return ::hermes::vm::Handle<::hermes::vm::JSArrayBuffer>::vmcast(&phv(arr));
}
static ::hermes::vm::WeakRoot<vm::JSObject> &weakRoot(jsi::Pointer &pointer) {
assert(
dynamic_cast<WeakRefPointerValue *>(getPointerValue(pointer)) &&
"Pointer does not contain a WeakRefPointerValue");
return static_cast<WeakRefPointerValue *>(getPointerValue(pointer))->wr;
}
// These helpers use public (mostly) interfaces on the runtime and
// value types to convert between jsi and vm types.
static vm::HermesValue hvFromValue(const jsi::Value &value) {
if (value.isUndefined()) {
return vm::HermesValue::encodeUndefinedValue();
} else if (value.isNull()) {
return vm::HermesValue::encodeNullValue();
} else if (value.isBool()) {
return vm::HermesValue::encodeBoolValue(value.getBool());
} else if (value.isNumber()) {
return vm::HermesValue::encodeUntrustedDoubleValue(value.getNumber());
} else if (
value.isSymbol() || value.isBigInt() || value.isString() ||
value.isObject()) {
return phv(value);
} else {
llvm_unreachable("unknown value kind");
}
}
vm::Handle<> vmHandleFromValue(const jsi::Value &value) {
if (value.isUndefined()) {
return vm::Runtime::getUndefinedValue();
} else if (value.isNull()) {
return vm::Runtime::getNullValue();
} else if (value.isBool()) {
return vm::Runtime::getBoolValue(value.getBool());
} else if (value.isNumber()) {
return runtime_.makeHandle(
vm::HermesValue::encodeUntrustedDoubleValue(value.getNumber()));
} else if (
value.isSymbol() || value.isBigInt() || value.isString() ||
value.isObject()) {
return vm::Handle<vm::HermesValue>(&phv(value));
} else {
llvm_unreachable("unknown value kind");
}
}
jsi::Value valueFromHermesValue(vm::HermesValue hv) {
if (hv.isUndefined() || hv.isEmpty()) {
return jsi::Value::undefined();
} else if (hv.isNull()) {
return nullptr;
} else if (hv.isBool()) {
return hv.getBool();
} else if (hv.isDouble()) {
return hv.getDouble();
} else if (hv.isSymbol()) {
return add<jsi::Symbol>(hv);
} else if (hv.isBigInt()) {
return add<jsi::BigInt>(hv);
} else if (hv.isString()) {
return add<jsi::String>(hv);
} else if (hv.isObject()) {
return add<jsi::Object>(hv);
} else {
llvm_unreachable("unknown HermesValue type");
}
}
/// Same as \c prepareJavaScript but with a source map.
std::shared_ptr<const jsi::PreparedJavaScript> prepareJavaScriptWithSourceMap(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::shared_ptr<const jsi::Buffer> &sourceMapBuf,
std::string sourceURL);
// Concrete declarations of jsi::Runtime pure virtual methods
std::shared_ptr<const jsi::PreparedJavaScript> prepareJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
std::string sourceURL) override;
jsi::Value evaluatePreparedJavaScript(
const std::shared_ptr<const jsi::PreparedJavaScript> &js) override;
jsi::Value evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string &sourceURL) override;
bool drainMicrotasks(int maxMicrotasksHint = -1) override;
jsi::Object global() override;
std::string description() override;
bool isInspectable() override;
jsi::Instrumentation &instrumentation() override;
PointerValue *cloneSymbol(const Runtime::PointerValue *pv) override;
PointerValue *cloneBigInt(const Runtime::PointerValue *pv) override;
PointerValue *cloneString(const Runtime::PointerValue *pv) override;
PointerValue *cloneObject(const Runtime::PointerValue *pv) override;
PointerValue *clonePropNameID(const Runtime::PointerValue *pv) override;
jsi::PropNameID createPropNameIDFromAscii(const char *str, size_t length)
override;
jsi::PropNameID createPropNameIDFromUtf8(const uint8_t *utf8, size_t length)
override;
jsi::PropNameID createPropNameIDFromString(const jsi::String &str) override;
jsi::PropNameID createPropNameIDFromSymbol(const jsi::Symbol &sym) override;
std::string utf8(const jsi::PropNameID &) override;
bool compare(const jsi::PropNameID &, const jsi::PropNameID &) override;
std::string symbolToString(const jsi::Symbol &) override;
jsi::BigInt createBigIntFromInt64(int64_t) override;
jsi::BigInt createBigIntFromUint64(uint64_t) override;
bool bigintIsInt64(const jsi::BigInt &) override;
bool bigintIsUint64(const jsi::BigInt &) override;
uint64_t truncate(const jsi::BigInt &) override;
jsi::String bigintToString(const jsi::BigInt &, int) override;
jsi::String createStringFromAscii(const char *str, size_t length) override;
jsi::String createStringFromUtf8(const uint8_t *utf8, size_t length) override;
std::string utf8(const jsi::String &) override;
jsi::Value createValueFromJsonUtf8(const uint8_t *json, size_t length)
override;
jsi::Object createObject() override;
jsi::Object createObject(std::shared_ptr<jsi::HostObject> ho) override;
std::shared_ptr<jsi::HostObject> getHostObject(const jsi::Object &) override;
jsi::HostFunctionType &getHostFunction(const jsi::Function &) override;
bool hasNativeState(const jsi::Object &) override;
std::shared_ptr<jsi::NativeState> getNativeState(
const jsi::Object &) override;
void setNativeState(const jsi::Object &, std::shared_ptr<jsi::NativeState>)
override;
jsi::Value getProperty(const jsi::Object &, const jsi::PropNameID &name)
override;
jsi::Value getProperty(const jsi::Object &, const jsi::String &name) override;
bool hasProperty(const jsi::Object &, const jsi::PropNameID &name) override;
bool hasProperty(const jsi::Object &, const jsi::String &name) override;
void setPropertyValue(
jsi::Object &,
const jsi::PropNameID &name,
const jsi::Value &value) override;
void setPropertyValue(
jsi::Object &,
const jsi::String &name,
const jsi::Value &value) override;
bool isArray(const jsi::Object &) const override;
bool isArrayBuffer(const jsi::Object &) const override;
bool isFunction(const jsi::Object &) const override;
bool isHostObject(const jsi::Object &) const override;
bool isHostFunction(const jsi::Function &) const override;
jsi::Array getPropertyNames(const jsi::Object &) override;
jsi::WeakObject createWeakObject(const jsi::Object &) override;
jsi::Value lockWeakObject(jsi::WeakObject &) override;
jsi::Array createArray(size_t length) override;
size_t size(const jsi::Array &) override;
size_t size(const jsi::ArrayBuffer &) override;
uint8_t *data(const jsi::ArrayBuffer &) override;
jsi::Value getValueAtIndex(const jsi::Array &, size_t i) override;
void setValueAtIndexImpl(jsi::Array &, size_t i, const jsi::Value &value)
override;
jsi::Function createFunctionFromHostFunction(
const jsi::PropNameID &name,
unsigned int paramCount,
jsi::HostFunctionType func) override;
jsi::Value call(
const jsi::Function &,
const jsi::Value &jsThis,
const jsi::Value *args,
size_t count) override;
jsi::Value callAsConstructor(
const jsi::Function &,
const jsi::Value *args,
size_t count) override;
bool strictEquals(const jsi::Symbol &a, const jsi::Symbol &b) const override;
bool strictEquals(const jsi::BigInt &a, const jsi::BigInt &b) const override;
bool strictEquals(const jsi::String &a, const jsi::String &b) const override;
bool strictEquals(const jsi::Object &a, const jsi::Object &b) const override;
bool instanceOf(const jsi::Object &o, const jsi::Function &ctor) override;
ScopeState *pushScope() override;
void popScope(ScopeState *prv) override;
void checkStatus(vm::ExecutionStatus);
vm::HermesValue stringHVFromAscii(const char *ascii, size_t length);
vm::HermesValue stringHVFromUtf8(const uint8_t *utf8, size_t length);
size_t getLength(vm::Handle<vm::ArrayImpl> arr);
size_t getByteLength(vm::Handle<vm::JSArrayBuffer> arr);
struct JsiProxy final : public vm::HostObjectProxy {
HermesRuntimeImpl &rt_;
std::shared_ptr<jsi::HostObject> ho_;
JsiProxy(HermesRuntimeImpl &rt, std::shared_ptr<jsi::HostObject> ho)
: rt_(rt), ho_(ho) {}
vm::CallResult<vm::HermesValue> get(vm::SymbolID id) override {
jsi::PropNameID sym =
rt_.add<jsi::PropNameID>(vm::HermesValue::encodeSymbolValue(id));
jsi::Value ret;
try {
ret = ho_->get(rt_, sym);
}
#ifdef HERMESVM_EXCEPTION_ON_OOM
catch (const vm::JSOutOfMemoryError &) {
throw;
}
#endif
catch (const jsi::JSError &error) {
return rt_.runtime_.setThrownValue(hvFromValue(error.value()));
} catch (const std::exception &ex) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
"Exception in HostObject::get for prop '" +
rt_.runtime_.getIdentifierTable().convertSymbolToUTF8(
id) +
"': " + ex.what())));
} catch (...) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
"Exception in HostObject::get: for prop '" +
rt_.runtime_.getIdentifierTable().convertSymbolToUTF8(
id) +
"': <unknown exception>")));
}
return hvFromValue(ret);
}
vm::CallResult<bool> set(vm::SymbolID id, vm::HermesValue value) override {
jsi::PropNameID sym =
rt_.add<jsi::PropNameID>(vm::HermesValue::encodeSymbolValue(id));
try {
ho_->set(rt_, sym, rt_.valueFromHermesValue(value));
}
#ifdef HERMESVM_EXCEPTION_ON_OOM
catch (const vm::JSOutOfMemoryError &) {
throw;
}
#endif
catch (const jsi::JSError &error) {
return rt_.runtime_.setThrownValue(hvFromValue(error.value()));
} catch (const std::exception &ex) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
"Exception in HostObject::set for prop '" +
rt_.runtime_.getIdentifierTable().convertSymbolToUTF8(
id) +
"': " + ex.what())));
} catch (...) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
"Exception in HostObject::set: for prop '" +
rt_.runtime_.getIdentifierTable().convertSymbolToUTF8(
id) +
"': <unknown exception>")));
}
return true;
}
vm::CallResult<vm::Handle<vm::JSArray>> getHostPropertyNames() override {
try {
auto names = ho_->getPropertyNames(rt_);
auto arrayRes =
vm::JSArray::create(rt_.runtime_, names.size(), names.size());
if (arrayRes == vm::ExecutionStatus::EXCEPTION) {
return vm::ExecutionStatus::EXCEPTION;
}
vm::Handle<vm::JSArray> arrayHandle = *arrayRes;
vm::GCScope gcScope{rt_.runtime_};
vm::MutableHandle<vm::SymbolID> tmpHandle{rt_.runtime_};
size_t i = 0;
for (auto &name : names) {
tmpHandle = phv(name).getSymbol();
vm::JSArray::setElementAt(arrayHandle, rt_.runtime_, i++, tmpHandle);
}
return arrayHandle;
}
#ifdef HERMESVM_EXCEPTION_ON_OOM
catch (const vm::JSOutOfMemoryError &) {
throw;
}
#endif
catch (const jsi::JSError &error) {
return rt_.runtime_.setThrownValue(hvFromValue(error.value()));
} catch (const std::exception &ex) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
std::string("Exception in HostObject::getPropertyNames: ") +
ex.what())));
} catch (...) {
return rt_.runtime_.setThrownValue(hvFromValue(
rt_.global()
.getPropertyAsFunction(rt_, "Error")
.call(
rt_,
"Exception in HostObject::getPropertyNames: <unknown>")));
}
};
};
struct HFContext final {
HFContext(jsi::HostFunctionType hf, HermesRuntimeImpl &hri)
: hostFunction(std::move(hf)), hermesRuntimeImpl(hri) {}
static vm::CallResult<vm::HermesValue>
func(void *context, vm::Runtime &runtime, vm::NativeArgs hvArgs) {
HFContext *hfc = reinterpret_cast<HFContext *>(context);
HermesRuntimeImpl &rt = hfc->hermesRuntimeImpl;
assert(&runtime == &rt.runtime_);
llvh::SmallVector<jsi::Value, 8> apiArgs;
for (vm::HermesValue hv : hvArgs) {
apiArgs.push_back(rt.valueFromHermesValue(hv));
}
jsi::Value ret;
const jsi::Value *args = apiArgs.empty() ? nullptr : &apiArgs.front();
try {
ret = (hfc->hostFunction)(
rt,
rt.valueFromHermesValue(hvArgs.getThisArg()),
args,
apiArgs.size());
}
#ifdef HERMESVM_EXCEPTION_ON_OOM
catch (const vm::JSOutOfMemoryError &) {
throw;
}
#endif
catch (const jsi::JSError &error) {
return runtime.setThrownValue(hvFromValue(error.value()));
} catch (const std::exception &ex) {
return rt.runtime_.setThrownValue(hvFromValue(
rt.global()
.getPropertyAsFunction(rt, "Error")
.call(
rt,
std::string("Exception in HostFunction: ") + ex.what())));
} catch (...) {
return rt.runtime_.setThrownValue(
hvFromValue(rt.global()
.getPropertyAsFunction(rt, "Error")
.call(rt, "Exception in HostFunction: <unknown>")));
}
return hvFromValue(ret);
}
static void finalize(void *context) {
delete reinterpret_cast<HFContext *>(context);
}
jsi::HostFunctionType hostFunction;
HermesRuntimeImpl &hermesRuntimeImpl;
};
template <typename T>
class ManagedValues {
public:
using iterator = typename std::list<T>::iterator;
template <typename... Args>
T &add(Args &&...args) {
// If the size has hit the target size, collect unused values.
if (LLVM_UNLIKELY(size() >= targetSize_))
collect();
values_.emplace_front(std::forward<Args>(args)...);
return values_.front();
}
iterator begin() {
return values_.begin();
}
iterator end() {
return values_.end();
}
iterator erase(iterator it) {
return values_.erase(it);
}
iterator eraseIfExpired(iterator it) {
auto next = std::next(it);
if (it->get() == 0) {
// TSAN will complain here because the value is being freed without any
// explicit synchronisation with a background thread that may have just
// updated the reference count (and read the vtable in the process).
// However, this can be safely ignored because the check above creates a
// load-store control dependency, and the free below therefore cannot be
// reordered before the check on the reference count.
TsanIgnoreWritesBegin();
values_.erase(it);
TsanIgnoreWritesEnd();
}
return next;