-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathNodeApiJsiRuntime.cpp
More file actions
3531 lines (3098 loc) · 120 KB
/
Copy pathNodeApiJsiRuntime.cpp
File metadata and controls
3531 lines (3098 loc) · 120 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) Microsoft Corporation.
// Licensed under the MIT License.
#define NAPI_EXPERIMENTAL
#include "NodeApiJsiRuntime.h"
#include <algorithm>
#include <array>
#include <mutex>
#include <optional>
#include <sstream>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
// JSI version defines set of features available in the API.
// Each significant API change must be under a new version.
// These macros must be defined in jsi.h, but define them here too
// in case if this code is used with unmodified jsi.h.
#ifndef JSI_VERSION
#define JSI_VERSION 10
#endif
#ifndef JSI_NO_CONST_3
#if JSI_VERSION >= 3
#define JSI_NO_CONST_3
#else
#define JSI_NO_CONST_3 const
#endif
#endif
#ifndef JSI_CONST_10
#if JSI_VERSION >= 10
#define JSI_CONST_10 const
#else
#define JSI_CONST_10
#endif
#endif
using namespace facebook;
using namespace std::string_view_literals;
// We use macros to report errors.
// Macros provide more flexibility to show assert and provide failure context.
// Check condition and crash process if it fails.
#define CHECK_ELSE_CRASH(condition, message) \
do { \
if (!(condition)) { \
assert(false && "Failed: " #condition && (message)); \
*((int *)0) = 1; \
} \
} while (false)
// Check condition and throw native exception if it fails.
#define CHECK_ELSE_THROW(condition, message) \
do { \
if (!(condition)) { \
throwNativeException(message); \
} \
} while (false)
// Check Node-API result and and throw JS exception if it is not napi_ok.
#define CHECK_NAPI(...) \
do { \
napi_status temp_error_code_ = (__VA_ARGS__); \
if (temp_error_code_ != napi_status::napi_ok) { \
runtime.throwJSException(temp_error_code_); \
} \
} while (false)
// Check Node-API result and and crash if it is not napi_ok.
#define CHECK_NAPI_ELSE_CRASH(expression) \
do { \
napi_status temp_error_code_ = (expression); \
if (temp_error_code_ != napi_status::napi_ok) { \
CHECK_ELSE_CRASH(false, "Failed: " #expression); \
} \
} while (false)
// Check Node-API result and return it when it is an error.
#define NAPI_CALL(expression) \
do { \
napi_status temp_error_code_ = (expression); \
if (temp_error_code_ != napi_status::napi_ok) { \
return temp_error_code_; \
} \
} while (false)
#ifdef __cpp_lib_span
#include <span>
#endif // __cpp_lib_span
namespace Microsoft::NodeApiJsi {
namespace {
#ifdef __cpp_lib_span
using std::span;
#else
/**
* @brief A span of values that can be used to pass arguments to a function.
*
* This should be replaced with std::span once C++20 is supported.
*/
template <typename T>
class span {
public:
constexpr span() noexcept : data_{nullptr}, size_{0} {}
constexpr span(T *data, size_t size) noexcept : data_{data}, size_{size} {}
template <std::size_t N>
constexpr span(T (&arr)[N]) noexcept : data_{arr}, size_{N} {}
[[nodiscard]] constexpr T *data() const noexcept {
return data_;
}
[[nodiscard]] constexpr size_t size() const noexcept {
return size_;
}
[[nodiscard]] constexpr T *begin() const noexcept {
return data_;
}
[[nodiscard]] constexpr T *end() const noexcept {
return *(data_ + size_);
}
const T &operator[](size_t index) const noexcept {
return *(data_ + index);
}
private:
T *data_;
size_t size_;
};
#endif // __cpp_lib_span
// To be used as a key in a unordered_map.
class StringKey {
public:
explicit StringKey(std::string &&string) noexcept;
explicit StringKey(std::string_view view) noexcept;
explicit StringKey(const char *data, size_t length) noexcept;
StringKey(StringKey &&other) noexcept;
StringKey &operator=(StringKey &&other) noexcept;
StringKey(const StringKey &other) = delete;
StringKey &operator=(const StringKey &other) = delete;
~StringKey();
std::string_view getStringView() const;
bool equalTo(const StringKey &other) const;
size_t hash() const;
struct Hash {
size_t operator()(const StringKey &key) const;
};
struct EqualTo {
bool operator()(const StringKey &left, const StringKey &right) const;
};
private:
enum class Type {
String,
View,
};
private:
union {
std::string string_;
std::string_view view_;
};
Type type_{Type::String};
size_t hash_;
};
struct NodeApiAttachTag {
} attachTag;
// Implementation of N-API JSI Runtime
class NodeApiJsiRuntime : public jsi::Runtime {
public:
NodeApiJsiRuntime(
napi_env env,
JSRuntimeApi *jsrApi,
std::function<void()> onDelete) noexcept;
~NodeApiJsiRuntime() override;
jsi::Value evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string &sourceURL) override;
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;
#if JSI_VERSION >= 12
void queueMicrotask(const jsi::Function &callback) override;
#endif
#if JSI_VERSION >= 4
bool drainMicrotasks(int maxMicrotasksHint = -1) override;
#endif
jsi::Object global() override;
std::string description() override;
bool isInspectable() override;
protected:
PointerValue *cloneSymbol(const PointerValue *pointerValue) override;
#if JSI_VERSION >= 6
PointerValue *cloneBigInt(const PointerValue *pointerValue) override;
#endif
PointerValue *cloneString(const PointerValue *pointerValue) override;
PointerValue *cloneObject(const PointerValue *pointerValue) override;
PointerValue *clonePropNameID(const PointerValue *pointerValue) 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;
#if JSI_VERSION >= 5
jsi::PropNameID createPropNameIDFromSymbol(const jsi::Symbol &sym) override;
#endif
std::string utf8(const jsi::PropNameID &id) override;
bool compare(const jsi::PropNameID &lhs, const jsi::PropNameID &rhs) override;
std::string symbolToString(const jsi::Symbol &s) override;
#if JSI_VERSION >= 8
jsi::BigInt createBigIntFromInt64(int64_t value) override;
jsi::BigInt createBigIntFromUint64(uint64_t value) override;
bool bigintIsInt64(const jsi::BigInt &value) override;
bool bigintIsUint64(const jsi::BigInt &value) override;
uint64_t truncate(const jsi::BigInt &value) override;
jsi::String bigintToString(const jsi::BigInt &value, int radix) override;
#endif
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 &str) 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;
#if JSI_VERSION >= 7
bool hasNativeState(const jsi::Object &value) override;
std::shared_ptr<jsi::NativeState> getNativeState(
const jsi::Object &value) override;
void setNativeState(
const jsi::Object &value,
std::shared_ptr<jsi::NativeState> state) override;
#endif
jsi::Value getProperty(const jsi::Object &obj, const jsi::PropNameID &name)
override;
jsi::Value getProperty(const jsi::Object &obj, const jsi::String &name)
override;
bool hasProperty(const jsi::Object &obj, const jsi::PropNameID &name)
override;
bool hasProperty(const jsi::Object &obj, const jsi::String &name) override;
void setPropertyValue(
JSI_CONST_10 jsi::Object &obj,
const jsi::PropNameID &name,
const jsi::Value &value) override;
void setPropertyValue(
JSI_CONST_10 jsi::Object &obj,
const jsi::String &name,
const jsi::Value &value) override;
bool isArray(const jsi::Object &obj) const override;
bool isArrayBuffer(const jsi::Object &obj) const override;
bool isFunction(const jsi::Object &obj) const override;
bool isHostObject(const jsi::Object &obj) const override;
bool isHostFunction(const jsi::Function &func) const override;
jsi::Array getPropertyNames(const jsi::Object &obj) override;
jsi::WeakObject createWeakObject(const jsi::Object &obj) override;
jsi::Value lockWeakObject(
JSI_NO_CONST_3 JSI_CONST_10 jsi::WeakObject &weakObj) override;
jsi::Array createArray(size_t length) override;
#if JSI_VERSION >= 9
jsi::ArrayBuffer createArrayBuffer(
std::shared_ptr<jsi::MutableBuffer> buffer);
#endif
size_t size(const jsi::Array &arr) override;
size_t size(const jsi::ArrayBuffer &arrBuf) override;
uint8_t *data(const jsi::ArrayBuffer &arrBuff) override;
jsi::Value getValueAtIndex(const jsi::Array &arr, size_t index) override;
void setValueAtIndexImpl(
JSI_CONST_10 jsi::Array &arr,
size_t index,
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 &func,
const jsi::Value &jsThis,
const jsi::Value *args,
size_t count) override;
jsi::Value callAsConstructor(
const jsi::Function &func,
const jsi::Value *args,
size_t count) override;
ScopeState *pushScope() override;
void popScope(ScopeState *) override;
bool strictEquals(const jsi::Symbol &a, const jsi::Symbol &b) const override;
#if JSI_VERSION >= 6
bool strictEquals(const jsi::BigInt &a, const jsi::BigInt &b) const override;
#endif
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 &obj, const jsi::Function &func) override;
#if JSI_VERSION >= 11
void setExternalMemoryPressure(const jsi::Object &obj, size_t amount)
override;
#endif
private:
// RAII class to open and close the environment scope.
class NodeApiScope {
public:
NodeApiScope(const NodeApiJsiRuntime &runtime) noexcept;
NodeApiScope(NodeApiJsiRuntime &runtime) noexcept;
~NodeApiScope() noexcept;
NodeApiScope(const NodeApiScope &) = delete;
NodeApiScope &operator=(const NodeApiScope &) = delete;
private:
NodeApiJsiRuntime &runtime_;
NodeApiEnvScope envScope_;
ScopeState *scopeState_{};
};
// RAII class to open and close the environment scope.
class NodeApiPointerValueScope {
public:
NodeApiPointerValueScope(NodeApiJsiRuntime &runtime) noexcept;
~NodeApiPointerValueScope() noexcept;
NodeApiPointerValueScope(const NodeApiPointerValueScope &) = delete;
NodeApiPointerValueScope &operator=(const NodeApiPointerValueScope &) =
delete;
private:
NodeApiJsiRuntime &runtime_;
};
// Sets the variable in the constructor and then restores its value in the
// destructor.
template <typename T>
class AutoRestore {
public:
AutoRestore(T &varRef, T value);
~AutoRestore();
AutoRestore(const AutoRestore &) = delete;
AutoRestore &operator=(const AutoRestore &) = delete;
private:
T &varRef_;
T oldValue_;
};
enum class NodeApiPointerValueKind : uint8_t {
Object,
WeakObject,
String,
StringPropNameID,
Symbol,
BigInt,
};
class NodeApiRefCountedPointerValue;
class NodeApiRefCount {
public:
static void incRefCount(std::atomic<int32_t> &value) noexcept {
int refCount = value.fetch_add(1, std::memory_order_relaxed) + 1;
CHECK_ELSE_CRASH(refCount > 1, "The ref count cannot bounce from zero.");
CHECK_ELSE_CRASH(
refCount < std::numeric_limits<int32_t>::max(),
"The ref count is too big.");
}
static bool decRefCount(std::atomic<int32_t> &value) noexcept {
int refCount = value.fetch_sub(1, std::memory_order_release) - 1;
CHECK_ELSE_CRASH(refCount >= 0, "The ref count must not be negative.");
if (refCount == 0) {
std::atomic_thread_fence(std::memory_order_acquire);
return true;
}
return false;
}
static bool isZero(std::atomic<int32_t> &value) noexcept {
return value.load(std::memory_order_relaxed) == 0;
}
};
// A smart pointer for types that implement intrusive ref count using
// methods incRefCount and decRefCount.
template <typename T>
class NodeApiRefCountedPtr final {
public:
NodeApiRefCountedPtr() noexcept = default;
explicit NodeApiRefCountedPtr(T *ptr, NodeApiAttachTag) noexcept
: ptr_(ptr) {}
NodeApiRefCountedPtr(const NodeApiRefCountedPtr &other) noexcept
: ptr_(other.ptr_) {
if (ptr_ != nullptr) {
ptr_->incRefCount();
}
}
NodeApiRefCountedPtr(NodeApiRefCountedPtr &&other)
: ptr_(std::exchange(other.ptr_, nullptr)) {}
~NodeApiRefCountedPtr() noexcept {
if (ptr_ != nullptr) {
ptr_->decRefCount();
}
}
NodeApiRefCountedPtr &operator=(std::nullptr_t) noexcept {
if (ptr_ != nullptr) {
ptr_->decRefCount();
}
ptr_ = nullptr;
return *this;
}
NodeApiRefCountedPtr &operator=(
const NodeApiRefCountedPtr &other) noexcept {
if (this != &other) {
NodeApiRefCountedPtr temp(std::move(*this));
ptr_ = other.ptr_;
if (ptr_ != nullptr) {
ptr_->incRefCount();
}
}
return *this;
}
NodeApiRefCountedPtr &operator=(NodeApiRefCountedPtr &&other) noexcept {
if (this != &other) {
NodeApiRefCountedPtr temp(std::move(*this));
ptr_ = std::exchange(other.ptr_, nullptr);
}
return *this;
}
T *operator->() const noexcept {
return ptr_;
}
T *get() const noexcept {
return ptr_;
}
explicit operator bool() const noexcept {
return ptr_ != nullptr;
}
T *release() noexcept {
return std::exchange(ptr_, nullptr);
}
private:
T *ptr_{};
};
// Removes the `napi_value value_` field.
class NodeApiStackValueDeleter {
public:
void operator()(NodeApiRefCountedPointerValue *ptr) const noexcept;
};
// Removes the NodeApiRefCountedPointerValue instance and ignores the
// `napi_ref ref_` field.
class NodeApiRefDeleter {
public:
void operator()(NodeApiRefCountedPointerValue *ptr) const noexcept;
};
using NodeApiRefHolder = NodeApiRefCountedPtr<NodeApiRefCountedPointerValue>;
using NodeApiStackValuePtr =
std::unique_ptr<NodeApiRefCountedPointerValue, NodeApiStackValueDeleter>;
using NodeApiRefPtr =
std::unique_ptr<NodeApiRefCountedPointerValue, NodeApiRefDeleter>;
// NodeApiPendingDeletions helps to delete PointerValues in a thread safe way
// from the JS thread. According to JSI spec the PointerValue's release method
// can be called from any thread, while Node-API can only manage objects in
// the JS thread. So, when a PointerValue's ref count goes to zero after
// calling the release method, the PointerValue is added into the
// pointerValuesToDelete_ vector, and then NodeApiJsiRuntime deletes them
// later from the JS thread. Note that the napi_delete_reference can only be
// called before the napi_env is destroyed. Thus, we remove the pointer to
// napi_env as soon as NodeApiJsiRuntime destructor starts.
class NodeApiPendingDeletions {
public:
// Create new instance of NodeApiPendingDeletions.
static NodeApiRefCountedPtr<NodeApiPendingDeletions> create() noexcept {
return NodeApiRefCountedPtr<NodeApiPendingDeletions>(
new NodeApiPendingDeletions(), attachTag);
}
// Add PointerValues to delete from JS thread. The method can be called from
// any thread.
void addPointerValueToDelete(NodeApiRefPtr pointerValueToDelete) noexcept {
std::scoped_lock lock{mutex_};
pointerValuesToDeletePool_[poolSelector_].push_back(
std::move(pointerValueToDelete));
}
// Delete all PointerValues scheduled for deletion along with their napi_ref
// instances. It must be called from a JS thread.
void deletePointerValues(NodeApiJsiRuntime &runtime) noexcept {
{
// TODO: Does it affect the performance to take the lock every time?
// Should we use an atomic variable?
std::scoped_lock lock{mutex_};
if (pointerValuesToDeletePool_[poolSelector_].empty()) {
return;
}
// Switch the pool entries.
poolSelector_ = poolSelector_ ^ 1;
}
std::vector<NodeApiRefPtr> &deleteInJSThread =
pointerValuesToDeletePool_[poolSelector_ ^ 1];
for (auto &pointerValue : deleteInJSThread) {
pointerValue.release()->deleteNodeApiRef(runtime);
}
deleteInJSThread.resize(0);
}
private:
friend class NodeApiRefCountedPtr<NodeApiPendingDeletions>;
NodeApiPendingDeletions() noexcept = default;
void incRefCount() noexcept {
NodeApiRefCount::incRefCount(refCount_);
}
void decRefCount() noexcept {
if (NodeApiRefCount::decRefCount(refCount_)) {
delete this;
}
}
private:
mutable std::atomic<int32_t> refCount_{1};
std::recursive_mutex mutex_;
// One of the vectors is used from different threads under the mutex_ lock
// to add items, while another is from JS thread to remove items. Since we
// never change the capacity of the vectors, it should help avoiding memory
// allocations at some point.
std::vector<NodeApiRefPtr> pointerValuesToDeletePool_[2]{
std::vector<NodeApiRefPtr>(),
std::vector<NodeApiRefPtr>()};
// Index of the pool to access under mutex.
int32_t poolSelector_{0};
};
// NodeApiPointerValue is used by jsi::Pointer derived classes.
struct NodeApiPointerValue : PointerValue {
virtual NodeApiRefCountedPointerValue *clone(
NodeApiJsiRuntime &runtime) const noexcept = 0;
virtual napi_value getValue(NodeApiJsiRuntime &runtime) noexcept = 0;
virtual NodeApiPointerValueKind getKind() const noexcept = 0;
};
// NodeApiStackOnlyPointerValue helps to avoid memory allocation in some
// scenarios. It is used by the JsiValueView, JsiValueViewArgs, and
// PropNameIDView classes to keep temporary PointerValues on the call stack
// when we call functions. Note that the clone() method return a new instance
// of the NodeApiRefCountedPointerValue.
class NodeApiStackOnlyPointerValue final : public NodeApiPointerValue {
public:
NodeApiStackOnlyPointerValue(
napi_value value,
NodeApiPointerValueKind pointerKind) noexcept;
void invalidate() noexcept override;
NodeApiRefCountedPointerValue *clone(
NodeApiJsiRuntime &runtime) const noexcept override;
napi_value getValue(NodeApiJsiRuntime &runtime) noexcept override;
NodeApiPointerValueKind getKind() const noexcept override;
NodeApiStackOnlyPointerValue(const NodeApiStackOnlyPointerValue &) = delete;
NodeApiStackOnlyPointerValue &operator=(
const NodeApiStackOnlyPointerValue &) = delete;
private:
napi_value value_{};
NodeApiPointerValueKind pointerKind_{NodeApiPointerValueKind::Object};
};
// TODO: Use arena allocator for NodeApiRefCountedPointerValue.
// NodeApiRefCountedPointerValue is a ref counted implementation of
// PointerValue that is allocated in the heap.
//
// Its lifetime is controlled by the atomic `refCount_` field. Since the
// `refCount_` can be changed from any thread, we do not remove the instance
// immediately when the `refCount_` becomes zero. Instead, we add it to the
// `NodeApiJsiRuntime::pendingDeletions_` list and delete it later from the JS
// thread. If `node_value value_` field is not null, then the
// `NodeApiRefCountedPointerValue` instance is also referenced from the
// `NodeApiJsiRuntime::stackValues_` list.
//
// The `NodeApiJsiRuntime::pendingDeletions_` is responsible for deleting
// `napi_ref ref_` and it deletes `NodeApiRefCountedPointerValue` instance if
// the `node_value value_` field is null. While
// `NodeApiJsiRuntime::stackValues_` is responsible for deleting
// `NodeApiRefCountedPointerValue` instance if `node_value value_` field is
// not null and `napi_ref ref_` is null. In case if
// `NodeApiJsiRuntime::pendingDeletions_` or `NodeApiJsiRuntime::stackValues_`
// cannot delete the instance, they set their "owned" `value_` or `ref_`
// fields to null.
//
// Some NodeApiRefCountedPointerValue are created with napi_value and may
// never get napi_ref. When stack scope is closed we check the `refCount_`. If
// it is not zero, then we ensure that it has an associated `napi_ref` or we
// create one.
//
// All methods except for invalidate() and decRefCount() must be called from
// the JS thread.
class NodeApiRefCountedPointerValue final : public NodeApiPointerValue {
friend class NodeApiStackValueDeleter;
friend class NodeApiRefDeleter;
friend class NodeApiRefCountedPtr<NodeApiRefCountedPointerValue>;
public:
// Creates new NodeApiRefCountedPointerValue and adds it to the
// NodeApiJsiRuntime::stackValues_.
static NodeApiRefHolder make(
NodeApiJsiRuntime &runtime,
napi_value value,
NodeApiPointerValueKind pointerKind,
int32_t initialRefCount = 1);
// Calls `make` method and forces creation of `napi_ref`.
static NodeApiRefHolder makeNodeApiRef(
NodeApiJsiRuntime &runtime,
napi_value value,
NodeApiPointerValueKind pointerKind,
int32_t initialRefCount = 1);
void invalidate() noexcept override;
NodeApiRefCountedPointerValue *clone(
NodeApiJsiRuntime &runtime) const noexcept override;
napi_value getValue(NodeApiJsiRuntime &runtime) noexcept override;
NodeApiPointerValueKind getKind() const noexcept override;
// Returns true if the refCount_ is not zero.
bool usedByJsiPointer() const noexcept;
// Removes `napi_value value_` field.
// In case if `refCount_` is not null, it ensures existence of the `napi_ref
// ref_` field.
void deleteStackValue(NodeApiJsiRuntime &runtime) noexcept;
// Removes napi_ref and deletes `NodeApiRefCountedPointerValue` if `value_`
// is null.
void deleteNodeApiRef(NodeApiJsiRuntime &runtime) noexcept;
NodeApiRefCountedPointerValue(const NodeApiRefCountedPointerValue &) =
delete;
NodeApiRefCountedPointerValue &operator=(
const NodeApiRefCountedPointerValue &) = delete;
private:
NodeApiRefCountedPointerValue(
NodeApiJsiRuntime &runtime,
napi_value value,
NodeApiPointerValueKind pointerKind,
int32_t initialRefCount) noexcept;
void incRefCount() const noexcept;
void decRefCount() const noexcept;
// Creates `napi_ref ref_` field for the `napi_value value_` field.
NodeApiRefCountedPointerValue *createNodeApiRef(NodeApiJsiRuntime &runtime);
private:
NodeApiRefCountedPtr<NodeApiPendingDeletions> pendingDeletions_;
napi_value value_{};
napi_ref ref_{};
mutable std::atomic<int32_t> refCount_{1};
const NodeApiPointerValueKind pointerKind_{NodeApiPointerValueKind::Object};
bool canBeDeletedFromStack_{false};
static constexpr char kPrimitivePropertyName[] = "X";
};
// SmallBuffer keeps InplaceSize elements in place in the class, and uses heap
// memory for more elements.
template <typename T, size_t InplaceSize>
class SmallBuffer {
public:
SmallBuffer(size_t size) noexcept;
T *data() noexcept;
size_t size() const noexcept;
SmallBuffer(const SmallBuffer &) = delete;
SmallBuffer &operator=(const SmallBuffer &) = delete;
private:
size_t size_{};
std::array<T, InplaceSize> stackData_{};
std::unique_ptr<T[]> heapData_{};
};
// The number of arguments that we keep on stack. We use heap if we have more
// arguments.
constexpr static size_t MaxStackArgCount = 8;
// NodeApiValueArgs helps optimize passing arguments to Node-API functions.
// If number of arguments is below or equal to MaxStackArgCount, they are kept
// on the call stack, otherwise arguments are allocated on the heap.
class NodeApiValueArgs {
public:
NodeApiValueArgs(NodeApiJsiRuntime &runtime, span<const jsi::Value> args);
operator span<napi_value>();
NodeApiValueArgs(const NodeApiValueArgs &) = delete;
NodeApiValueArgs &operator=(const NodeApiValueArgs &) = delete;
private:
SmallBuffer<napi_value, MaxStackArgCount> args_;
};
// Helps to use the stack storage for a temporary conversion from napi_value
// to jsi::Value. It also helps to avoid a conversion to a relatively
// expensive napi_ref.
class JsiValueView {
public:
union StoreType {
NodeApiStackOnlyPointerValue value_;
std::array<std::byte, sizeof(NodeApiStackOnlyPointerValue)> bytes_;
StoreType() {}
~StoreType() {}
};
public:
JsiValueView(NodeApiJsiRuntime *runtime, napi_value jsValue);
operator const jsi::Value &() const noexcept;
static jsi::Value
initValue(NodeApiJsiRuntime *runtime, napi_value jsValue, StoreType *store);
JsiValueView(const JsiValueView &) = delete;
JsiValueView &operator=(const JsiValueView &) = delete;
private:
StoreType pointerStore_;
jsi::Value value_{};
};
// Helps to use stack storage for passing arguments that must be temporarily
// converted from napi_value to jsi::Value. It helps to avoid conversion to a
// relatively expensive napi_ref.
class JsiValueViewArgs {
public:
JsiValueViewArgs(
NodeApiJsiRuntime *runtime,
span<napi_value> args) noexcept;
const jsi::Value *data() noexcept;
size_t size() const noexcept;
JsiValueViewArgs(const JsiValueViewArgs &);
JsiValueViewArgs &operator=(const JsiValueViewArgs &);
private:
using StoreType = JsiValueView::StoreType;
SmallBuffer<StoreType, MaxStackArgCount> pointerStore_{0};
SmallBuffer<jsi::Value, MaxStackArgCount> args_{0};
};
// Helps to use stack storage for a temporary conversion from napi_value to
// jsi::PropNameID. It helps to avoid conversions to a relatively expensive
// napi_ref.
class PropNameIDView {
public:
PropNameIDView(NodeApiJsiRuntime *runtime, napi_value propertyId) noexcept;
operator const jsi::PropNameID &() const noexcept;
PropNameIDView(const PropNameIDView &);
PropNameIDView &operator=(const PropNameIDView &);
private:
using StoreType = JsiValueView::StoreType;
StoreType pointerStore_{};
jsi::PropNameID const propertyId_;
};
// Wraps up the jsi::HostFunctionType along with the NodeApiJsiRuntime.
class HostFunctionWrapper {
public:
HostFunctionWrapper(
jsi::HostFunctionType &&hostFunction,
NodeApiJsiRuntime &runtime);
jsi::HostFunctionType &hostFunction() noexcept;
NodeApiJsiRuntime &runtime() noexcept;
HostFunctionWrapper(const HostFunctionWrapper &) = delete;
HostFunctionWrapper &operator=(const HostFunctionWrapper &) = delete;
private:
jsi::HostFunctionType hostFunction_;
NodeApiJsiRuntime &runtime_;
};
// Wraps up the jsr_prepared_script.
class NodeApiPreparedJavaScript final : public jsi::PreparedJavaScript {
public:
NodeApiPreparedJavaScript(
napi_env env,
jsr_prepared_script script,
std::string sourceURL)
: env_(env), script_(script), sourceURL_(std::move(sourceURL)) {}
~NodeApiPreparedJavaScript() override {
JSRuntimeApi::current()->jsr_delete_prepared_script(env_, script_);
}
jsr_prepared_script getScript() const {
return script_;
}
const std::string &sourceURL() const {
return sourceURL_;
}
NodeApiPreparedJavaScript(const NodeApiPreparedJavaScript &) = delete;
NodeApiPreparedJavaScript &operator=(const NodeApiPreparedJavaScript &) =
delete;
private:
napi_env env_;
jsr_prepared_script script_;
std::string sourceURL_;
};
private: // Error-handling utility methods
template <typename... Args>
jsi::JSError makeJSError(Args &&...args);
[[noreturn]] void throwJSException(napi_status errorCode) const;
[[noreturn]] void throwNativeException(char const *errorMessage) const;
void rewriteErrorMessage(napi_value jsError) const;
template <typename TLambda>
auto runInMethodContext(char const *methodName, TLambda lambda);
template <typename TLambda>
napi_value handleCallbackExceptions(TLambda lambda) const noexcept;
bool setException(napi_value error) const noexcept;
bool setException(std::string_view message) const noexcept;
private: // Shared Node-API call helpers
napi_valuetype typeOf(napi_value value) const;
bool strictEquals(napi_value left, napi_value right) const;
napi_value getUndefined() const;
napi_value getNull() const;
napi_value getGlobal() const;
napi_value getBoolean(bool value) const;
bool getValueBool(napi_value value) const;
napi_value createInt32(int32_t value) const;
napi_value createUInt32(uint32_t value) const;
napi_value createDouble(double value) const;
double getValueDouble(napi_value value) const;
napi_value createStringLatin1(std::string_view value) const;
napi_value createStringUtf8(std::string_view value) const;
napi_value createStringUtf8(const uint8_t *data, size_t length) const;
std::string stringToStdString(napi_value stringValue) const;
napi_value getPropertyIdFromName(std::string_view value) const;
napi_value getPropertyIdFromName(const uint8_t *data, size_t length) const;
napi_value getPropertyIdFromName(napi_value str) const;
napi_value getPropertyIdFromSymbol(napi_value sym) const;
std::string propertyIdToStdString(napi_value propertyId);
napi_value createSymbol(std::string_view symbolDescription) const;
std::string symbolToStdString(napi_value symbolValue);
napi_value callFunction(
napi_value thisArg,
napi_value function,
span<napi_value> args = {}) const;
napi_value constructObject(napi_value constructor, span<napi_value> args = {})
const;
bool instanceOf(napi_value object, napi_value constructor) const;
napi_value createNodeApiObject() const;
bool hasProperty(napi_value object, napi_value propertyId) const;
napi_value getProperty(napi_value object, napi_value propertyId) const;
void setProperty(napi_value object, napi_value propertyId, napi_value value)
const;
void setProperty(
napi_value object,
napi_value propertyId,
napi_value value,
napi_property_attributes attrs) const;
napi_value createNodeApiArray(size_t length) const;
bool isArray(napi_value value) const;
size_t getArrayLength(napi_value value) const;
napi_value getElement(napi_value arr, size_t index) const;
void setElement(napi_value array, uint32_t index, napi_value value) const;
static napi_value __cdecl jsiHostFunctionCallback(
napi_env env,
napi_callback_info info) noexcept;
napi_value createExternalFunction(
napi_value name,
int32_t paramCount,
napi_callback callback,
void *callbackData);
napi_value createExternalObject(
void *data,
node_api_nogc_finalize finalizeCallback) const;
template <typename T>
napi_value createExternalObject(std::unique_ptr<T> &&data) const;
void *getExternalData(napi_value object) const;
const std::shared_ptr<jsi::HostObject> &getJsiHostObject(napi_value obj);
napi_value getHostObjectProxyHandler();
template <
napi_value (NodeApiJsiRuntime::*trapMethod)(span<napi_value>),
size_t argCount>
void setProxyTrap(napi_value handler, napi_value propertyName);
napi_value hostObjectHasTrap(span<napi_value> args);
napi_value hostObjectGetTrap(span<napi_value> args);
napi_value hostObjectSetTrap(span<napi_value> args);
napi_value hostObjectOwnKeysTrap(span<napi_value> args);
napi_value hostObjectGetOwnPropertyDescriptorTrap(span<napi_value> args);
private: // Miscellaneous utility methods
span<const uint8_t> toSpan(const jsi::Buffer &buffer);
jsi::Value toJsiValue(napi_value value) const;
napi_value getNodeApiValue(const jsi::Value &value) const;
napi_value getNodeApiValue(const jsi::Pointer &ptr) const;
napi_value getNodeApiValue(const NodeApiRefHolder &ref) const;
NodeApiRefCountedPointerValue *cloneNodeApiPointerValue(
const PointerValue *pointerValue);
std::optional<uint32_t> toArrayIndex(
std::string::const_iterator first,
std::string::const_iterator last);
template <
typename T,
std::enable_if_t<std::is_same_v<jsi::Object, T>, int> = 0>
T makeJsiPointer(napi_value value) const;
template <
typename T,
std::enable_if_t<std::is_same_v<jsi::String, T>, int> = 0>
T makeJsiPointer(napi_value value) const;
template <
typename T,
std::enable_if_t<std::is_same_v<jsi::Symbol, T>, int> = 0>
T makeJsiPointer(napi_value value) const;
#if JSI_VERSION >= 6
template <
typename T,
std::enable_if_t<std::is_same_v<jsi::BigInt, T>, int> = 0>
T makeJsiPointer(napi_value value) const;
#endif
template <
typename TTo,
typename TFrom,
std::enable_if_t<std::is_base_of_v<jsi::Pointer, TTo>, int> = 0,
std::enable_if_t<std::is_base_of_v<jsi::Pointer, TFrom>, int> = 0>
TTo cloneAs(const TFrom &pointer) const;
NodeApiRefHolder makeNodeApiRef(
napi_value value,
NodeApiPointerValueKind pointerKind,
int32_t initialRefCount = 1);
void addStackValue(NodeApiStackValuePtr stackPointer);
void pushPointerValueScope() noexcept;
void popPointerValueScope() noexcept;
napi_env getEnv() const noexcept {
return env_;
}
private: // Fields