forked from rogchap/v8go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
v8go.cc
1712 lines (1425 loc) · 44.3 KB
/
v8go.cc
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 2019 Roger Chapman and the v8go contributors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "v8go.h"
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "_cgo_export.h"
using namespace v8;
auto default_platform = platform::NewDefaultPlatform();
ArrayBuffer::Allocator* default_allocator;
const int ScriptCompilerNoCompileOptions = ScriptCompiler::kNoCompileOptions;
const int ScriptCompilerConsumeCodeCache = ScriptCompiler::kConsumeCodeCache;
const int ScriptCompilerEagerCompile = ScriptCompiler::kEagerCompile;
struct m_ctx {
Isolate* iso;
std::unordered_map<long, m_value*> vals;
std::vector<m_unboundScript*> unboundScripts;
Persistent<Context> ptr;
long nextValId;
};
struct m_value {
long id;
Isolate* iso;
m_ctx* ctx;
Persistent<Value, CopyablePersistentTraits<Value>> ptr;
};
struct m_template {
Isolate* iso;
Persistent<Template> ptr;
};
struct m_unboundScript {
Persistent<UnboundScript> ptr;
};
const char* CopyString(std::string str) {
int len = str.length();
char* mem = (char*)malloc(len + 1);
memcpy(mem, str.data(), len);
mem[len] = 0;
return mem;
}
const char* CopyString(String::Utf8Value& value) {
if (value.length() == 0) {
return nullptr;
}
return CopyString(std::string(*value, value.length()));
}
static RtnError ExceptionError(TryCatch& try_catch,
Isolate* iso,
Local<Context> ctx) {
HandleScope handle_scope(iso);
RtnError rtn = {nullptr, nullptr, nullptr};
if (try_catch.HasTerminated()) {
rtn.msg =
CopyString("ExecutionTerminated: script execution has been terminated");
return rtn;
}
String::Utf8Value exception(iso, try_catch.Exception());
rtn.msg = CopyString(exception);
Local<Message> msg = try_catch.Message();
if (!msg.IsEmpty()) {
String::Utf8Value origin(iso, msg->GetScriptOrigin().ResourceName());
std::ostringstream sb;
sb << *origin;
Maybe<int> line = try_catch.Message()->GetLineNumber(ctx);
if (line.IsJust()) {
sb << ":" << line.ToChecked();
}
Maybe<int> start = try_catch.Message()->GetStartColumn(ctx);
if (start.IsJust()) {
sb << ":"
<< start.ToChecked() + 1; // + 1 to match output from stack trace
}
rtn.location = CopyString(sb.str());
}
Local<Value> mstack;
if (try_catch.StackTrace(ctx).ToLocal(&mstack)) {
String::Utf8Value stack(iso, mstack);
rtn.stack = CopyString(stack);
}
return rtn;
}
m_value* tracked_value(m_ctx* ctx, m_value* val) {
// (rogchap) we track values against a context so that when the context is
// closed (either manually or GC'd by Go) we can also release all the
// values associated with the context;
if (val->id == 0) {
val->id = ++ctx->nextValId;
ctx->vals[val->id] = val;
}
return val;
}
m_unboundScript* tracked_unbound_script(m_ctx* ctx, m_unboundScript* us) {
ctx->unboundScripts.push_back(us);
return us;
}
extern "C" {
/********** Isolate **********/
#define ISOLATE_SCOPE(iso) \
Locker locker(iso); \
Isolate::Scope isolate_scope(iso); \
HandleScope handle_scope(iso);
#define ISOLATE_SCOPE_INTERNAL_CONTEXT(iso) \
ISOLATE_SCOPE(iso); \
m_ctx* ctx = isolateInternalContext(iso);
void Init() {
#ifdef _WIN32
V8::InitializeExternalStartupData(".");
#endif
V8::InitializePlatform(default_platform.get());
V8::Initialize();
default_allocator = ArrayBuffer::Allocator::NewDefaultAllocator();
return;
}
IsolatePtr NewIsolate() {
Isolate::CreateParams params;
params.array_buffer_allocator = default_allocator;
Isolate* iso = Isolate::New(params);
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
iso->SetCaptureStackTraceForUncaughtExceptions(true);
// Create a Context for internal use
m_ctx* ctx = new m_ctx;
ctx->ptr.Reset(iso, Context::New(iso));
ctx->iso = iso;
iso->SetData(0, ctx);
return iso;
}
static inline m_ctx* isolateInternalContext(Isolate* iso) {
return static_cast<m_ctx*>(iso->GetData(0));
}
void IsolatePerformMicrotaskCheckpoint(IsolatePtr iso) {
ISOLATE_SCOPE(iso)
iso->PerformMicrotaskCheckpoint();
}
void IsolateDispose(IsolatePtr iso) {
if (iso == nullptr) {
return;
}
ContextFree(isolateInternalContext(iso));
iso->Dispose();
}
void IsolateTerminateExecution(IsolatePtr iso) {
iso->TerminateExecution();
}
int IsolateIsExecutionTerminating(IsolatePtr iso) {
return iso->IsExecutionTerminating();
}
IsolateHStatistics IsolationGetHeapStatistics(IsolatePtr iso) {
if (iso == nullptr) {
return IsolateHStatistics{0};
}
v8::HeapStatistics hs;
iso->GetHeapStatistics(&hs);
return IsolateHStatistics{hs.total_heap_size(),
hs.total_heap_size_executable(),
hs.total_physical_size(),
hs.total_available_size(),
hs.used_heap_size(),
hs.heap_size_limit(),
hs.malloced_memory(),
hs.external_memory(),
hs.peak_malloced_memory(),
hs.number_of_native_contexts(),
hs.number_of_detached_contexts()};
}
RtnUnboundScript IsolateCompileUnboundScript(IsolatePtr iso,
const char* s,
const char* o,
CompileOptions opts) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
TryCatch try_catch(iso);
Local<Context> local_ctx = ctx->ptr.Get(iso);
Context::Scope context_scope(local_ctx);
RtnUnboundScript rtn = {};
Local<String> src =
String::NewFromUtf8(iso, s, NewStringType::kNormal).ToLocalChecked();
Local<String> ogn =
String::NewFromUtf8(iso, o, NewStringType::kNormal).ToLocalChecked();
ScriptCompiler::CompileOptions option =
static_cast<ScriptCompiler::CompileOptions>(opts.compileOption);
ScriptCompiler::CachedData* cached_data = nullptr;
if (opts.cachedData.data) {
cached_data = new ScriptCompiler::CachedData(opts.cachedData.data,
opts.cachedData.length);
}
ScriptOrigin script_origin(iso, ogn);
ScriptCompiler::Source source(src, script_origin, cached_data);
Local<UnboundScript> unbound_script;
if (!ScriptCompiler::CompileUnboundScript(iso, &source, option)
.ToLocal(&unbound_script)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
};
if (cached_data) {
rtn.cachedDataRejected = cached_data->rejected;
}
m_unboundScript* us = new m_unboundScript;
us->ptr.Reset(iso, unbound_script);
rtn.ptr = tracked_unbound_script(ctx, us);
return rtn;
}
/********** Exceptions & Errors **********/
ValuePtr IsolateThrowException(IsolatePtr iso, ValuePtr value) {
ISOLATE_SCOPE(iso);
m_ctx* ctx = value->ctx;
Local<Value> throw_ret_val = iso->ThrowException(value->ptr.Get(iso));
m_value* new_val = new m_value;
new_val->id = 0;
new_val->iso = iso;
new_val->ctx = ctx;
new_val->ptr =
Persistent<Value, CopyablePersistentTraits<Value>>(iso, throw_ret_val);
return tracked_value(ctx, new_val);
}
/********** CpuProfiler **********/
CPUProfiler* NewCPUProfiler(IsolatePtr iso_ptr) {
Isolate* iso = static_cast<Isolate*>(iso_ptr);
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
CPUProfiler* c = new CPUProfiler;
c->iso = iso;
c->ptr = CpuProfiler::New(iso);
return c;
}
void CPUProfilerDispose(CPUProfiler* profiler) {
if (profiler->ptr == nullptr) {
return;
}
profiler->ptr->Dispose();
delete profiler;
}
void CPUProfilerStartProfiling(CPUProfiler* profiler, const char* title) {
if (profiler->iso == nullptr) {
return;
}
Locker locker(profiler->iso);
Isolate::Scope isolate_scope(profiler->iso);
HandleScope handle_scope(profiler->iso);
Local<String> title_str =
String::NewFromUtf8(profiler->iso, title, NewStringType::kNormal)
.ToLocalChecked();
profiler->ptr->StartProfiling(title_str);
}
CPUProfileNode* NewCPUProfileNode(const CpuProfileNode* ptr_) {
int count = ptr_->GetChildrenCount();
CPUProfileNode** children = new CPUProfileNode*[count];
for (int i = 0; i < count; ++i) {
children[i] = NewCPUProfileNode(ptr_->GetChild(i));
}
CPUProfileNode* root = new CPUProfileNode{
ptr_,
ptr_->GetNodeId(),
ptr_->GetScriptId(),
ptr_->GetScriptResourceNameStr(),
ptr_->GetFunctionNameStr(),
ptr_->GetLineNumber(),
ptr_->GetColumnNumber(),
ptr_->GetHitCount(),
ptr_->GetBailoutReason(),
count,
children,
};
return root;
}
CPUProfile* CPUProfilerStopProfiling(CPUProfiler* profiler, const char* title) {
if (profiler->iso == nullptr) {
return nullptr;
}
Locker locker(profiler->iso);
Isolate::Scope isolate_scope(profiler->iso);
HandleScope handle_scope(profiler->iso);
Local<String> title_str =
String::NewFromUtf8(profiler->iso, title, NewStringType::kNormal)
.ToLocalChecked();
CPUProfile* profile = new CPUProfile;
profile->ptr = profiler->ptr->StopProfiling(title_str);
Local<String> str = profile->ptr->GetTitle();
String::Utf8Value t(profiler->iso, str);
profile->title = CopyString(t);
CPUProfileNode* root = NewCPUProfileNode(profile->ptr->GetTopDownRoot());
profile->root = root;
profile->startTime = profile->ptr->GetStartTime();
profile->endTime = profile->ptr->GetEndTime();
return profile;
}
void CPUProfileNodeDelete(CPUProfileNode* node) {
for (int i = 0; i < node->childrenCount; ++i) {
CPUProfileNodeDelete(node->children[i]);
}
delete[] node->children;
delete node;
}
void CPUProfileDelete(CPUProfile* profile) {
if (profile->ptr == nullptr) {
return;
}
profile->ptr->Delete();
free((void*)profile->title);
CPUProfileNodeDelete(profile->root);
delete profile;
}
/********** Template **********/
#define LOCAL_TEMPLATE(tmpl_ptr) \
Isolate* iso = tmpl_ptr->iso; \
Locker locker(iso); \
Isolate::Scope isolate_scope(iso); \
HandleScope handle_scope(iso); \
Local<Template> tmpl = tmpl_ptr->ptr.Get(iso);
void TemplateFreeWrapper(TemplatePtr tmpl) {
tmpl->ptr.Empty(); // Just does `val_ = 0;` without calling V8::DisposeGlobal
delete tmpl;
}
void TemplateSetValue(TemplatePtr ptr,
const char* name,
ValuePtr val,
int attributes) {
LOCAL_TEMPLATE(ptr);
Local<String> prop_name =
String::NewFromUtf8(iso, name, NewStringType::kNormal).ToLocalChecked();
tmpl->Set(prop_name, val->ptr.Get(iso), (PropertyAttribute)attributes);
}
void TemplateSetTemplate(TemplatePtr ptr,
const char* name,
TemplatePtr obj,
int attributes) {
LOCAL_TEMPLATE(ptr);
Local<String> prop_name =
String::NewFromUtf8(iso, name, NewStringType::kNormal).ToLocalChecked();
tmpl->Set(prop_name, obj->ptr.Get(iso), (PropertyAttribute)attributes);
}
/********** ObjectTemplate **********/
TemplatePtr NewObjectTemplate(IsolatePtr iso) {
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
m_template* ot = new m_template;
ot->iso = iso;
ot->ptr.Reset(iso, ObjectTemplate::New(iso));
return ot;
}
RtnValue ObjectTemplateNewInstance(TemplatePtr ptr, ContextPtr ctx) {
LOCAL_TEMPLATE(ptr);
TryCatch try_catch(iso);
Local<Context> local_ctx = ctx->ptr.Get(iso);
Context::Scope context_scope(local_ctx);
RtnValue rtn = {};
Local<ObjectTemplate> obj_tmpl = tmpl.As<ObjectTemplate>();
Local<Object> obj;
if (!obj_tmpl->NewInstance(local_ctx).ToLocal(&obj)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, obj);
rtn.value = tracked_value(ctx, val);
return rtn;
}
void ObjectTemplateSetInternalFieldCount(TemplatePtr ptr, int field_count) {
LOCAL_TEMPLATE(ptr);
Local<ObjectTemplate> obj_tmpl = tmpl.As<ObjectTemplate>();
obj_tmpl->SetInternalFieldCount(field_count);
}
int ObjectTemplateInternalFieldCount(TemplatePtr ptr) {
LOCAL_TEMPLATE(ptr);
Local<ObjectTemplate> obj_tmpl = tmpl.As<ObjectTemplate>();
return obj_tmpl->InternalFieldCount();
}
/********** FunctionTemplate **********/
static void FunctionTemplateCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* iso = info.GetIsolate();
ISOLATE_SCOPE(iso);
// This callback function can be called from any Context, which we only know
// at runtime. We extract the Context reference from the embedder data so that
// we can use the context registry to match the Context on the Go side
Local<Context> local_ctx = iso->GetCurrentContext();
int ctx_ref = local_ctx->GetEmbedderData(1).As<Integer>()->Value();
m_ctx* ctx = goContext(ctx_ref);
int callback_ref = info.Data().As<Integer>()->Value();
m_value* _this = new m_value;
_this->id = 0;
_this->iso = iso;
_this->ctx = ctx;
_this->ptr.Reset(iso, Persistent<Value, CopyablePersistentTraits<Value>>(
iso, info.This()));
int args_count = info.Length();
ValuePtr thisAndArgs[args_count + 1];
thisAndArgs[0] = tracked_value(ctx, _this);
ValuePtr* args = thisAndArgs + 1;
for (int i = 0; i < args_count; i++) {
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr.Reset(
iso, Persistent<Value, CopyablePersistentTraits<Value>>(iso, info[i]));
args[i] = tracked_value(ctx, val);
}
ValuePtr val =
goFunctionCallback(ctx_ref, callback_ref, thisAndArgs, args_count);
if (val != nullptr) {
info.GetReturnValue().Set(val->ptr.Get(iso));
} else {
info.GetReturnValue().SetUndefined();
}
}
TemplatePtr NewFunctionTemplate(IsolatePtr iso, int callback_ref) {
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
// (rogchap) We only need to store one value, callback_ref, into the
// C++ callback function data, but if we needed to store more items we could
// use an V8::Array; this would require the internal context from
// iso->GetData(0)
Local<Integer> cbData = Integer::New(iso, callback_ref);
m_template* ot = new m_template;
ot->iso = iso;
ot->ptr.Reset(iso,
FunctionTemplate::New(iso, FunctionTemplateCallback, cbData));
return ot;
}
RtnValue FunctionTemplateGetFunction(TemplatePtr ptr, ContextPtr ctx) {
LOCAL_TEMPLATE(ptr);
TryCatch try_catch(iso);
Local<Context> local_ctx = ctx->ptr.Get(iso);
Context::Scope context_scope(local_ctx);
Local<FunctionTemplate> fn_tmpl = tmpl.As<FunctionTemplate>();
RtnValue rtn = {};
Local<Function> fn;
if (!fn_tmpl->GetFunction(local_ctx).ToLocal(&fn)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, fn);
rtn.value = tracked_value(ctx, val);
return rtn;
}
/********** Context **********/
#define LOCAL_CONTEXT(ctx) \
Isolate* iso = ctx->iso; \
Locker locker(iso); \
Isolate::Scope isolate_scope(iso); \
HandleScope handle_scope(iso); \
TryCatch try_catch(iso); \
Local<Context> local_ctx = ctx->ptr.Get(iso); \
Context::Scope context_scope(local_ctx);
ContextPtr NewContext(IsolatePtr iso,
TemplatePtr global_template_ptr,
int ref) {
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
Local<ObjectTemplate> global_template;
if (global_template_ptr != nullptr) {
global_template = global_template_ptr->ptr.Get(iso).As<ObjectTemplate>();
} else {
global_template = ObjectTemplate::New(iso);
}
// For function callbacks we need a reference to the context, but because of
// the complexities of C -> Go function pointers, we store a reference to the
// context as a simple integer identifier; this can then be used on the Go
// side to lookup the context in the context registry. We use slot 1 as slot 0
// has special meaning for the Chrome debugger.
Local<Context> local_ctx = Context::New(iso, nullptr, global_template);
local_ctx->SetEmbedderData(1, Integer::New(iso, ref));
m_ctx* ctx = new m_ctx;
ctx->ptr.Reset(iso, local_ctx);
ctx->iso = iso;
return ctx;
}
int ContextRetainedValueCount(ContextPtr ctx) {
return ctx->vals.size();
}
void ContextFree(ContextPtr ctx) {
if (ctx == nullptr) {
return;
}
ctx->ptr.Reset();
for (auto it = ctx->vals.begin(); it != ctx->vals.end(); ++it) {
auto value = it->second;
value->ptr.Reset();
delete value;
}
ctx->vals.clear();
for (m_unboundScript* us : ctx->unboundScripts) {
us->ptr.Reset();
delete us;
}
delete ctx;
}
RtnValue RunScript(ContextPtr ctx, const char* source, const char* origin) {
LOCAL_CONTEXT(ctx);
RtnValue rtn = {};
MaybeLocal<String> maybeSrc =
String::NewFromUtf8(iso, source, NewStringType::kNormal);
MaybeLocal<String> maybeOgn =
String::NewFromUtf8(iso, origin, NewStringType::kNormal);
Local<String> src, ogn;
if (!maybeSrc.ToLocal(&src) || !maybeOgn.ToLocal(&ogn)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
ScriptOrigin script_origin(iso, ogn);
Local<Script> script;
if (!Script::Compile(local_ctx, src, &script_origin).ToLocal(&script)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
Local<Value> result;
if (!script->Run(local_ctx).ToLocal(&result)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, result);
rtn.value = tracked_value(ctx, val);
return rtn;
}
/********** UnboundScript & ScriptCompilerCachedData **********/
ScriptCompilerCachedData* UnboundScriptCreateCodeCache(
IsolatePtr iso,
UnboundScriptPtr us_ptr) {
ISOLATE_SCOPE(iso);
Local<UnboundScript> unbound_script = us_ptr->ptr.Get(iso);
ScriptCompiler::CachedData* cached_data =
ScriptCompiler::CreateCodeCache(unbound_script);
ScriptCompilerCachedData* cd = new ScriptCompilerCachedData;
cd->ptr = cached_data;
cd->data = cached_data->data;
cd->length = cached_data->length;
cd->rejected = cached_data->rejected;
return cd;
}
void ScriptCompilerCachedDataDelete(ScriptCompilerCachedData* cached_data) {
delete cached_data->ptr;
delete cached_data;
}
// This can only run in contexts that belong to the same isolate
// the script was compiled in
RtnValue UnboundScriptRun(ContextPtr ctx, UnboundScriptPtr us_ptr) {
LOCAL_CONTEXT(ctx)
RtnValue rtn = {};
Local<UnboundScript> unbound_script = us_ptr->ptr.Get(iso);
Local<Script> script = unbound_script->BindToCurrentContext();
Local<Value> result;
if (!script->Run(local_ctx).ToLocal(&result)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, result);
rtn.value = tracked_value(ctx, val);
return rtn;
}
RtnValue JSONParse(ContextPtr ctx, const char* str) {
LOCAL_CONTEXT(ctx);
RtnValue rtn = {};
Local<String> v8Str;
if (!String::NewFromUtf8(iso, str, NewStringType::kNormal).ToLocal(&v8Str)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
}
Local<Value> result;
if (!JSON::Parse(local_ctx, v8Str).ToLocal(&result)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, result);
rtn.value = tracked_value(ctx, val);
return rtn;
}
const char* JSONStringify(ContextPtr ctx, ValuePtr val) {
Isolate* iso;
Local<Context> local_ctx;
if (ctx != nullptr) {
iso = ctx->iso;
} else {
iso = val->iso;
}
Locker locker(iso);
Isolate::Scope isolate_scope(iso);
HandleScope handle_scope(iso);
if (ctx != nullptr) {
local_ctx = ctx->ptr.Get(iso);
} else {
if (val->ctx != nullptr) {
local_ctx = val->ctx->ptr.Get(iso);
} else {
m_ctx* ctx = isolateInternalContext(iso);
local_ctx = ctx->ptr.Get(iso);
}
}
Context::Scope context_scope(local_ctx);
Local<String> str;
if (!JSON::Stringify(local_ctx, val->ptr.Get(iso)).ToLocal(&str)) {
return nullptr;
}
String::Utf8Value json(iso, str);
return CopyString(json);
}
void ValueRelease(ValuePtr ptr) {
if (ptr == nullptr) {
return;
}
ptr->ctx->vals.erase(ptr->id);
ptr->ptr.Reset();
delete ptr;
}
ValuePtr ContextGlobal(ContextPtr ctx) {
LOCAL_CONTEXT(ctx);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, local_ctx->Global());
return tracked_value(ctx, val);
}
/********** Value **********/
#define LOCAL_VALUE(val) \
Isolate* iso = val->iso; \
Locker locker(iso); \
Isolate::Scope isolate_scope(iso); \
HandleScope handle_scope(iso); \
TryCatch try_catch(iso); \
m_ctx* ctx = val->ctx; \
Local<Context> local_ctx; \
if (ctx != nullptr) { \
local_ctx = ctx->ptr.Get(iso); \
} else { \
ctx = isolateInternalContext(iso); \
local_ctx = ctx->ptr.Get(iso); \
} \
Context::Scope context_scope(local_ctx); \
Local<Value> value = val->ptr.Get(iso);
ValuePtr NewValueInteger(IsolatePtr iso, int32_t v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, Integer::New(iso, v));
return tracked_value(ctx, val);
}
ValuePtr NewValueIntegerFromUnsigned(IsolatePtr iso, uint32_t v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, Integer::NewFromUnsigned(iso, v));
return tracked_value(ctx, val);
}
RtnValue NewValueString(IsolatePtr iso, const char* v, int v_length) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
TryCatch try_catch(iso);
RtnValue rtn = {};
Local<String> str;
if (!String::NewFromUtf8(iso, v, NewStringType::kNormal, v_length)
.ToLocal(&str)) {
rtn.error = ExceptionError(try_catch, iso, ctx->ptr.Get(iso));
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, str);
rtn.value = tracked_value(ctx, val);
return rtn;
}
ValuePtr NewValueNull(IsolatePtr iso) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, Null(iso));
return tracked_value(ctx, val);
}
ValuePtr NewValueUndefined(IsolatePtr iso) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr =
Persistent<Value, CopyablePersistentTraits<Value>>(iso, Undefined(iso));
return tracked_value(ctx, val);
}
ValuePtr NewValueBoolean(IsolatePtr iso, int v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, Boolean::New(iso, v));
return tracked_value(ctx, val);
}
ValuePtr NewValueNumber(IsolatePtr iso, double v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, Number::New(iso, v));
return tracked_value(ctx, val);
}
ValuePtr NewValueBigInt(IsolatePtr iso, int64_t v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, BigInt::New(iso, v));
return tracked_value(ctx, val);
}
ValuePtr NewValueBigIntFromUnsigned(IsolatePtr iso, uint64_t v) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(
iso, BigInt::NewFromUnsigned(iso, v));
return tracked_value(ctx, val);
}
RtnValue NewValueBigIntFromWords(IsolatePtr iso,
int sign_bit,
int word_count,
const uint64_t* words) {
ISOLATE_SCOPE_INTERNAL_CONTEXT(iso);
TryCatch try_catch(iso);
Local<Context> local_ctx = ctx->ptr.Get(iso);
RtnValue rtn = {};
Local<BigInt> bigint;
if (!BigInt::NewFromWords(local_ctx, sign_bit, word_count, words)
.ToLocal(&bigint)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
m_value* val = new m_value;
val->id = 0;
val->iso = iso;
val->ctx = ctx;
val->ptr = Persistent<Value, CopyablePersistentTraits<Value>>(iso, bigint);
rtn.value = tracked_value(ctx, val);
return rtn;
}
const uint32_t* ValueToArrayIndex(ValuePtr ptr) {
LOCAL_VALUE(ptr);
Local<Uint32> array_index;
if (!value->ToArrayIndex(local_ctx).ToLocal(&array_index)) {
return nullptr;
}
uint32_t* idx = (uint32_t*)malloc(sizeof(uint32_t));
*idx = array_index->Value();
return idx;
}
int ValueToBoolean(ValuePtr ptr) {
LOCAL_VALUE(ptr);
return value->BooleanValue(iso);
}
int32_t ValueToInt32(ValuePtr ptr) {
LOCAL_VALUE(ptr);
return value->Int32Value(local_ctx).ToChecked();
}
int64_t ValueToInteger(ValuePtr ptr) {
LOCAL_VALUE(ptr);
return value->IntegerValue(local_ctx).ToChecked();
}
double ValueToNumber(ValuePtr ptr) {
LOCAL_VALUE(ptr);
return value->NumberValue(local_ctx).ToChecked();
}
RtnString ValueToDetailString(ValuePtr ptr) {
LOCAL_VALUE(ptr);
RtnString rtn = {0};
Local<String> str;
if (!value->ToDetailString(local_ctx).ToLocal(&str)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
}
String::Utf8Value ds(iso, str);
rtn.data = CopyString(ds);
rtn.length = ds.length();
return rtn;
}
RtnString ValueToString(ValuePtr ptr) {
LOCAL_VALUE(ptr);
RtnString rtn = {0};
// String::Utf8Value will result in an empty string if conversion to a string
// fails
// TODO: Consider propagating the JS error. A fallback value could be returned
// in Value.String()
String::Utf8Value src(iso, value);
char* data = static_cast<char*>(malloc(src.length()));