-
Notifications
You must be signed in to change notification settings - Fork 1
/
JSCRuntime.cpp
1418 lines (1252 loc) · 42.8 KB
/
JSCRuntime.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "JSCRuntime.h"
#include <JavaScriptCore/JavaScript.h>
#include <atomic>
#include <condition_variable>
#include <cstdlib>
#include <jsi/jsilib.h>
#include <mutex>
#include <queue>
#include <sstream>
#include <thread>
namespace facebook {
namespace jsc {
namespace detail {
class ArgsConverter;
} // namespace detail
class JSCRuntime;
struct Lock {
void lock(const jsc::JSCRuntime&) const {}
void unlock(const jsc::JSCRuntime&) const {}
};
class JSCRuntime : public jsi::Runtime {
public:
// Creates new context in new context group
JSCRuntime();
// Retains ctx
JSCRuntime(JSGlobalContextRef ctx);
~JSCRuntime();
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;
jsi::Object global() override;
std::string description() override;
bool isInspectable() override;
void setDescription(const std::string& desc);
// Please don't use the following two functions, only exposed for
// integration efforts.
JSGlobalContextRef getContext() {
return ctx_;
}
// JSValueRef->JSValue (needs make.*Value so it must be member function)
jsi::Value createValue(JSValueRef value) const;
// Value->JSValueRef (similar to above)
JSValueRef valueRef(const jsi::Value& value);
protected:
friend class detail::ArgsConverter;
class JSCSymbolValue final : public PointerValue {
#ifndef NDEBUG
JSCSymbolValue(JSGlobalContextRef ctx,
const std::atomic<bool>& ctxInvalid,
JSValueRef sym, std::atomic<intptr_t>& counter);
#else
JSCSymbolValue(JSGlobalContextRef ctx,
const std::atomic<bool>& ctxInvalid,
JSValueRef sym);
#endif
void invalidate() override;
JSGlobalContextRef ctx_;
const std::atomic<bool>& ctxInvalid_;
// There is no C type in the JSC API to represent Symbol, so this stored
// a JSValueRef which contains the Symbol.
JSValueRef sym_;
#ifndef NDEBUG
std::atomic<intptr_t>& counter_;
#endif
protected:
friend class JSCRuntime;
};
class JSCStringValue final : public PointerValue {
#ifndef NDEBUG
JSCStringValue(JSStringRef str, std::atomic<intptr_t>& counter);
#else
JSCStringValue(JSStringRef str);
#endif
void invalidate() override;
JSStringRef str_;
#ifndef NDEBUG
std::atomic<intptr_t>& counter_;
#endif
protected:
friend class JSCRuntime;
};
class JSCObjectValue final : public PointerValue {
JSCObjectValue(
JSGlobalContextRef ctx,
const std::atomic<bool>& ctxInvalid,
JSObjectRef obj
#ifndef NDEBUG
,
std::atomic<intptr_t>& counter
#endif
);
void invalidate() override;
JSGlobalContextRef ctx_;
const std::atomic<bool>& ctxInvalid_;
JSObjectRef obj_;
#ifndef NDEBUG
std::atomic<intptr_t>& counter_;
#endif
protected:
friend class JSCRuntime;
};
PointerValue* cloneSymbol(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;
std::string utf8(const jsi::PropNameID&) override;
bool compare(const jsi::PropNameID&, const jsi::PropNameID&) override;
std::string symbolToString(const jsi::Symbol&) 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::Object createObject() override;
jsi::Object createObject(std::shared_ptr<jsi::HostObject> ho) override;
virtual std::shared_ptr<jsi::HostObject> getHostObject(
const jsi::Object&) override;
jsi::HostFunctionType& getHostFunction(const jsi::Function&) override;
jsi::Value getProperty(const jsi::Object&, const jsi::String& name) override;
jsi::Value getProperty(const jsi::Object&, const jsi::PropNameID& name)
override;
bool hasProperty(const jsi::Object&, const jsi::String& name) override;
bool hasProperty(const jsi::Object&, const jsi::PropNameID& name) override;
void setPropertyValue(
jsi::Object&,
const jsi::String& name,
const jsi::Value& value) override;
void setPropertyValue(
jsi::Object&,
const jsi::PropNameID& 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;
// TODO: revisit this implementation
jsi::WeakObject createWeakObject(const jsi::Object&) override;
jsi::Value lockWeakObject(const 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::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& f) override;
private:
// Basically convenience casts
static JSValueRef symbolRef(const jsi::Symbol& str);
static JSStringRef stringRef(const jsi::String& str);
static JSStringRef stringRef(const jsi::PropNameID& sym);
static JSObjectRef objectRef(const jsi::Object& obj);
#ifdef RN_FABRIC_ENABLED
static JSObjectRef objectRef(const jsi::WeakObject& obj);
#endif
// Factory methods for creating String/Object
jsi::Symbol createSymbol(JSValueRef symbolRef) const;
jsi::String createString(JSStringRef stringRef) const;
jsi::PropNameID createPropNameID(JSStringRef stringRef);
jsi::Object createObject(JSObjectRef objectRef) const;
// Used by factory methods and clone methods
jsi::Runtime::PointerValue* makeSymbolValue(JSValueRef sym) const;
jsi::Runtime::PointerValue* makeStringValue(JSStringRef str) const;
jsi::Runtime::PointerValue* makeObjectValue(JSObjectRef obj) const;
void checkException(JSValueRef exc);
void checkException(JSValueRef res, JSValueRef exc);
void checkException(JSValueRef exc, const char* msg);
void checkException(JSValueRef res, JSValueRef exc, const char* msg);
JSGlobalContextRef ctx_;
std::atomic<bool> ctxInvalid_;
std::string desc_;
#ifndef NDEBUG
mutable std::atomic<intptr_t> objectCounter_;
mutable std::atomic<intptr_t> symbolCounter_;
mutable std::atomic<intptr_t> stringCounter_;
#endif
};
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#if __has_builtin(__builtin_expect) || defined(__GNUC__)
#define JSC_LIKELY(EXPR) __builtin_expect((bool)(EXPR), true)
#define JSC_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false)
#else
#define JSC_LIKELY(EXPR) (EXPR)
#define JSC_UNLIKELY(EXPR) (EXPR)
#endif
#define JSC_ASSERT(x) \
do { \
if (JSC_UNLIKELY(!!(x))) { \
abort(); \
} \
} while (0)
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
// This takes care of watch and tvos (due to backwards compatibility in
// Availability.h
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0
#define _JSC_FAST_IS_ARRAY
#endif
#endif
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_11
// Only one of these should be set for a build. If somehow that's not
// true, this will be a compile-time error and it can be resolved when
// we understand why.
#define _JSC_FAST_IS_ARRAY
#endif
#endif
// JSStringRef utilities
namespace {
std::string JSStringToSTLString(JSStringRef str) {
size_t maxBytes = JSStringGetMaximumUTF8CStringSize(str);
std::vector<char> buffer(maxBytes);
JSStringGetUTF8CString(str, buffer.data(), maxBytes);
return std::string(buffer.data());
}
JSStringRef getLengthString() {
static JSStringRef length = JSStringCreateWithUTF8CString("length");
return length;
}
JSStringRef getNameString() {
static JSStringRef name = JSStringCreateWithUTF8CString("name");
return name;
}
JSStringRef getFunctionString() {
static JSStringRef func = JSStringCreateWithUTF8CString("Function");
return func;
}
#if !defined(_JSC_FAST_IS_ARRAY)
JSStringRef getArrayString() {
static JSStringRef array = JSStringCreateWithUTF8CString("Array");
return array;
}
JSStringRef getIsArrayString() {
static JSStringRef isArray = JSStringCreateWithUTF8CString("isArray");
return isArray;
}
#endif
} // namespace
// std::string utility
namespace {
std::string to_string(void* value) {
std::ostringstream ss;
ss << value;
return ss.str();
}
} // namespace
JSCRuntime::JSCRuntime()
: JSCRuntime(JSGlobalContextCreateInGroup(nullptr, nullptr)) {
JSGlobalContextRelease(ctx_);
}
JSCRuntime::JSCRuntime(JSGlobalContextRef ctx)
: ctx_(JSGlobalContextRetain(ctx)),
ctxInvalid_(false)
#ifndef NDEBUG
,
objectCounter_(0),
stringCounter_(0)
#endif
{
}
JSCRuntime::~JSCRuntime() {
// On shutting down and cleaning up: when JSC is actually torn down,
// it calls JSC::Heap::lastChanceToFinalize internally which
// finalizes anything left over. But at this point,
// JSValueUnprotect() can no longer be called. We use an
// atomic<bool> to avoid unsafe unprotects happening after shutdown
// has started.
ctxInvalid_ = true;
JSGlobalContextRelease(ctx_);
#ifndef NDEBUG
assert(
objectCounter_ == 0 && "JSCRuntime destroyed with a dangling API object");
assert(
stringCounter_ == 0 && "JSCRuntime destroyed with a dangling API string");
#endif
}
std::shared_ptr<const jsi::PreparedJavaScript> JSCRuntime::prepareJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
std::string sourceURL) {
return std::make_shared<jsi::SourceJavaScriptPreparation>(
buffer, std::move(sourceURL));
}
jsi::Value JSCRuntime::evaluatePreparedJavaScript(
const std::shared_ptr<const jsi::PreparedJavaScript>& js) {
assert(
dynamic_cast<const jsi::SourceJavaScriptPreparation*>(js.get()) &&
"preparedJavaScript must be a SourceJavaScriptPreparation");
auto sourceJs =
std::static_pointer_cast<const jsi::SourceJavaScriptPreparation>(js);
return evaluateJavaScript(sourceJs, sourceJs->sourceURL());
}
jsi::Value JSCRuntime::evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string& sourceURL) {
std::string tmp(
reinterpret_cast<const char*>(buffer->data()), buffer->size());
JSStringRef sourceRef = JSStringCreateWithUTF8CString(tmp.c_str());
JSStringRef sourceURLRef = nullptr;
if (!sourceURL.empty()) {
sourceURLRef = JSStringCreateWithUTF8CString(sourceURL.c_str());
}
JSValueRef exc = nullptr;
JSValueRef res =
JSEvaluateScript(ctx_, sourceRef, nullptr, sourceURLRef, 0, &exc);
JSStringRelease(sourceRef);
if (sourceURLRef) {
JSStringRelease(sourceURLRef);
}
checkException(res, exc);
return createValue(res);
}
jsi::Object JSCRuntime::global() {
return createObject(JSContextGetGlobalObject(ctx_));
}
std::string JSCRuntime::description() {
if (desc_.empty()) {
desc_ = std::string("<JSCRuntime@") + to_string(this) + ">";
}
return desc_;
}
bool JSCRuntime::isInspectable() {
return false;
}
namespace {
bool smellsLikeES6Symbol(JSGlobalContextRef ctx, JSValueRef ref) {
// Empirically, an es6 Symbol is not an object, but its type is
// object. This makes no sense, but we'll run with it.
return (!JSValueIsObject(ctx, ref) &&
JSValueGetType(ctx, ref) == kJSTypeObject);
}
}
JSCRuntime::JSCSymbolValue::JSCSymbolValue(
JSGlobalContextRef ctx,
const std::atomic<bool>& ctxInvalid,
JSValueRef sym
#ifndef NDEBUG
,
std::atomic<intptr_t>& counter
#endif
)
: ctx_(ctx),
ctxInvalid_(ctxInvalid),
sym_(sym)
#ifndef NDEBUG
,
counter_(counter)
#endif
{
assert(smellsLikeES6Symbol(ctx_, sym_));
JSValueProtect(ctx_, sym_);
#ifndef NDEBUG
counter_ += 1;
#endif
}
void JSCRuntime::JSCSymbolValue::invalidate() {
#ifndef NDEBUG
counter_ -= 1;
#endif
if (!ctxInvalid_) {
JSValueUnprotect(ctx_, sym_);
}
delete this;
}
#ifndef NDEBUG
JSCRuntime::JSCStringValue::JSCStringValue(
JSStringRef str,
std::atomic<intptr_t>& counter)
: str_(JSStringRetain(str)), counter_(counter) {
// Since std::atomic returns a copy instead of a reference when calling
// operator+= we must do this explicitly in the constructor
counter_ += 1;
}
#else
JSCRuntime::JSCStringValue::JSCStringValue(JSStringRef str)
: str_(JSStringRetain(str)) {
}
#endif
void JSCRuntime::JSCStringValue::invalidate() {
// These JSC{String,Object}Value objects are implicitly owned by the
// {String,Object} objects, thus when a String/Object is destructed
// the JSC{String,Object}Value should be released.
#ifndef NDEBUG
counter_ -= 1;
#endif
JSStringRelease(str_);
// Angery reaccs only
delete this;
}
JSCRuntime::JSCObjectValue::JSCObjectValue(
JSGlobalContextRef ctx,
const std::atomic<bool>& ctxInvalid,
JSObjectRef obj
#ifndef NDEBUG
,
std::atomic<intptr_t>& counter
#endif
)
: ctx_(ctx),
ctxInvalid_(ctxInvalid),
obj_(obj)
#ifndef NDEBUG
,
counter_(counter)
#endif
{
JSValueProtect(ctx_, obj_);
#ifndef NDEBUG
counter_ += 1;
#endif
}
void JSCRuntime::JSCObjectValue::invalidate() {
#ifndef NDEBUG
counter_ -= 1;
#endif
// When shutting down the VM, if there is a HostObject which
// contains or otherwise owns a jsi::Object, then the final GC will
// finalize the HostObject, leading to a call to invalidate(). But
// at that point, making calls to JSValueUnprotect will crash.
// It is up to the application to make sure that any other calls to
// invalidate() happen before VM destruction; see the comment on
// jsi::Runtime.
//
// Another potential concern here is that in the non-shutdown case,
// if a HostObject is GCd, JSValueUnprotect will be called from the
// JSC finalizer. The documentation warns against this: "You must
// not call any function that may cause a garbage collection or an
// allocation of a garbage collected object from within a
// JSObjectFinalizeCallback. This includes all functions that have a
// JSContextRef parameter." However, an audit of the source code for
// JSValueUnprotect in late 2018 shows that it cannot cause
// allocation or a GC, and further, this code has not changed in
// about two years. In the future, we may choose to reintroduce the
// mechanism previously used here which uses a separate thread for
// JSValueUnprotect, in order to conform to the documented API, but
// use the "unsafe" synchronous version on iOS 11 and earlier.
if (!ctxInvalid_) {
JSValueUnprotect(ctx_, obj_);
}
delete this;
}
jsi::Runtime::PointerValue* JSCRuntime::cloneSymbol(
const jsi::Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
const JSCSymbolValue* symbol = static_cast<const JSCSymbolValue*>(pv);
return makeSymbolValue(symbol->sym_);
}
jsi::Runtime::PointerValue* JSCRuntime::cloneString(
const jsi::Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
const JSCStringValue* string = static_cast<const JSCStringValue*>(pv);
return makeStringValue(string->str_);
}
jsi::Runtime::PointerValue* JSCRuntime::cloneObject(
const jsi::Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
const JSCObjectValue* object = static_cast<const JSCObjectValue*>(pv);
assert(
object->ctx_ == ctx_ &&
"Don't try to clone an object backed by a different Runtime");
return makeObjectValue(object->obj_);
}
jsi::Runtime::PointerValue* JSCRuntime::clonePropNameID(
const jsi::Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
const JSCStringValue* string = static_cast<const JSCStringValue*>(pv);
return makeStringValue(string->str_);
}
jsi::PropNameID JSCRuntime::createPropNameIDFromAscii(
const char* str,
size_t length) {
// For system JSC this must is identical to a string
std::string tmp(str, length);
JSStringRef strRef = JSStringCreateWithUTF8CString(tmp.c_str());
auto res = createPropNameID(strRef);
JSStringRelease(strRef);
return res;
}
jsi::PropNameID JSCRuntime::createPropNameIDFromUtf8(
const uint8_t* utf8,
size_t length) {
std::string tmp(reinterpret_cast<const char*>(utf8), length);
JSStringRef strRef = JSStringCreateWithUTF8CString(tmp.c_str());
auto res = createPropNameID(strRef);
JSStringRelease(strRef);
return res;
}
jsi::PropNameID JSCRuntime::createPropNameIDFromString(const jsi::String& str) {
return createPropNameID(stringRef(str));
}
std::string JSCRuntime::utf8(const jsi::PropNameID& sym) {
return JSStringToSTLString(stringRef(sym));
}
bool JSCRuntime::compare(const jsi::PropNameID& a, const jsi::PropNameID& b) {
return JSStringIsEqual(stringRef(a), stringRef(b));
}
std::string JSCRuntime::symbolToString(const jsi::Symbol& sym) {
return jsi::Value(*this, sym)
.toString(*this)
.utf8(*this);
}
jsi::String JSCRuntime::createStringFromAscii(const char* str, size_t length) {
// Yes we end up double casting for semantic reasons (UTF8 contains ASCII,
// not the other way around)
return this->createStringFromUtf8(
reinterpret_cast<const uint8_t*>(str), length);
}
jsi::String JSCRuntime::createStringFromUtf8(
const uint8_t* str,
size_t length) {
std::string tmp(reinterpret_cast<const char*>(str), length);
JSStringRef stringRef = JSStringCreateWithUTF8CString(tmp.c_str());
auto result = createString(stringRef);
JSStringRelease(stringRef);
return result;
}
std::string JSCRuntime::utf8(const jsi::String& str) {
return JSStringToSTLString(stringRef(str));
}
jsi::Object JSCRuntime::createObject() {
return createObject(static_cast<JSObjectRef>(nullptr));
}
// HostObject details
namespace detail {
struct HostObjectProxyBase {
HostObjectProxyBase(
JSCRuntime& rt,
const std::shared_ptr<jsi::HostObject>& sho)
: runtime(rt), hostObject(sho) {}
JSCRuntime& runtime;
std::shared_ptr<jsi::HostObject> hostObject;
};
} // namespace detail
namespace {
std::once_flag hostObjectClassOnceFlag;
JSClassRef hostObjectClass{};
} // namespace
jsi::Object JSCRuntime::createObject(std::shared_ptr<jsi::HostObject> ho) {
struct HostObjectProxy : public detail::HostObjectProxyBase {
static JSValueRef getProperty(
JSContextRef ctx,
JSObjectRef object,
JSStringRef propName,
JSValueRef* exception) {
auto proxy = static_cast<HostObjectProxy*>(JSObjectGetPrivate(object));
auto& rt = proxy->runtime;
jsi::PropNameID sym = rt.createPropNameID(propName);
jsi::Value ret;
try {
ret = proxy->hostObject->get(rt, sym);
} catch (const jsi::JSError& error) {
*exception = rt.valueRef(error.value());
return JSValueMakeUndefined(ctx);
} catch (const std::exception& ex) {
auto excValue =
rt.global()
.getPropertyAsFunction(rt, "Error")
.call(
rt,
std::string("Exception in HostObject::get(propName:")
+ JSStringToSTLString(propName)
+ std::string("): ") + ex.what());
*exception = rt.valueRef(excValue);
return JSValueMakeUndefined(ctx);
} catch (...) {
auto excValue =
rt.global()
.getPropertyAsFunction(rt, "Error")
.call(
rt,
std::string("Exception in HostObject::get(propName:")
+ JSStringToSTLString(propName)
+ std::string("): <unknown>"));
*exception = rt.valueRef(excValue);
return JSValueMakeUndefined(ctx);
}
return rt.valueRef(ret);
}
#define JSC_UNUSED(x) (void) (x);
static bool setProperty(
JSContextRef ctx,
JSObjectRef object,
JSStringRef propName,
JSValueRef value,
JSValueRef* exception) {
JSC_UNUSED(ctx);
auto proxy = static_cast<HostObjectProxy*>(JSObjectGetPrivate(object));
auto& rt = proxy->runtime;
jsi::PropNameID sym = rt.createPropNameID(propName);
try {
proxy->hostObject->set(rt, sym, rt.createValue(value));
} catch (const jsi::JSError& error) {
*exception = rt.valueRef(error.value());
return false;
} catch (const std::exception& ex) {
auto excValue =
rt.global()
.getPropertyAsFunction(rt, "Error")
.call(
rt,
std::string("Exception in HostObject::set(propName:")
+ JSStringToSTLString(propName)
+ std::string("): ") + ex.what());
*exception = rt.valueRef(excValue);
return false;
} catch (...) {
auto excValue =
rt.global()
.getPropertyAsFunction(rt, "Error")
.call(
rt,
std::string("Exception in HostObject::set(propName:")
+ JSStringToSTLString(propName)
+ std::string("): <unknown>"));
*exception = rt.valueRef(excValue);
return false;
}
return true;
}
// JSC does not provide means to communicate errors from this callback,
// so the error handling strategy is very brutal - we'll just crash
// due to noexcept.
static void getPropertyNames(
JSContextRef ctx,
JSObjectRef object,
JSPropertyNameAccumulatorRef propertyNames) noexcept {
JSC_UNUSED(ctx);
auto proxy = static_cast<HostObjectProxy*>(JSObjectGetPrivate(object));
auto& rt = proxy->runtime;
auto names = proxy->hostObject->getPropertyNames(rt);
for (auto& name : names) {
JSPropertyNameAccumulatorAddName(propertyNames, stringRef(name));
}
}
#undef JSC_UNUSED
static void finalize(JSObjectRef obj) {
auto hostObject = static_cast<HostObjectProxy*>(JSObjectGetPrivate(obj));
JSObjectSetPrivate(obj, nullptr);
delete hostObject;
}
using HostObjectProxyBase::HostObjectProxyBase;
};
std::call_once(hostObjectClassOnceFlag, []() {
JSClassDefinition hostObjectClassDef = kJSClassDefinitionEmpty;
hostObjectClassDef.version = 0;
hostObjectClassDef.attributes = kJSClassAttributeNoAutomaticPrototype;
hostObjectClassDef.finalize = HostObjectProxy::finalize;
hostObjectClassDef.getProperty = HostObjectProxy::getProperty;
hostObjectClassDef.setProperty = HostObjectProxy::setProperty;
hostObjectClassDef.getPropertyNames = HostObjectProxy::getPropertyNames;
hostObjectClass = JSClassCreate(&hostObjectClassDef);
});
JSObjectRef obj =
JSObjectMake(ctx_, hostObjectClass, new HostObjectProxy(*this, ho));
return createObject(obj);
}
std::shared_ptr<jsi::HostObject> JSCRuntime::getHostObject(
const jsi::Object& obj) {
// We are guaranteed at this point to have isHostObject(obj) == true
// so the private data should be HostObjectMetadata
JSObjectRef object = objectRef(obj);
auto metadata =
static_cast<detail::HostObjectProxyBase*>(JSObjectGetPrivate(object));
assert(metadata);
return metadata->hostObject;
}
jsi::Value JSCRuntime::getProperty(
const jsi::Object& obj,
const jsi::String& name) {
JSObjectRef objRef = objectRef(obj);
JSValueRef exc = nullptr;
JSValueRef res = JSObjectGetProperty(ctx_, objRef, stringRef(name), &exc);
checkException(exc);
return createValue(res);
}
jsi::Value JSCRuntime::getProperty(
const jsi::Object& obj,
const jsi::PropNameID& name) {
JSObjectRef objRef = objectRef(obj);
JSValueRef exc = nullptr;
JSValueRef res = JSObjectGetProperty(ctx_, objRef, stringRef(name), &exc);
checkException(exc);
return createValue(res);
}
bool JSCRuntime::hasProperty(const jsi::Object& obj, const jsi::String& name) {
JSObjectRef objRef = objectRef(obj);
return JSObjectHasProperty(ctx_, objRef, stringRef(name));
}
bool JSCRuntime::hasProperty(
const jsi::Object& obj,
const jsi::PropNameID& name) {
JSObjectRef objRef = objectRef(obj);
return JSObjectHasProperty(ctx_, objRef, stringRef(name));
}
void JSCRuntime::setPropertyValue(
jsi::Object& object,
const jsi::PropNameID& name,
const jsi::Value& value) {
JSValueRef exc = nullptr;
JSObjectSetProperty(
ctx_,
objectRef(object),
stringRef(name),
valueRef(value),
kJSPropertyAttributeNone,
&exc);
checkException(exc);
}
void JSCRuntime::setPropertyValue(
jsi::Object& object,
const jsi::String& name,
const jsi::Value& value) {
JSValueRef exc = nullptr;
JSObjectSetProperty(
ctx_,
objectRef(object),
stringRef(name),
valueRef(value),
kJSPropertyAttributeNone,
&exc);
checkException(exc);
}
bool JSCRuntime::isArray(const jsi::Object& obj) const {
#if !defined(_JSC_FAST_IS_ARRAY)
JSObjectRef global = JSContextGetGlobalObject(ctx_);
JSStringRef arrayString = getArrayString();
JSValueRef exc = nullptr;
JSValueRef arrayCtorValue =
JSObjectGetProperty(ctx_, global, arrayString, &exc);
JSC_ASSERT(exc);
JSObjectRef arrayCtor = JSValueToObject(ctx_, arrayCtorValue, &exc);
JSC_ASSERT(exc);
JSStringRef isArrayString = getIsArrayString();
JSValueRef isArrayValue =
JSObjectGetProperty(ctx_, arrayCtor, isArrayString, &exc);
JSC_ASSERT(exc);
JSObjectRef isArray = JSValueToObject(ctx_, isArrayValue, &exc);
JSC_ASSERT(exc);
JSValueRef arg = objectRef(obj);
JSValueRef result =
JSObjectCallAsFunction(ctx_, isArray, nullptr, 1, &arg, &exc);
JSC_ASSERT(exc);
return JSValueToBoolean(ctx_, result);
#else
return JSValueIsArray(ctx_, objectRef(obj));
#endif
}
bool JSCRuntime::isArrayBuffer(const jsi::Object& /*obj*/) const {
// TODO: T23270523 - This would fail on builds that use our custom JSC
// auto typedArrayType = JSValueGetTypedArrayType(ctx_, objectRef(obj),
// nullptr); return typedArrayType == kJSTypedArrayTypeArrayBuffer;
throw std::runtime_error("Unsupported");
}
uint8_t* JSCRuntime::data(const jsi::ArrayBuffer& /*obj*/) {
// TODO: T23270523 - This would fail on builds that use our custom JSC
// return static_cast<uint8_t*>(
// JSObjectGetArrayBufferBytesPtr(ctx_, objectRef(obj), nullptr));
throw std::runtime_error("Unsupported");
}
size_t JSCRuntime::size(const jsi::ArrayBuffer& /*obj*/) {
// TODO: T23270523 - This would fail on builds that use our custom JSC
// return JSObjectGetArrayBufferByteLength(ctx_, objectRef(obj), nullptr);
throw std::runtime_error("Unsupported");
}
bool JSCRuntime::isFunction(const jsi::Object& obj) const {
return JSObjectIsFunction(ctx_, objectRef(obj));
}
bool JSCRuntime::isHostObject(const jsi::Object& obj) const {
auto cls = hostObjectClass;
return cls != nullptr && JSValueIsObjectOfClass(ctx_, objectRef(obj), cls);
}
// Very expensive
jsi::Array JSCRuntime::getPropertyNames(const jsi::Object& obj) {
JSPropertyNameArrayRef names =
JSObjectCopyPropertyNames(ctx_, objectRef(obj));
size_t len = JSPropertyNameArrayGetCount(names);
// Would be better if we could create an array with explicit elements
auto result = createArray(len);
for (size_t i = 0; i < len; i++) {
JSStringRef str = JSPropertyNameArrayGetNameAtIndex(names, i);
result.setValueAtIndex(*this, i, createString(str));
}
JSPropertyNameArrayRelease(names);
return result;
}
jsi::WeakObject JSCRuntime::createWeakObject(const jsi::Object& obj) {
#ifdef RN_FABRIC_ENABLED
// TODO: revisit this implementation
JSObjectRef objRef = objectRef(obj);
return make<jsi::WeakObject>(makeObjectValue(objRef));
#else
throw std::logic_error("Not implemented");
#endif
}
jsi::Value JSCRuntime::lockWeakObject(const jsi::WeakObject& obj) {
#ifdef RN_FABRIC_ENABLED
// TODO: revisit this implementation
JSObjectRef objRef = objectRef(obj);
return jsi::Value(createObject(objRef));
#else
throw std::logic_error("Not implemented");
#endif
}
jsi::Array JSCRuntime::createArray(size_t length) {
JSValueRef exc = nullptr;
JSObjectRef obj = JSObjectMakeArray(ctx_, 0, nullptr, &exc);
checkException(obj, exc);
JSObjectSetProperty(
ctx_,
obj,
getLengthString(),
JSValueMakeNumber(ctx_, static_cast<double>(length)),
0,
&exc);
checkException(exc);
return createObject(obj).getArray(*this);
}
size_t JSCRuntime::size(const jsi::Array& arr) {
return static_cast<size_t>(
getProperty(arr, createPropNameID(getLengthString())).getNumber());
}
jsi::Value JSCRuntime::getValueAtIndex(const jsi::Array& arr, size_t i) {
JSValueRef exc = nullptr;
auto res = JSObjectGetPropertyAtIndex(ctx_, objectRef(arr), (int)i, &exc);
checkException(exc);
return createValue(res);
}
void JSCRuntime::setValueAtIndexImpl(
jsi::Array& arr,
size_t i,
const jsi::Value& value) {
JSValueRef exc = nullptr;
JSObjectSetPropertyAtIndex(ctx_, objectRef(arr), (int)i, valueRef(value), &exc);
checkException(exc);
}
namespace {
std::once_flag hostFunctionClassOnceFlag;
JSClassRef hostFunctionClass{};
class HostFunctionProxy {
public:
HostFunctionProxy(jsi::HostFunctionType hostFunction)
: hostFunction_(hostFunction) {}