-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathV8Runtime.cpp
More file actions
1589 lines (1350 loc) · 55.9 KB
/
V8Runtime.cpp
File metadata and controls
1589 lines (1350 loc) · 55.9 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) Kudo Chien.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "V8Runtime.h"
#include "runtime/Runtime.h"
#include "runtime/Helpers.h"
#include "v8.h"
// #include <glog/logging.h>
#include <filesystem>
#include <mutex>
#include <sstream>
#include "HostProxy.h"
#include "JSIV8ValueConverter.h"
// #include "V8Inspector.h"
#include "V8PointerValue.h"
#include "jsi/jsilib.h"
namespace jsi = facebook::jsi;
namespace rnv8 {
namespace {
const char kHostFunctionProxyProp[] = "__hostFunctionProxy";
} // namespace
// static
std::unique_ptr<v8::Platform> V8Runtime::s_platform = nullptr;
std::mutex s_platform_mutex; // protects s_platform
V8Runtime::V8Runtime() {
isolate_ = tns::Runtime::GetCurrentRuntime()->GetIsolate();
// V8Runtime::V8Runtime(
// std::unique_ptr<V8RuntimeConfig> config,
// std::shared_ptr<facebook::react::MessageQueueThread> jsQueue)
// : config_(std::move(config)) {
// {
// const std::lock_guard<std::mutex> lock(s_platform_mutex);
// if (!s_platform) {
// s_platform = v8::platform::NewDefaultPlatform();
// v8::V8::InitializeICU();
// v8::V8::InitializePlatform(s_platform.get());
// #if TARGET_OS_IOS
// v8::V8::SetFlagsFromString("--nolazy --nofreeze_flags_after_init");
// #else
// v8::V8::SetFlagsFromString("--nolazy");
// #endif
// v8::V8::Initialize();
// }
// }
// if (config_->snapshotBlob) {
// snapshotBlob_ = std::make_unique<v8::StartupData>();
// snapshotBlob_->data = config_->snapshotBlob->c_str();
// snapshotBlob_->raw_size =
// static_cast<int>(config_->snapshotBlob->size());
// createParams.snapshot_blob = snapshotBlob_.get();
// }
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
context_.Reset(isolate_, isolate_->GetCurrentContext());
v8::Context::Scope scopedContext(context_.Get(isolate_));
arrayBufferAllocator_.reset(
v8::ArrayBuffer::Allocator::NewDefaultAllocator());
// jsQueue_ = jsQueue;
// if (config_->enableInspector) {
// inspectorClient_ = std::make_shared<InspectorClient>(
// jsQueue_,
// context_.Get(isolate_),
// config_->appName,
// config_->deviceName);
// inspectorClient_->ConnectToReactFrontend();
// }
}
// V8Runtime::V8Runtime(const V8Runtime* v8Runtime,
// std::unique_ptr<V8RuntimeConfig> config)
// : config_(std::move(config)) {
// arrayBufferAllocator_.reset(
// v8::ArrayBuffer::Allocator::NewDefaultAllocator());
// v8::Isolate::CreateParams createParams;
// createParams.array_buffer_allocator = arrayBufferAllocator_.get();
// if (v8Runtime->config_->snapshotBlob) {
// snapshotBlob_ = std::make_unique<v8::StartupData>();
// snapshotBlob_->data = v8Runtime->config_->snapshotBlob->c_str();
// snapshotBlob_->raw_size =
// static_cast<int>(v8Runtime->config_->snapshotBlob->size());
// createParams.snapshot_blob = snapshotBlob_.get();
// }
// config_->codecacheMode = V8RuntimeConfig::CodecacheMode::kNone;
// isolate_ = v8::Isolate::New(createParams);
// #if defined(__ANDROID__)
// if (!v8Runtime->config_->timezoneId.empty()) {
// isolate_->DateTimeConfigurationChangeNotification(
// v8::Isolate::TimeZoneDetection::kCustom,
// v8Runtime->config_->timezoneId.c_str());
// }
// #endif
// v8::Locker locker(isolate_);
// v8::Isolate::Scope scopedIsolate(isolate_);
// v8::HandleScope scopedHandle(isolate_);
// context_.Reset(isolate_, CreateGlobalContext(isolate_));
// v8::Context::Scope scopedContext(context_.Get(isolate_));
// // jsQueue_ = v8Runtime->jsQueue_;
// // if (config_->enableInspector) {
// // inspectorClient_ = std::make_shared<InspectorClient>(
// // jsQueue_,
// // context_.Get(isolate_),
// // config_->appName,
// // config_->deviceName);
// // inspectorClient_->ConnectToReactFrontend();
// // }
// #if 0 // Experimental shared global context
// isSharedRuntime_ = true;
// isolate_ = v8Runtime->isolate_;
// // jsQueue_ = v8Runtime->jsQueue_;
// v8::Locker locker(isolate_);
// v8::Isolate::Scope scopedIsolate(isolate_);
// v8::HandleScope scopedHandle(isolate_);
// context_.Reset(isolate_, CreateGlobalContext(isolate_));
// auto localContext = context_.Get(isolate_);
// localContext->SetSecurityToken(
// v8Runtime->context_.Get(isolate_)->GetSecurityToken());
// bool inheritProtoResult =
// localContext->Global()
// ->GetPrototype()
// .As<v8::Object>()
// ->SetPrototype(
// localContext,
// v8Runtime->context_.Get(isolate_)->Global()->GetPrototype())
// .FromJust();
// if (!inheritProtoResult) {
// LOG(ERROR) << "Unable to inherit prototype from parent shared runtime.";
// }
// // if (config_->enableInspector) {
// // inspectorClient_ = std::make_shared<InspectorClient>(
// // jsQueue_,
// // context_.Get(isolate_),
// // config_->appName,
// // config_->deviceName);
// // inspectorClient_->ConnectToReactFrontend();
// // }
// #endif
// }
V8Runtime::~V8Runtime() {
{
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
if (inspectorClient_) {
inspectorClient_.reset();
}
context_.Reset();
}
if (!isSharedRuntime_) {
isolate_->Dispose();
}
// v8::V8::Dispose();
// v8::V8::DisposePlatform();
}
void V8Runtime::OnMainLoopIdle() {
// v8::Locker locker(isolate_);
// v8::Isolate::Scope scopedIsolate(isolate_);
// v8::HandleScope scopedHandle(isolate_);
// v8::Context::Scope scopedContext(context_.Get(isolate_));
// while (v8::platform::PumpMessageLoop(
// s_platform.get(), isolate_,
// v8::platform::MessageLoopBehavior::kDoNotWait)) {
// continue;
// }
}
// v8::Local<v8::Context> V8Runtime::CreateGlobalContext(v8::Isolate* isolate) {
// v8::HandleScope scopedHandle(isolate);
// v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_);
// global->Set(
// v8::String::NewFromUtf8(isolate, "_v8runtime",
// v8::NewStringType::kNormal)
// .ToLocalChecked(),
// v8::FunctionTemplate::New(isolate, V8Runtime::GetRuntimeInfo));
// return v8::Context::New(isolate_, nullptr, global);
// }
// jsi::Value V8Runtime::ExecuteScript(v8::Isolate* isolate,
// const v8::Local<v8::String>& script,
// const std::string& sourceURL) {
// v8::HandleScope scopedHandle(isolate);
// v8::TryCatch tryCatch(isolate);
// v8::MaybeLocal<v8::String> sourceURLValue = v8::String::NewFromUtf8(
// isolate, sourceURL.c_str(), v8::NewStringType::kNormal,
// static_cast<int>(sourceURL.length()));
// v8::ScriptOrigin origin(isolate, sourceURLValue.ToLocalChecked());
// v8::Local<v8::Context> context(isolate->GetCurrentContext());
// auto codecache = LoadCodeCacheIfNeeded(sourceURL);
// v8::ScriptCompiler::CachedData* cachedData = codecache.release();
// std::unique_ptr<v8::ScriptCompiler::Source> source =
// UseFakeSourceIfNeeded(origin, cachedData);
// if (!source) {
// source = std::make_unique<v8::ScriptCompiler::Source>(script, origin,
// cachedData);
// }
// v8::Local<v8::Script> compiledScript;
// if (!v8::ScriptCompiler::Compile(context, source.release(),
// cachedData
// ?
// v8::ScriptCompiler::kConsumeCodeCache
// :
// v8::ScriptCompiler::kNoCompileOptions)
// .ToLocal(&compiledScript)) {
// ReportException(isolate, &tryCatch);
// return {};
// }
// if (cachedData && cachedData->rejected) {
// LOG(INFO) << "[rnv8] cache miss: " << sourceURL;
// }
// SaveCodeCacheIfNeeded(compiledScript, sourceURL, cachedData);
// v8::Local<v8::Value> result;
// if (!compiledScript->Run(context).ToLocal(&result)) {
// assert(tryCatch.HasCaught());
// ReportException(isolate, &tryCatch);
// return {};
// }
// return JSIV8ValueConverter::ToJSIValue(isolate, result);
// }
void V8Runtime::ReportException(v8::Isolate* isolate,
v8::TryCatch* tryCatch) const {
v8::HandleScope scopedHandle(isolate);
std::string exception =
JSIV8ValueConverter::ToSTLString(isolate, tryCatch->Exception());
v8::Local<v8::Message> message = tryCatch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
throw jsi::JSError(const_cast<V8Runtime&>(*this), exception);
return;
} else {
std::ostringstream ss;
v8::Local<v8::Context> context(isolate->GetCurrentContext());
// Print (filename):(line number): (message).
ss << JSIV8ValueConverter::ToSTLString(
isolate, message->GetScriptOrigin().ResourceName())
<< ":" << message->GetLineNumber(context).FromJust() << ": " << exception
<< std::endl;
// Print line of source code.
ss << JSIV8ValueConverter::ToSTLString(
isolate, message->GetSourceLine(context).ToLocalChecked())
<< std::endl;
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn(context).FromJust();
for (int i = 0; i < start; i++) {
ss << " ";
}
int end = message->GetEndColumn(context).FromJust();
for (int i = start; i < end; i++) {
ss << "^";
}
ss << std::endl;
v8::Local<v8::Value> stackTraceString;
if (tryCatch->StackTrace(context).ToLocal(&stackTraceString) &&
stackTraceString->IsString() &&
v8::Local<v8::String>::Cast(stackTraceString)->Length() > 0) {
v8::String::Utf8Value stackTrace(isolate, stackTraceString);
std::string stlStack = JSIV8ValueConverter::ToSTLString(stackTrace);
// Reverted: do not remap stack here
ss << stlStack << std::endl;
}
throw jsi::JSError(const_cast<V8Runtime&>(*this), ss.str());
return;
}
}
// std::unique_ptr<v8::ScriptCompiler::CachedData>
// V8Runtime::LoadCodeCacheIfNeeded(const std::string& sourceURL) {
// // caching is for main runtime only
// if (isSharedRuntime_) {
// return nullptr;
// }
// if (config_->codecacheMode == V8RuntimeConfig::CodecacheMode::kNone) {
// return nullptr;
// }
// std::filesystem::path codecachePath(config_->codecacheDir);
// codecachePath /= std::filesystem::path(sourceURL).filename();
// auto* file = std::fopen(codecachePath.string().c_str(), "rb");
// if (!file) {
// LOG(INFO) << "Cannot load codecache file: " << codecachePath.string();
// return nullptr;
// }
// std::fseek(file, 0, SEEK_END);
// size_t size = std::ftell(file);
// uint8_t* buffer = new uint8_t[size];
// std::rewind(file);
// std::fread(buffer, size, 1, file);
// std::fclose(file);
// return std::make_unique<v8::ScriptCompiler::CachedData>(
// buffer, static_cast<int>(size),
// v8::ScriptCompiler::CachedData::BufferPolicy::BufferOwned);
// }
// bool V8Runtime::SaveCodeCacheIfNeeded(
// const v8::Local<v8::Script>& script, const std::string& sourceURL,
// v8::ScriptCompiler::CachedData* cachedData) {
// // caching is for main runtime only
// if (isSharedRuntime_) {
// return false;
// }
// if (cachedData && !cachedData->rejected) {
// return false;
// }
// if (config_->codecacheMode == V8RuntimeConfig::CodecacheMode::kNone) {
// return false;
// }
// v8::HandleScope scopedHandle(isolate_);
// v8::Local<v8::UnboundScript> unboundScript = script->GetUnboundScript();
// std::unique_ptr<v8::ScriptCompiler::CachedData> newCachedData;
// newCachedData.reset(v8::ScriptCompiler::CreateCodeCache(unboundScript));
// if (!newCachedData) {
// return false;
// }
// std::filesystem::path codecachePath(config_->codecacheDir);
// codecachePath /= std::filesystem::path(sourceURL).filename();
// if (auto* file = std::fopen(codecachePath.string().c_str(), "wb")) {
// std::fwrite(newCachedData->data, 1, newCachedData->length, file);
// std::fclose(file);
// return true;
// } else {
// LOG(ERROR) << "Cannot save codecache file: " << codecachePath.string();
// return false;
// }
// }
// std::unique_ptr<v8::ScriptCompiler::Source> V8Runtime::UseFakeSourceIfNeeded(
// const v8::ScriptOrigin& origin,
// v8::ScriptCompiler::CachedData* cachedData) {
// // caching is for main runtime only
// if (isSharedRuntime_) {
// return nullptr;
// }
// if (!cachedData) {
// return nullptr;
// }
// if (config_->codecacheMode == V8RuntimeConfig::CodecacheMode::kStubBundle)
// {
// uint32_t payloadSize =
// (cachedData->data[8] << 0) | (cachedData->data[9] << 8) |
// (cachedData->data[10] << 16) | (cachedData->data[11] << 24);
// std::string stubScriptString(payloadSize, ' ');
// v8::Local<v8::String> stubScript =
// v8::String::NewFromUtf8(isolate_, stubScriptString.c_str())
// .ToLocalChecked();
// return std::make_unique<v8::ScriptCompiler::Source>(stubScript, origin,
// cachedData);
// }
// return nullptr;
// }
V8Runtime::InternalFieldType V8Runtime::GetInternalFieldType(
v8::Local<v8::Object> object) const {
if (object->InternalFieldCount() != 2) {
return V8Runtime::InternalFieldType::kInvalid;
}
v8::Local<v8::Value> typeValue = object->GetInternalField(0);
assert(typeValue->IsUint32());
return static_cast<V8Runtime::InternalFieldType>(
v8::Local<v8::Uint32>::Cast(typeValue)->Value());
}
// static
v8::Platform* V8Runtime::GetPlatform() { return s_platform.get(); }
//
// jsi::Runtime implementations
//
jsi::Value V8Runtime::evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer>& buffer,
const std::string& sourceURL) {
return {};
}
std::shared_ptr<const jsi::PreparedJavaScript> V8Runtime::prepareJavaScript(
const std::shared_ptr<const jsi::Buffer>& buffer, std::string sourceURL) {
return nullptr;
}
jsi::Value V8Runtime::evaluatePreparedJavaScript(
const std::shared_ptr<const jsi::PreparedJavaScript>& js) {
return evaluateJavaScript(nullptr, nullptr);
}
void V8Runtime::queueMicrotask(const jsi::Function& callback) {
// TODO: add this when we revisit new architecture support
}
bool V8Runtime::drainMicrotasks(int maxMicrotasksHint) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
while (v8::platform::PumpMessageLoop(
s_platform.get(), isolate_,
v8::platform::MessageLoopBehavior::kDoNotWait)) {
continue;
}
isolate_->PerformMicrotaskCheckpoint();
return true;
}
jsi::Object V8Runtime::global() {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
return make<jsi::Object>(
new V8PointerValue(isolate_, context_.Get(isolate_)->Global()));
}
std::string V8Runtime::description() {
std::ostringstream ss;
ss << "<V8Runtime@" << this << ">";
return ss.str();
}
bool V8Runtime::isInspectable() { return false; }
// These clone methods are shallow clone
jsi::Runtime::PointerValue* V8Runtime::cloneSymbol(
const Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue = static_cast<const V8PointerValue*>(pv);
assert(v8PointerValue->Get(isolate_)->IsSymbol());
return new V8PointerValue(isolate_, v8PointerValue->Get(isolate_));
}
jsi::Runtime::PointerValue* V8Runtime::cloneBigInt(
const Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue = static_cast<const V8PointerValue*>(pv);
assert(v8PointerValue->Get(isolate_)->IsBigInt());
return new V8PointerValue(isolate_, v8PointerValue->Get(isolate_));
}
jsi::Runtime::PointerValue* V8Runtime::cloneString(
const Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue = static_cast<const V8PointerValue*>(pv);
assert(v8PointerValue->Get(isolate_)->IsString());
return new V8PointerValue(isolate_, v8PointerValue->Get(isolate_));
}
jsi::Runtime::PointerValue* V8Runtime::cloneObject(
const Runtime::PointerValue* pv) {
if (!pv) {
return nullptr;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue = static_cast<const V8PointerValue*>(pv);
assert(v8PointerValue->Get(isolate_)->IsObject());
return new V8PointerValue(isolate_, v8PointerValue->Get(isolate_));
}
jsi::Runtime::PointerValue* V8Runtime::clonePropNameID(
const Runtime::PointerValue* pv) {
return cloneString(pv);
}
jsi::PropNameID V8Runtime::createPropNameIDFromAscii(const char* str,
size_t length) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
V8PointerValue* value =
V8PointerValue::createFromOneByte(isolate_, str, length);
if (!value) {
throw jsi::JSError(*this, "createFromOneByte() - string creation failed.");
}
return make<jsi::PropNameID>(value);
}
jsi::PropNameID V8Runtime::createPropNameIDFromUtf8(const uint8_t* utf8,
size_t length) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
V8PointerValue* value =
V8PointerValue::createFromUtf8(isolate_, utf8, length);
if (!value) {
throw jsi::JSError(*this, "createFromUtf8() - string creation failed.");
}
return make<jsi::PropNameID>(value);
}
jsi::PropNameID V8Runtime::createPropNameIDFromString(const jsi::String& str) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(str));
assert(v8PointerValue->Get(isolate_)->IsString());
v8::String::Utf8Value utf8(isolate_, v8PointerValue->Get(isolate_));
return createPropNameIDFromUtf8(reinterpret_cast<const uint8_t*>(*utf8),
utf8.length());
}
jsi::PropNameID V8Runtime::createPropNameIDFromSymbol(
const facebook::jsi::Symbol& sym) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
assert(static_cast<const V8PointerValue*>(getPointerValue(sym))
->Get(isolate_)
->IsSymbol());
return make<jsi::PropNameID>(const_cast<PointerValue*>(getPointerValue(sym)));
}
std::string V8Runtime::utf8(const jsi::PropNameID& sym) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(sym));
v8::String::Utf8Value utf8(isolate_, v8PointerValue->Get(isolate_));
return JSIV8ValueConverter::ToSTLString(utf8);
}
bool V8Runtime::compare(const jsi::PropNameID& a, const jsi::PropNameID& b) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValueA =
static_cast<const V8PointerValue*>(getPointerValue(a));
const V8PointerValue* v8PointerValueB =
static_cast<const V8PointerValue*>(getPointerValue(b));
v8::Local<v8::String> v8StringA =
v8::Local<v8::String>::Cast(v8PointerValueA->Get(isolate_));
v8::Local<v8::String> v8StringB =
v8::Local<v8::String>::Cast(v8PointerValueB->Get(isolate_));
return v8StringA->StringEquals(v8StringB);
}
std::string V8Runtime::symbolToString(const jsi::Symbol& symbol) {
return jsi::Value(*this, symbol).toString(*this).utf8(*this);
}
jsi::BigInt V8Runtime::createBigIntFromInt64(int64_t value) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::BigInt> v8BigInt = v8::BigInt::New(isolate_, value);
return make<jsi::BigInt>(new V8PointerValue(isolate_, v8BigInt));
}
jsi::BigInt V8Runtime::createBigIntFromUint64(uint64_t value) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::BigInt> v8BigInt = v8::BigInt::NewFromUnsigned(isolate_, value);
return make<jsi::BigInt>(new V8PointerValue(isolate_, v8BigInt));
}
bool V8Runtime::bigintIsInt64(const jsi::BigInt& value) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(value));
assert(v8PointerValue->Get(isolate_)->IsBigInt());
v8::Local<v8::BigInt> v8BigInt =
v8::Local<v8::BigInt>::Cast(v8PointerValue->Get(isolate_));
bool lossless = false;
v8BigInt->Int64Value(&lossless);
return lossless == true;
}
bool V8Runtime::bigintIsUint64(const jsi::BigInt& value) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(value));
assert(v8PointerValue->Get(isolate_)->IsBigInt());
v8::Local<v8::BigInt> v8BigInt =
v8::Local<v8::BigInt>::Cast(v8PointerValue->Get(isolate_));
bool lossless = false;
v8BigInt->Uint64Value(&lossless);
return lossless == true;
}
uint64_t V8Runtime::truncate(const jsi::BigInt& value) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(value));
assert(v8PointerValue->Get(isolate_)->IsBigInt());
v8::Local<v8::BigInt> v8BigInt =
v8::Local<v8::BigInt>::Cast(v8PointerValue->Get(isolate_));
return v8BigInt->Uint64Value();
}
jsi::String V8Runtime::bigintToString(const jsi::BigInt& value, int radix) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(value));
assert(v8PointerValue->Get(isolate_)->IsBigInt());
v8::Local<v8::BigInt> v8Value =
v8::Local<v8::BigInt>::Cast(v8PointerValue->Get(isolate_));
// V8 does not expose `toString(radix)` in its API, so we have to use
// `BigInt.prototype.toString.call(value, radix)` instead.
v8::Local<v8::Object> global = context_.Get(isolate_)->Global();
v8::Local<v8::Object> bigintClass = v8::Local<v8::Object>::Cast(
global
->Get(isolate_->GetCurrentContext(),
v8::String::NewFromUtf8Literal(isolate_, "BigInt"))
.ToLocalChecked());
v8::Local<v8::Object> bigintProto = v8::Local<v8::Object>::Cast(
bigintClass
->Get(isolate_->GetCurrentContext(),
v8::String::NewFromUtf8Literal(isolate_, "prototype"))
.ToLocalChecked());
v8::Local<v8::Function> bigintToStringFunction =
v8::Local<v8::Function>::Cast(
bigintProto
->Get(isolate_->GetCurrentContext(),
v8::String::NewFromUtf8Literal(isolate_, "toString"))
.ToLocalChecked());
v8::Local<v8::Value> args[] = {v8::Integer::New(isolate_, radix)};
v8::Local<v8::Value> result =
bigintToStringFunction
->Call(isolate_->GetCurrentContext(), v8Value, 1, args)
.ToLocalChecked();
assert(result->IsString());
return V8Runtime::make<jsi::String>(new V8PointerValue(isolate_, result));
}
jsi::String V8Runtime::createStringFromAscii(const char* str, size_t length) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
V8PointerValue* value =
V8PointerValue::createFromOneByte(isolate_, str, length);
if (!value) {
throw jsi::JSError(*this, "createFromOneByte() - string creation failed.");
}
return make<jsi::String>(value);
}
jsi::String V8Runtime::createStringFromUtf8(const uint8_t* str, size_t length) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
V8PointerValue* value = V8PointerValue::createFromUtf8(isolate_, str, length);
if (!value) {
throw jsi::JSError(*this, "createFromUtf8() - string creation failed.");
}
return make<jsi::String>(value);
}
std::string V8Runtime::utf8(const jsi::String& str) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(str));
assert(v8PointerValue->Get(isolate_)->IsString());
v8::String::Utf8Value utf8(isolate_, v8PointerValue->Get(isolate_));
return JSIV8ValueConverter::ToSTLString(utf8);
}
jsi::Object V8Runtime::createObject() {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::Object> object = v8::Object::New(isolate_);
return make<jsi::Object>(new V8PointerValue(isolate_, object));
}
jsi::Object V8Runtime::createObject(
std::shared_ptr<jsi::HostObject> hostObject) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
HostObjectProxy* hostObjectProxy =
new HostObjectProxy(*this, isolate_, hostObject);
v8::Local<v8::Object> v8Object;
v8::Local<v8::ObjectTemplate> hostObjectTemplate =
v8::ObjectTemplate::New(isolate_);
hostObjectTemplate->SetHandler(v8::NamedPropertyHandlerConfiguration(
HostObjectProxy::Getter, HostObjectProxy::Setter, nullptr, nullptr,
HostObjectProxy::Enumerator));
hostObjectTemplate->SetInternalFieldCount(2);
if (!hostObjectTemplate->NewInstance(isolate_->GetCurrentContext())
.ToLocal(&v8Object)) {
delete hostObjectProxy;
throw jsi::JSError(*this, "Unable to create HostObject");
}
v8::Local<v8::External> wrappedHostObjectProxy =
v8::External::New(isolate_, hostObjectProxy);
v8Object->SetInternalField(0, v8::Integer::NewFromUnsigned(
isolate_, InternalFieldType::kHostObject));
v8Object->SetInternalField(1, wrappedHostObjectProxy);
hostObjectProxy->BindFinalizer(v8Object);
return make<jsi::Object>(new V8PointerValue(isolate_, v8Object));
}
std::shared_ptr<jsi::HostObject> V8Runtime::getHostObject(
const jsi::Object& object) {
assert(isHostObject(object));
// We are guarenteed at this point to have isHostObject(obj) == true
// so the internal data should be HostObjectMetadata
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::Object> v8Object =
JSIV8ValueConverter::ToV8Object(*this, object);
v8::Local<v8::External> internalField =
v8::Local<v8::External>::Cast(v8Object->GetInternalField(1));
HostObjectProxy* hostObjectProxy =
reinterpret_cast<HostObjectProxy*>(internalField->Value());
assert(hostObjectProxy);
return hostObjectProxy->GetHostObject();
}
jsi::HostFunctionType& V8Runtime::getHostFunction(
const jsi::Function& function) {
assert(isHostFunction(function));
// We know that isHostFunction(function) is true here, so its safe to proceed
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
const V8PointerValue* v8PointerValue =
static_cast<const V8PointerValue*>(getPointerValue(function));
assert(v8PointerValue->Get(isolate_)->IsFunction());
v8::Local<v8::Function> v8Function =
v8::Local<v8::Function>::Cast(v8PointerValue->Get(isolate_));
v8::Local<v8::String> prop =
v8::String::NewFromUtf8(isolate_, kHostFunctionProxyProp,
v8::NewStringType::kNormal)
.ToLocalChecked();
v8::Local<v8::External> wrappedHostFunctionProxy =
v8::Local<v8::External>::Cast(
v8Function->Get(isolate_->GetCurrentContext(), prop)
.ToLocalChecked());
HostFunctionProxy* hostFunctionProxy =
reinterpret_cast<HostFunctionProxy*>(wrappedHostFunctionProxy->Value());
assert(hostFunctionProxy);
return hostFunctionProxy->GetHostFunction();
}
bool V8Runtime::hasNativeState(const jsi::Object& object) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::Object> v8Object =
JSIV8ValueConverter::ToV8Object(*this, object);
return GetInternalFieldType(v8Object) == InternalFieldType::kNativeState;
}
std::shared_ptr<jsi::NativeState> V8Runtime::getNativeState(
const jsi::Object& object) {
if (isHostObject(object)) {
throw jsi::JSINativeException("native state unsupported on HostObject");
}
assert(hasNativeState(object));
// We are guarenteed at this point to have hasNativeState(obj) == true
// so the internal data should be a NativeState
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::Object> v8Object =
JSIV8ValueConverter::ToV8Object(*this, object);
auto* nativeStatePtr = reinterpret_cast<std::shared_ptr<jsi::NativeState>*>(
v8Object->GetAlignedPointerFromInternalField(1));
return std::shared_ptr(*nativeStatePtr);
}
void V8Runtime::setNativeState(const jsi::Object& object,
std::shared_ptr<jsi::NativeState> state) {
if (isHostObject(object)) {
throw jsi::JSINativeException("native state unsupported on HostObject");
}
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::Local<v8::Object> v8ObjectOriginal =
JSIV8ValueConverter::ToV8Object(*this, object);
v8::Local<v8::ObjectTemplate> objectTemplate =
v8::ObjectTemplate::New(isolate_);
objectTemplate->SetInternalFieldCount(2);
v8::Local<v8::Object> v8Object;
if (!objectTemplate->NewInstance(isolate_->GetCurrentContext())
.ToLocal(&v8Object)) {
throw jsi::JSError(*this, "Unable to create new Object for setNativeState");
}
V8PointerValue* v8PointerValue = static_cast<V8PointerValue*>(
const_cast<Runtime::PointerValue*>(getPointerValue(object)));
v8PointerValue->Reset(isolate_, v8Object);
v8Object->SetInternalField(0, v8::Integer::NewFromUnsigned(
isolate_, InternalFieldType::kNativeState));
// Allocate a shared_ptr on the C++ heap and use it as context of NativeState.
auto* nativeStatePtr =
new std::shared_ptr<jsi::NativeState>(std::move(state));
v8Object->SetAlignedPointerInInternalField(
1, reinterpret_cast<void*>(nativeStatePtr));
// Clone properties to the new object created from object template with
// two internal fields.
v8::Local<v8::Object> global = context_.Get(isolate_)->Global();
v8::Local<v8::Object> objectClass = v8::Local<v8::Object>::Cast(
global
->Get(isolate_->GetCurrentContext(),
v8::String::NewFromUtf8Literal(isolate_, "Object"))
.ToLocalChecked());
v8::Local<v8::Function> objectAssignFunction = v8::Local<v8::Function>::Cast(
objectClass
->Get(isolate_->GetCurrentContext(),
v8::String::NewFromUtf8Literal(isolate_, "assign"))
.ToLocalChecked());
v8::Local<v8::Value> args[] = {v8Object, v8ObjectOriginal};
objectAssignFunction
->Call(isolate_->GetCurrentContext(), v8::Undefined(isolate_), 2, args)
.ToLocalChecked();
// Bind a global handle with weak callback to cleanup the shared_ptr
// on the C++ heap.
v8::Global<v8::Object> weakV8Object(isolate_, v8Object);
weakV8Object.SetWeak(
&weakV8Object,
[](const v8::WeakCallbackInfo<v8::Global<v8::Object>>& data) {
v8::Global<v8::Object>* weakV8ObjectPtr = data.GetParameter();
weakV8ObjectPtr->Reset();
delete reinterpret_cast<std::shared_ptr<jsi::NativeState>*>(
data.GetInternalField(1));
},
v8::WeakCallbackType::kInternalFields);
}
jsi::Value V8Runtime::getProperty(const jsi::Object& object,
const jsi::PropNameID& name) {
v8::Locker locker(isolate_);
v8::Isolate::Scope scopedIsolate(isolate_);
v8::HandleScope scopedHandle(isolate_);
v8::Context::Scope scopedContext(context_.Get(isolate_));
v8::TryCatch tryCatch(isolate_);
v8::Local<v8::Object> v8Object =
JSIV8ValueConverter::ToV8Object(*this, object);
v8::MaybeLocal<v8::Value> result =
v8Object->Get(isolate_->GetCurrentContext(),
JSIV8ValueConverter::ToV8String(*this, name));
if (tryCatch.HasCaught()) {
ReportException(isolate_, &tryCatch);
}
if (result.IsEmpty()) {
return jsi::Value::undefined();
}
return JSIV8ValueConverter::ToJSIValue(isolate_, result.ToLocalChecked());
}