-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathmini_racer_v8.cc
840 lines (805 loc) · 31.3 KB
/
mini_racer_v8.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
#include "v8.h"
#include "v8-profiler.h"
#include "libplatform/libplatform.h"
#include "mini_racer_v8.h"
#include <memory>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <vector>
struct Callback
{
struct State *st;
int32_t id;
};
// NOTE: do *not* use thread_locals to store state. In single-threaded
// mode, V8 runs on the same thread as Ruby and the Ruby runtime clobbers
// thread-locals when it context-switches threads. Ruby 3.4.0 has a new
// API rb_thread_lock_native_thread() that pins the thread but I don't
// think we're quite ready yet to drop support for older versions, hence
// this inelegant "everything" struct.
struct State
{
v8::Isolate *isolate;
// declaring as Local is safe because we take special care
// to ensure it's rooted in a HandleScope before being used
v8::Local<v8::Context> context;
// extra context for when we need access to built-ins like Array
// and want to be sure they haven't been tampered with by JS code
v8::Local<v8::Context> safe_context;
v8::Persistent<v8::Context> persistent_context; // single-thread mode only
v8::Persistent<v8::Context> persistent_safe_context; // single-thread mode only
v8::Persistent<v8::Object> persistent_webassembly_instance;
v8::Local<v8::Object> webassembly_instance;
Context *ruby_context;
int64_t max_memory;
int err_reason;
bool verbose_exceptions;
std::vector<Callback*> callbacks;
std::unique_ptr<v8::ArrayBuffer::Allocator> allocator;
inline ~State();
};
namespace {
// deliberately leaked on program exit,
// not safe to destroy after main() returns
v8::Platform *platform;
struct Serialized
{
uint8_t *data = nullptr;
size_t size = 0;
Serialized(State& st, v8::Local<v8::Value> v)
{
v8::ValueSerializer ser(st.isolate);
ser.WriteHeader();
if (!ser.WriteValue(st.context, v).FromMaybe(false)) return; // exception pending
auto pair = ser.Release();
data = pair.first;
size = pair.second;
}
~Serialized()
{
free(data);
}
};
// throws JS exception on serialization error
bool reply(State& st, v8::Local<v8::Value> v)
{
Serialized serialized(st, v);
if (serialized.data)
v8_reply(st.ruby_context, serialized.data, serialized.size);
return serialized.data != nullptr; // exception pending if false
}
v8::Local<v8::Value> sanitize(State& st, v8::Local<v8::Value> v)
{
// punch through proxies
while (v->IsProxy()) v = v8::Proxy::Cast(*v)->GetTarget();
// things that cannot be serialized
if (v->IsArgumentsObject() ||
v->IsPromise() ||
v->IsModule() ||
v->IsModuleNamespaceObject() ||
v->IsWasmMemoryObject() ||
v->IsWasmModuleObject() ||
v->IsWasmNull() ||
v->IsWeakRef()) {
return v8::Object::New(st.isolate);
}
// V8's serializer doesn't accept symbols
if (v->IsSymbol()) return v8::Symbol::Cast(*v)->Description(st.isolate);
// TODO(bnoordhuis) replace this hack with something more principled
if (v->IsFunction()) {
auto type = v8::NewStringType::kNormal;
const size_t size = sizeof(js_function_marker) / sizeof(*js_function_marker);
return v8::String::NewFromTwoByte(st.isolate, js_function_marker, type, size).ToLocalChecked();
}
if (v->IsWeakMap() || v->IsWeakSet() || v->IsMapIterator() || v->IsSetIterator()) {
bool is_key_value;
v8::Local<v8::Array> array;
if (v8::Object::Cast(*v)->PreviewEntries(&is_key_value).ToLocal(&array)) {
return array;
}
}
// WebAssembly.Instance objects are not serializable but there
// is no direct way to detect them through the V8 C++ API
if (!st.webassembly_instance.IsEmpty() &&
v->IsObject() &&
v->InstanceOf(st.context, st.webassembly_instance).FromMaybe(false)) {
return v8::Object::New(st.isolate);
}
return v;
}
v8::Local<v8::Value> to_error(State& st, v8::TryCatch *try_catch, int cause)
{
v8::Local<v8::Value> t;
char buf[1024];
*buf = '\0';
if (cause == NO_ERROR) {
// nothing to do
} else if (cause == PARSE_ERROR) {
auto message = try_catch->Message();
v8::String::Utf8Value s(st.isolate, message->Get());
v8::String::Utf8Value name(st.isolate, message->GetScriptResourceName());
if (!*s || !*name) goto fallback;
auto line = message->GetLineNumber(st.context).FromMaybe(0);
auto column = message->GetStartColumn(st.context).FromMaybe(0);
snprintf(buf, sizeof(buf), "%c%s at %s:%d:%d", cause, *s, *name, line, column);
} else if (try_catch->StackTrace(st.context).ToLocal(&t)) {
v8::String::Utf8Value s(st.isolate, t);
if (!*s) goto fallback;
snprintf(buf, sizeof(buf), "%c%s", cause, *s);
} else {
fallback:
v8::String::Utf8Value s(st.isolate, try_catch->Exception());
const char *message = *s ? *s : "unexpected failure";
if (cause == MEMORY_ERROR) message = "out of memory";
if (cause == TERMINATED_ERROR) message = "terminated";
snprintf(buf, sizeof(buf), "%c%s", cause, message);
}
v8::Local<v8::String> s;
if (v8::String::NewFromUtf8(st.isolate, buf).ToLocal(&s)) return s;
return v8::String::Empty(st.isolate);
}
extern "C" void v8_global_init(void)
{
char *p;
size_t n;
v8_get_flags(&p, &n);
if (p) {
for (char *s = p; s < p+n; s += 1 + strlen(s)) {
v8::V8::SetFlagsFromString(s);
}
free(p);
}
v8::V8::InitializeICU();
if (single_threaded) {
platform = v8::platform::NewSingleThreadedDefaultPlatform().release();
} else {
platform = v8::platform::NewDefaultPlatform().release();
}
v8::V8::InitializePlatform(platform);
v8::V8::Initialize();
}
void v8_gc_callback(v8::Isolate*, v8::GCType, v8::GCCallbackFlags, void *data)
{
State& st = *static_cast<State*>(data);
v8::HeapStatistics s;
st.isolate->GetHeapStatistics(&s);
int64_t used_heap_size = static_cast<int64_t>(s.used_heap_size());
if (used_heap_size > st.max_memory) {
st.err_reason = MEMORY_ERROR;
st.isolate->TerminateExecution();
}
}
extern "C" State *v8_thread_init(Context *c, const uint8_t *snapshot_buf,
size_t snapshot_len, int64_t max_memory,
int verbose_exceptions)
{
State *pst = new State{};
State& st = *pst;
st.verbose_exceptions = (verbose_exceptions != 0);
st.ruby_context = c;
st.allocator.reset(v8::ArrayBuffer::Allocator::NewDefaultAllocator());
v8::StartupData blob{nullptr, 0};
v8::Isolate::CreateParams params;
params.array_buffer_allocator = st.allocator.get();
if (snapshot_len) {
blob.data = reinterpret_cast<const char*>(snapshot_buf);
blob.raw_size = snapshot_len;
params.snapshot_blob = &blob;
}
st.isolate = v8::Isolate::New(params);
st.max_memory = max_memory;
if (st.max_memory > 0)
st.isolate->AddGCEpilogueCallback(v8_gc_callback, pst);
{
v8::Locker locker(st.isolate);
v8::Isolate::Scope isolate_scope(st.isolate);
v8::HandleScope handle_scope(st.isolate);
st.safe_context = v8::Context::New(st.isolate);
st.context = v8::Context::New(st.isolate);
v8::Context::Scope context_scope(st.context);
auto global = st.context->Global();
// globalThis.WebAssembly is missing in --jitless mode
auto key = v8::String::NewFromUtf8Literal(st.isolate, "WebAssembly");
v8::Local<v8::Value> wasm_v;
if (global->Get(st.context, key).ToLocal(&wasm_v) && wasm_v->IsObject()) {
auto key = v8::String::NewFromUtf8Literal(st.isolate, "Instance");
st.webassembly_instance =
wasm_v.As<v8::Object>()
->Get(st.context, key).ToLocalChecked().As<v8::Object>();
}
if (single_threaded) {
st.persistent_webassembly_instance.Reset(st.isolate, st.webassembly_instance);
st.persistent_safe_context.Reset(st.isolate, st.safe_context);
st.persistent_context.Reset(st.isolate, st.context);
return pst; // intentionally returning early and keeping alive
}
v8_thread_main(c, pst);
}
delete pst;
return nullptr;
}
void v8_api_callback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
auto ext = v8::External::Cast(*info.Data());
Callback *cb = static_cast<Callback*>(ext->Value());
State& st = *cb->st;
v8::Local<v8::Array> request;
{
v8::Context::Scope context_scope(st.safe_context);
request = v8::Array::New(st.isolate, 2);
}
for (int i = 0, n = info.Length(); i < n; i++) {
request->Set(st.context, i, sanitize(st, info[i])).Check();
}
auto id = v8::Int32::New(st.isolate, cb->id);
request->Set(st.context, info.Length(), id).Check(); // callback id
{
Serialized serialized(st, request);
if (!serialized.data) return; // exception pending
uint8_t marker = 'c'; // callback marker
v8_reply(st.ruby_context, &marker, 1);
v8_reply(st.ruby_context, serialized.data, serialized.size);
}
const uint8_t *p;
size_t n;
for (;;) {
v8_roundtrip(st.ruby_context, &p, &n);
if (*p == 'c') // callback reply
break;
if (*p == 'e') // ruby exception pending
return st.isolate->TerminateExecution();
v8_dispatch(st.ruby_context);
}
v8::ValueDeserializer des(st.isolate, p+1, n-1);
des.ReadHeader(st.context).Check();
v8::Local<v8::Value> result;
if (!des.ReadValue(st.context).ToLocal(&result)) return; // exception pending
v8::Local<v8::Object> response; // [result, err]
if (!result->ToObject(st.context).ToLocal(&response)) return;
v8::Local<v8::Value> err;
if (!response->Get(st.context, 1).ToLocal(&err)) return;
if (err->IsUndefined()) {
if (!response->Get(st.context, 0).ToLocal(&result)) return;
info.GetReturnValue().Set(result);
} else {
v8::Local<v8::String> message;
if (!err->ToString(st.context).ToLocal(&message)) return;
st.isolate->ThrowException(v8::Exception::Error(message));
}
}
// response is err or empty string
extern "C" void v8_attach(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
v8::ValueDeserializer des(st.isolate, p, n);
des.ReadHeader(st.context).Check();
int cause = INTERNAL_ERROR;
{
v8::Local<v8::Value> request_v;
if (!des.ReadValue(st.context).ToLocal(&request_v)) goto fail;
v8::Local<v8::Object> request; // [name, id]
if (!request_v->ToObject(st.context).ToLocal(&request)) goto fail;
v8::Local<v8::Value> name_v;
if (!request->Get(st.context, 0).ToLocal(&name_v)) goto fail;
v8::Local<v8::Value> id_v;
if (!request->Get(st.context, 1).ToLocal(&id_v)) goto fail;
v8::Local<v8::String> name;
if (!name_v->ToString(st.context).ToLocal(&name)) goto fail;
int32_t id;
if (!id_v->Int32Value(st.context).To(&id)) goto fail;
Callback *cb = new Callback{pst, id};
st.callbacks.push_back(cb);
v8::Local<v8::External> ext = v8::External::New(st.isolate, cb);
v8::Local<v8::Function> function;
if (!v8::Function::New(st.context, v8_api_callback, ext).ToLocal(&function)) goto fail;
// support foo.bar.baz paths
v8::String::Utf8Value path(st.isolate, name);
if (!*path) goto fail;
v8::Local<v8::Object> obj = st.context->Global();
v8::Local<v8::String> key;
for (const char *p = *path;;) {
size_t n = strcspn(p, ".");
auto type = v8::NewStringType::kNormal;
if (!v8::String::NewFromUtf8(st.isolate, p, type, n).ToLocal(&key)) goto fail;
if (p[n] == '\0') break;
p += n + 1;
v8::Local<v8::Value> val;
if (!obj->Get(st.context, key).ToLocal(&val)) goto fail;
if (!val->IsObject() && !val->IsFunction()) {
val = v8::Object::New(st.isolate);
if (!obj->Set(st.context, key, val).FromMaybe(false)) goto fail;
}
obj = val.As<v8::Object>();
}
if (!obj->Set(st.context, key, function).FromMaybe(false)) goto fail;
}
cause = NO_ERROR;
fail:
if (!cause && try_catch.HasCaught()) cause = RUNTIME_ERROR;
auto err = to_error(st, &try_catch, cause);
if (!reply(st, err)) abort();
}
// response is errback [result, err] array
extern "C" void v8_call(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
v8::ValueDeserializer des(st.isolate, p, n);
std::vector<v8::Local<v8::Value>> args;
des.ReadHeader(st.context).Check();
v8::Local<v8::Array> response;
{
v8::Context::Scope context_scope(st.safe_context);
response = v8::Array::New(st.isolate, 2);
}
v8::Local<v8::Value> result;
int cause = INTERNAL_ERROR;
{
v8::Local<v8::Value> request_v;
if (!des.ReadValue(st.context).ToLocal(&request_v)) goto fail;
v8::Local<v8::Object> request;
if (!request_v->ToObject(st.context).ToLocal(&request)) goto fail;
v8::Local<v8::Value> name_v;
if (!request->Get(st.context, 0).ToLocal(&name_v)) goto fail;
v8::Local<v8::String> name;
if (!name_v->ToString(st.context).ToLocal(&name)) goto fail;
cause = RUNTIME_ERROR;
// support foo.bar.baz paths
v8::String::Utf8Value path(st.isolate, name);
if (!*path) goto fail;
v8::Local<v8::Object> obj = st.context->Global();
v8::Local<v8::String> key;
for (const char *p = *path;;) {
size_t n = strcspn(p, ".");
auto type = v8::NewStringType::kNormal;
if (!v8::String::NewFromUtf8(st.isolate, p, type, n).ToLocal(&key)) goto fail;
if (p[n] == '\0') break;
p += n + 1;
v8::Local<v8::Value> val;
if (!obj->Get(st.context, key).ToLocal(&val)) goto fail;
if (!val->ToObject(st.context).ToLocal(&obj)) goto fail;
}
v8::Local<v8::Value> function_v;
if (!obj->Get(st.context, key).ToLocal(&function_v)) goto fail;
if (!function_v->IsFunction()) {
// XXX it's technically possible for |function_v| to be a callable
// object but those are effectively extinct; regexp objects used
// to be callable but not anymore
auto message = v8::String::NewFromUtf8Literal(st.isolate, "not a function");
auto exception = v8::Exception::TypeError(message);
st.isolate->ThrowException(exception);
goto fail;
}
auto function = v8::Function::Cast(*function_v);
assert(request->IsArray());
int n = v8::Array::Cast(*request)->Length();
for (int i = 1; i < n; i++) {
v8::Local<v8::Value> val;
if (!request->Get(st.context, i).ToLocal(&val)) goto fail;
args.push_back(val);
}
auto maybe_result_v = function->Call(st.context, obj, args.size(), args.data());
v8::Local<v8::Value> result_v;
if (!maybe_result_v.ToLocal(&result_v)) goto fail;
result = sanitize(st, result_v);
}
cause = NO_ERROR;
fail:
if (st.isolate->IsExecutionTerminating()) {
st.isolate->CancelTerminateExecution();
cause = st.err_reason ? st.err_reason : TERMINATED_ERROR;
st.err_reason = NO_ERROR;
}
if (!cause && try_catch.HasCaught()) cause = RUNTIME_ERROR;
if (cause) result = v8::Undefined(st.isolate);
auto err = to_error(st, &try_catch, cause);
response->Set(st.context, 0, result).Check();
response->Set(st.context, 1, err).Check();
if (!reply(st, response)) {
assert(try_catch.HasCaught());
goto fail; // retry; can be termination exception
}
}
// response is errback [result, err] array
extern "C" void v8_eval(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
v8::ValueDeserializer des(st.isolate, p, n);
des.ReadHeader(st.context).Check();
v8::Local<v8::Array> response;
{
v8::Context::Scope context_scope(st.safe_context);
response = v8::Array::New(st.isolate, 2);
}
v8::Local<v8::Value> result;
int cause = INTERNAL_ERROR;
{
v8::Local<v8::Value> request_v;
if (!des.ReadValue(st.context).ToLocal(&request_v)) goto fail;
v8::Local<v8::Object> request; // [filename, source]
if (!request_v->ToObject(st.context).ToLocal(&request)) goto fail;
v8::Local<v8::Value> filename;
if (!request->Get(st.context, 0).ToLocal(&filename)) goto fail;
v8::Local<v8::Value> source_v;
if (!request->Get(st.context, 1).ToLocal(&source_v)) goto fail;
v8::Local<v8::String> source;
if (!source_v->ToString(st.context).ToLocal(&source)) goto fail;
v8::ScriptOrigin origin(filename);
v8::Local<v8::Script> script;
cause = PARSE_ERROR;
if (!v8::Script::Compile(st.context, source, &origin).ToLocal(&script)) goto fail;
v8::Local<v8::Value> result_v;
cause = RUNTIME_ERROR;
auto maybe_result_v = script->Run(st.context);
if (!maybe_result_v.ToLocal(&result_v)) goto fail;
result = sanitize(st, result_v);
}
cause = NO_ERROR;
fail:
if (st.isolate->IsExecutionTerminating()) {
st.isolate->CancelTerminateExecution();
cause = st.err_reason ? st.err_reason : TERMINATED_ERROR;
st.err_reason = NO_ERROR;
}
if (!cause && try_catch.HasCaught()) cause = RUNTIME_ERROR;
if (cause) result = v8::Undefined(st.isolate);
auto err = to_error(st, &try_catch, cause);
response->Set(st.context, 0, result).Check();
response->Set(st.context, 1, err).Check();
if (!reply(st, response)) {
assert(try_catch.HasCaught());
goto fail; // retry; can be termination exception
}
}
extern "C" void v8_heap_stats(State *pst)
{
State& st = *pst;
v8::HandleScope handle_scope(st.isolate);
v8::HeapStatistics s;
st.isolate->GetHeapStatistics(&s);
v8::Local<v8::Object> response = v8::Object::New(st.isolate);
#define PROP(name) \
do { \
auto key = v8::String::NewFromUtf8Literal(st.isolate, #name); \
auto val = v8::Number::New(st.isolate, s.name()); \
response->Set(st.context, key, val).Check(); \
} while (0)
PROP(total_heap_size);
PROP(total_heap_size);
PROP(total_heap_size_executable);
PROP(total_physical_size);
PROP(total_available_size);
PROP(total_global_handles_size);
PROP(used_global_handles_size);
PROP(used_heap_size);
PROP(heap_size_limit);
PROP(malloced_memory);
PROP(external_memory);
PROP(peak_malloced_memory);
PROP(number_of_native_contexts);
PROP(number_of_detached_contexts);
#undef PROP
if (!reply(st, response)) abort();
}
struct OutputStream : public v8::OutputStream
{
std::vector<uint8_t> buf;
void EndOfStream() final {}
int GetChunkSize() final { return 65536; }
WriteResult WriteAsciiChunk(char* data, int size)
{
const uint8_t *p = reinterpret_cast<uint8_t*>(data);
buf.insert(buf.end(), p, p+size);
return WriteResult::kContinue;
}
};
extern "C" void v8_heap_snapshot(State *pst)
{
State& st = *pst;
v8::HandleScope handle_scope(st.isolate);
auto snapshot = st.isolate->GetHeapProfiler()->TakeHeapSnapshot();
OutputStream os;
snapshot->Serialize(&os, v8::HeapSnapshot::kJSON);
v8_reply(st.ruby_context, os.buf.data(), os.buf.size()); // not serialized because big
}
extern "C" void v8_pump_message_loop(State *pst)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
bool ran_task = v8::platform::PumpMessageLoop(platform, st.isolate);
if (st.isolate->IsExecutionTerminating()) goto fail;
if (try_catch.HasCaught()) goto fail;
if (ran_task) v8::MicrotasksScope::PerformCheckpoint(st.isolate);
if (st.isolate->IsExecutionTerminating()) goto fail;
if (platform->IdleTasksEnabled(st.isolate)) {
double idle_time_in_seconds = 1.0 / 50;
v8::platform::RunIdleTasks(platform, st.isolate, idle_time_in_seconds);
if (st.isolate->IsExecutionTerminating()) goto fail;
if (try_catch.HasCaught()) goto fail;
}
fail:
if (st.isolate->IsExecutionTerminating()) {
st.isolate->CancelTerminateExecution();
st.err_reason = NO_ERROR;
}
auto result = v8::Boolean::New(st.isolate, ran_task);
if (!reply(st, result)) abort();
}
int snapshot(bool is_warmup, bool verbose_exceptions,
const v8::String::Utf8Value& code,
v8::StartupData blob, v8::StartupData *result,
char (*errbuf)[512])
{
// SnapshotCreator takes ownership of isolate
v8::Isolate *isolate = v8::Isolate::Allocate();
v8::StartupData *existing_blob = is_warmup ? &blob : nullptr;
v8::SnapshotCreator snapshot_creator(isolate, nullptr, existing_blob);
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
v8::TryCatch try_catch(isolate);
try_catch.SetVerbose(verbose_exceptions);
auto filename = is_warmup
? v8::String::NewFromUtf8Literal(isolate, "<warmup>")
: v8::String::NewFromUtf8Literal(isolate, "<snapshot>");
auto mode = is_warmup
? v8::SnapshotCreator::FunctionCodeHandling::kKeep
: v8::SnapshotCreator::FunctionCodeHandling::kClear;
int cause = INTERNAL_ERROR;
{
auto context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
v8::Local<v8::String> source;
auto type = v8::NewStringType::kNormal;
if (!v8::String::NewFromUtf8(isolate, *code, type, code.length()).ToLocal(&source)) {
v8::String::Utf8Value s(isolate, try_catch.Exception());
if (*s) snprintf(*errbuf, sizeof(*errbuf), "%c%s", cause, *s);
goto fail;
}
v8::ScriptOrigin origin(filename);
v8::Local<v8::Script> script;
cause = PARSE_ERROR;
if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) {
goto err;
}
cause = RUNTIME_ERROR;
if (script->Run(context).IsEmpty()) {
err:
auto m = try_catch.Message();
v8::String::Utf8Value s(isolate, m->Get());
v8::String::Utf8Value name(isolate, m->GetScriptResourceName());
auto line = m->GetLineNumber(context).FromMaybe(0);
auto column = m->GetStartColumn(context).FromMaybe(0);
snprintf(*errbuf, sizeof(*errbuf), "%c%s\n%s:%d:%d",
cause, *s, *name, line, column);
goto fail;
}
cause = INTERNAL_ERROR;
if (!is_warmup) snapshot_creator.SetDefaultContext(context);
}
if (is_warmup) {
isolate->ContextDisposedNotification(false);
auto context = v8::Context::New(isolate);
snapshot_creator.SetDefaultContext(context);
}
*result = snapshot_creator.CreateBlob(mode);
cause = NO_ERROR;
fail:
return cause;
}
// response is errback [result, err] array
// note: currently needs --stress_snapshot in V8 debug builds
// to work around a buggy check in the snapshot deserializer
extern "C" void v8_snapshot(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
v8::ValueDeserializer des(st.isolate, p, n);
des.ReadHeader(st.context).Check();
v8::Local<v8::Array> response;
{
v8::Context::Scope context_scope(st.safe_context);
response = v8::Array::New(st.isolate, 2);
}
v8::Local<v8::Value> result;
v8::StartupData blob{nullptr, 0};
int cause = INTERNAL_ERROR;
char errbuf[512] = {0};
{
v8::Local<v8::Value> code_v;
if (!des.ReadValue(st.context).ToLocal(&code_v)) goto fail;
v8::String::Utf8Value code(st.isolate, code_v);
if (!*code) goto fail;
v8::StartupData init{nullptr, 0};
cause = snapshot(/*is_warmup*/false, st.verbose_exceptions, code, init, &blob, &errbuf);
if (cause) goto fail;
}
if (blob.data) {
auto data = reinterpret_cast<const uint8_t*>(blob.data);
auto type = v8::NewStringType::kNormal;
bool ok = v8::String::NewFromOneByte(st.isolate, data, type,
blob.raw_size).ToLocal(&result);
delete[] blob.data;
blob = v8::StartupData{nullptr, 0};
if (!ok) goto fail;
}
cause = NO_ERROR;
fail:
if (st.isolate->IsExecutionTerminating()) {
st.isolate->CancelTerminateExecution();
cause = st.err_reason ? st.err_reason : TERMINATED_ERROR;
st.err_reason = NO_ERROR;
}
if (!cause && try_catch.HasCaught()) cause = RUNTIME_ERROR;
if (cause) result = v8::Undefined(st.isolate);
v8::Local<v8::Value> err;
if (*errbuf) {
if (!v8::String::NewFromUtf8(st.isolate, errbuf).ToLocal(&err)) {
err = v8::String::NewFromUtf8Literal(st.isolate, "unexpected error");
}
} else {
err = to_error(st, &try_catch, cause);
}
response->Set(st.context, 0, result).Check();
response->Set(st.context, 1, err).Check();
if (!reply(st, response)) {
assert(try_catch.HasCaught());
goto fail; // retry; can be termination exception
}
}
extern "C" void v8_warmup(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
try_catch.SetVerbose(st.verbose_exceptions);
v8::HandleScope handle_scope(st.isolate);
std::vector<uint8_t> storage;
v8::ValueDeserializer des(st.isolate, p, n);
des.ReadHeader(st.context).Check();
v8::Local<v8::Array> response;
{
v8::Context::Scope context_scope(st.safe_context);
response = v8::Array::New(st.isolate, 2);
}
v8::Local<v8::Value> result;
v8::StartupData blob{nullptr, 0};
int cause = INTERNAL_ERROR;
char errbuf[512] = {0};
{
v8::Local<v8::Value> request_v;
if (!des.ReadValue(st.context).ToLocal(&request_v)) goto fail;
v8::Local<v8::Object> request; // [snapshot, warmup_code]
if (!request_v->ToObject(st.context).ToLocal(&request)) goto fail;
v8::Local<v8::Value> blob_data_v;
if (!request->Get(st.context, 0).ToLocal(&blob_data_v)) goto fail;
v8::Local<v8::String> blob_data;
if (!blob_data_v->ToString(st.context).ToLocal(&blob_data)) goto fail;
assert(blob_data->IsOneByte());
assert(blob_data->ContainsOnlyOneByte());
if (const size_t len = blob_data->Length()) {
auto flags = v8::String::NO_NULL_TERMINATION
| v8::String::PRESERVE_ONE_BYTE_NULL;
storage.resize(len);
blob_data->WriteOneByte(st.isolate, storage.data(), 0, len, flags);
}
v8::Local<v8::Value> code_v;
if (!request->Get(st.context, 1).ToLocal(&code_v)) goto fail;
v8::String::Utf8Value code(st.isolate, code_v);
if (!*code) goto fail;
auto data = reinterpret_cast<const char*>(storage.data());
auto size = static_cast<int>(storage.size());
v8::StartupData init{data, size};
cause = snapshot(/*is_warmup*/true, st.verbose_exceptions, code, init, &blob, &errbuf);
if (cause) goto fail;
}
if (blob.data) {
auto data = reinterpret_cast<const uint8_t*>(blob.data);
auto type = v8::NewStringType::kNormal;
bool ok = v8::String::NewFromOneByte(st.isolate, data, type,
blob.raw_size).ToLocal(&result);
delete[] blob.data;
blob = v8::StartupData{nullptr, 0};
if (!ok) goto fail;
}
cause = NO_ERROR;
fail:
if (st.isolate->IsExecutionTerminating()) {
st.isolate->CancelTerminateExecution();
cause = st.err_reason ? st.err_reason : TERMINATED_ERROR;
st.err_reason = NO_ERROR;
}
if (!cause && try_catch.HasCaught()) cause = RUNTIME_ERROR;
if (cause) result = v8::Undefined(st.isolate);
v8::Local<v8::Value> err;
if (*errbuf) {
if (!v8::String::NewFromUtf8(st.isolate, errbuf).ToLocal(&err)) {
err = v8::String::NewFromUtf8Literal(st.isolate, "unexpected error");
}
} else {
err = to_error(st, &try_catch, cause);
}
response->Set(st.context, 0, result).Check();
response->Set(st.context, 1, err).Check();
if (!reply(st, response)) {
assert(try_catch.HasCaught());
goto fail; // retry; can be termination exception
}
}
extern "C" void v8_idle_notification(State *pst, const uint8_t *p, size_t n)
{
State& st = *pst;
v8::TryCatch try_catch(st.isolate);
v8::HandleScope handle_scope(st.isolate);
v8::ValueDeserializer des(st.isolate, p, n);
des.ReadHeader(st.context).Check();
double idle_time_in_seconds = .01;
{
v8::Local<v8::Value> idle_time_in_seconds_v;
if (!des.ReadValue(st.context).ToLocal(&idle_time_in_seconds_v)) goto fail;
if (!idle_time_in_seconds_v->NumberValue(st.context).To(&idle_time_in_seconds)) goto fail;
}
fail:
double now = platform->MonotonicallyIncreasingTime();
bool stop = st.isolate->IdleNotificationDeadline(now + idle_time_in_seconds);
auto result = v8::Boolean::New(st.isolate, stop);
if (!reply(st, result)) abort();
}
extern "C" void v8_low_memory_notification(State *pst)
{
pst->isolate->LowMemoryNotification();
}
// called from ruby thread
extern "C" void v8_terminate_execution(State *pst)
{
pst->isolate->TerminateExecution();
}
extern "C" void v8_single_threaded_enter(State *pst, Context *c, void (*f)(Context *c))
{
State& st = *pst;
v8::Locker locker(st.isolate);
v8::Isolate::Scope isolate_scope(st.isolate);
v8::HandleScope handle_scope(st.isolate);
{
st.webassembly_instance = v8::Local<v8::Object>::New(st.isolate, st.persistent_webassembly_instance);
st.safe_context = v8::Local<v8::Context>::New(st.isolate, st.persistent_safe_context);
st.context = v8::Local<v8::Context>::New(st.isolate, st.persistent_context);
v8::Context::Scope context_scope(st.context);
f(c);
st.context = v8::Local<v8::Context>();
st.safe_context = v8::Local<v8::Context>();
st.webassembly_instance = v8::Local<v8::Object>();
}
}
extern "C" void v8_single_threaded_dispose(struct State *pst)
{
delete pst; // see State::~State() below
}
} // namespace anonymous
State::~State()
{
{
v8::Locker locker(isolate);
v8::Isolate::Scope isolate_scope(isolate);
persistent_webassembly_instance.Reset();
persistent_safe_context.Reset();
persistent_context.Reset();
}
isolate->Dispose();
for (Callback *cb : callbacks)
delete cb;
}