-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathmini_racer_extension.cc
1714 lines (1373 loc) · 54.8 KB
/
mini_racer_extension.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
#include <stdio.h>
#include <ruby.h>
#include <ruby/thread.h>
#include <ruby/io.h>
#include <v8.h>
#include <v8-profiler.h>
#include <libplatform/libplatform.h>
#include <ruby/encoding.h>
#include <pthread.h>
#include <unistd.h>
#include <mutex>
#include <atomic>
#include <math.h>
using namespace v8;
typedef struct {
const char* data;
int raw_size;
} SnapshotInfo;
class IsolateInfo {
public:
Isolate* isolate;
ArrayBuffer::Allocator* allocator;
StartupData* startup_data;
bool interrupted;
bool added_gc_cb;
pid_t pid;
VALUE mutex;
class Lock {
VALUE &mutex;
public:
Lock(VALUE &mutex) : mutex(mutex) {
rb_mutex_lock(mutex);
}
~Lock() {
rb_mutex_unlock(mutex);
}
};
IsolateInfo() : isolate(nullptr), allocator(nullptr), startup_data(nullptr),
interrupted(false), added_gc_cb(false), pid(getpid()), refs_count(0) {
VALUE cMutex = rb_const_get(rb_cThread, rb_intern("Mutex"));
mutex = rb_class_new_instance(0, nullptr, cMutex);
}
~IsolateInfo();
void init(SnapshotInfo* snapshot_info = nullptr);
void mark() {
rb_gc_mark(mutex);
}
Lock createLock() {
Lock lock(mutex);
return lock;
}
void hold() {
refs_count++;
}
void release() {
if (--refs_count <= 0) {
delete this;
}
}
int refs() {
return refs_count;
}
static void* operator new(size_t size) {
return ruby_xmalloc(size);
}
static void operator delete(void *block) {
xfree(block);
}
private:
// how many references to this isolate exist
// we can't rely on Ruby's GC for this, because Ruby could destroy the
// isolate before destroying the contexts that depend on them. We'd need to
// keep a list of linked contexts in the isolate to destroy those first when
// isolate destruction was requested. Keeping such a list would require
// notification from the context VALUEs when they are constructed and
// destroyed. With a ref count, those notifications are still needed, but
// we keep a simple int rather than a list of pointers.
std::atomic_int refs_count;
};
typedef struct {
IsolateInfo* isolate_info;
Persistent<Context>* context;
} ContextInfo;
typedef struct {
bool parsed;
bool executed;
bool terminated;
bool json;
Persistent<Value>* value;
Persistent<Value>* message;
Persistent<Value>* backtrace;
} EvalResult;
typedef struct {
ContextInfo* context_info;
Local<String>* eval;
Local<String>* filename;
useconds_t timeout;
EvalResult* result;
size_t max_memory;
} EvalParams;
typedef struct {
ContextInfo *context_info;
char *function_name;
int argc;
bool error;
Local<Function> fun;
Local<Value> *argv;
EvalResult result;
size_t max_memory;
} FunctionCall;
enum IsolateFlags {
IN_GVL,
DO_TERMINATE,
MEM_SOFTLIMIT_VALUE,
MEM_SOFTLIMIT_REACHED,
};
static VALUE rb_cContext;
static VALUE rb_cSnapshot;
static VALUE rb_cIsolate;
static VALUE rb_eScriptTerminatedError;
static VALUE rb_eV8OutOfMemoryError;
static VALUE rb_eParseError;
static VALUE rb_eScriptRuntimeError;
static VALUE rb_cJavaScriptFunction;
static VALUE rb_eSnapshotError;
static VALUE rb_ePlatformAlreadyInitializedError;
static VALUE rb_mJSON;
static VALUE rb_cFailedV8Conversion;
static VALUE rb_cDateTime = Qnil;
static std::unique_ptr<Platform> current_platform = NULL;
static std::mutex platform_lock;
static pthread_attr_t *thread_attr_p;
static pthread_rwlock_t exit_lock = PTHREAD_RWLOCK_INITIALIZER;
static bool ruby_exiting; // guarded by exit_lock
static VALUE rb_platform_set_flag_as_str(VALUE _klass, VALUE flag_as_str) {
bool platform_already_initialized = false;
if(TYPE(flag_as_str) != T_STRING) {
rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE" (should be a string)",
rb_obj_class(flag_as_str));
}
platform_lock.lock();
if (current_platform == NULL) {
V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), (int)RSTRING_LEN(flag_as_str));
} else {
platform_already_initialized = true;
}
platform_lock.unlock();
// important to raise outside of the lock
if (platform_already_initialized) {
rb_raise(rb_ePlatformAlreadyInitializedError, "The V8 platform is already initialized");
}
return Qnil;
}
static void init_v8() {
// no need to wait for the lock if already initialized
if (current_platform != NULL) return;
platform_lock.lock();
if (current_platform == NULL) {
V8::InitializeICU();
current_platform = platform::NewDefaultPlatform();
V8::InitializePlatform(current_platform.get());
V8::Initialize();
}
platform_lock.unlock();
}
static void gc_callback(Isolate *isolate, GCType type, GCCallbackFlags flags) {
if((bool)isolate->GetData(MEM_SOFTLIMIT_REACHED)) return;
size_t softlimit = *(size_t*) isolate->GetData(MEM_SOFTLIMIT_VALUE);
HeapStatistics stats;
isolate->GetHeapStatistics(&stats);
size_t used = stats.used_heap_size();
if(used > softlimit) {
isolate->SetData(MEM_SOFTLIMIT_REACHED, (void*)true);
isolate->TerminateExecution();
}
}
// to be called with active lock and scope
static void prepare_result(MaybeLocal<Value> v8res,
TryCatch& trycatch,
Isolate* isolate,
Local<Context> context,
EvalResult& evalRes /* out */) {
// just don't touch .parsed
evalRes.terminated = false;
evalRes.json = false;
evalRes.value = nullptr;
evalRes.message = nullptr;
evalRes.backtrace = nullptr;
evalRes.executed = !v8res.IsEmpty();
if (evalRes.executed) {
// arrays and objects get converted to json
Local<Value> local_value = v8res.ToLocalChecked();
if ((local_value->IsObject() || local_value->IsArray()) &&
!local_value->IsDate() && !local_value->IsFunction()) {
Local<Object> JSON = context->Global()->Get(
context, String::NewFromUtf8Literal(isolate, "JSON"))
.ToLocalChecked().As<Object>();
Local<Function> stringify = JSON->Get(
context, v8::String::NewFromUtf8Literal(isolate, "stringify"))
.ToLocalChecked().As<Function>();
Local<Object> object = local_value->ToObject(context).ToLocalChecked();
const unsigned argc = 1;
Local<Value> argv[argc] = { object };
MaybeLocal<Value> json = stringify->Call(context, JSON, argc, argv);
if (json.IsEmpty()) {
evalRes.executed = false;
} else {
evalRes.json = true;
Persistent<Value>* persistent = new Persistent<Value>();
persistent->Reset(isolate, json.ToLocalChecked());
evalRes.value = persistent;
}
} else {
Persistent<Value>* persistent = new Persistent<Value>();
persistent->Reset(isolate, local_value);
evalRes.value = persistent;
}
}
if (!evalRes.executed || !evalRes.parsed) {
if (trycatch.HasCaught()) {
if (!trycatch.Exception()->IsNull()) {
evalRes.message = new Persistent<Value>();
Local<Message> message = trycatch.Message();
char buf[1000];
int len, line, column;
if (!message->GetLineNumber(context).To(&line)) {
line = 0;
}
if (!message->GetStartColumn(context).To(&column)) {
column = 0;
}
len = snprintf(buf, sizeof(buf), "%s at %s:%i:%i", *String::Utf8Value(isolate, message->Get()),
*String::Utf8Value(isolate, message->GetScriptResourceName()->ToString(context).ToLocalChecked()),
line,
column);
if ((size_t) len >= sizeof(buf)) {
len = sizeof(buf) - 1;
buf[len] = '\0';
}
Local<String> v8_message = String::NewFromUtf8(isolate, buf, NewStringType::kNormal, len).ToLocalChecked();
evalRes.message->Reset(isolate, v8_message);
} else if(trycatch.HasTerminated()) {
evalRes.terminated = true;
evalRes.message = new Persistent<Value>();
Local<String> tmp = String::NewFromUtf8Literal(isolate, "JavaScript was terminated (either by timeout or explicitly)");
evalRes.message->Reset(isolate, tmp);
}
if (!trycatch.StackTrace(context).IsEmpty()) {
evalRes.backtrace = new Persistent<Value>();
evalRes.backtrace->Reset(isolate,
trycatch.StackTrace(context).ToLocalChecked()->ToString(context).ToLocalChecked());
}
}
}
}
void*
nogvl_context_eval(void* arg) {
EvalParams* eval_params = (EvalParams*)arg;
EvalResult* result = eval_params->result;
IsolateInfo* isolate_info = eval_params->context_info->isolate_info;
Isolate* isolate = isolate_info->isolate;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
TryCatch trycatch(isolate);
Local<Context> context = eval_params->context_info->context->Get(isolate);
Context::Scope context_scope(context);
v8::ScriptOrigin *origin = NULL;
// in gvl flag
isolate->SetData(IN_GVL, (void*)false);
// terminate ASAP
isolate->SetData(DO_TERMINATE, (void*)false);
// Memory softlimit
isolate->SetData(MEM_SOFTLIMIT_VALUE, (void*)false);
// Memory softlimit hit flag
isolate->SetData(MEM_SOFTLIMIT_REACHED, (void*)false);
MaybeLocal<Script> parsed_script;
if (eval_params->filename) {
origin = new v8::ScriptOrigin(*eval_params->filename);
}
parsed_script = Script::Compile(context, *eval_params->eval, origin);
if (origin) {
delete origin;
}
result->parsed = !parsed_script.IsEmpty();
result->executed = false;
result->terminated = false;
result->json = false;
result->value = NULL;
MaybeLocal<Value> maybe_value;
if (!result->parsed) {
result->message = new Persistent<Value>();
result->message->Reset(isolate, trycatch.Exception());
} else {
// parsing successful
if (eval_params->max_memory > 0) {
isolate->SetData(MEM_SOFTLIMIT_VALUE, &eval_params->max_memory);
if (!isolate_info->added_gc_cb) {
isolate->AddGCEpilogueCallback(gc_callback);
isolate_info->added_gc_cb = true;
}
}
maybe_value = parsed_script.ToLocalChecked()->Run(context);
}
prepare_result(maybe_value, trycatch, isolate, context, *result);
isolate->SetData(IN_GVL, (void*)true);
return NULL;
}
static VALUE new_empty_failed_conv_obj() {
// TODO isolate code that translates execption to ruby
// exception so we can properly return it
return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
}
// assumes isolate locking is in place
static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
Local<Value> value) {
Isolate::Scope isolate_scope(isolate);
HandleScope scope(isolate);
if (value->IsNull() || value->IsUndefined()){
return Qnil;
}
if (value->IsInt32()) {
return INT2FIX(value->Int32Value(context).ToChecked());
}
if (value->IsNumber()) {
return rb_float_new(value->NumberValue(context).ToChecked());
}
if (value->IsTrue()) {
return Qtrue;
}
if (value->IsFalse()) {
return Qfalse;
}
if (value->IsArray()) {
VALUE rb_array = rb_ary_new();
Local<Array> arr = Local<Array>::Cast(value);
for(uint32_t i=0; i < arr->Length(); i++) {
MaybeLocal<Value> element = arr->Get(context, i);
if (element.IsEmpty()) {
continue;
}
VALUE rb_elem = convert_v8_to_ruby(isolate, context, element.ToLocalChecked());
if (rb_funcall(rb_elem, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
return rb_elem;
}
rb_ary_push(rb_array, rb_elem);
}
return rb_array;
}
if (value->IsFunction()){
return rb_funcall(rb_cJavaScriptFunction, rb_intern("new"), 0);
}
if (value->IsDate()){
double ts = Local<Date>::Cast(value)->ValueOf();
double secs = ts/1000;
long nanos = round((secs - floor(secs)) * 1000000);
return rb_time_new(secs, nanos);
}
if (value->IsObject()) {
VALUE rb_hash = rb_hash_new();
TryCatch trycatch(isolate);
Local<Object> object = value->ToObject(context).ToLocalChecked();
auto maybe_props = object->GetOwnPropertyNames(context);
if (!maybe_props.IsEmpty()) {
Local<Array> props = maybe_props.ToLocalChecked();
for(uint32_t i=0; i < props->Length(); i++) {
MaybeLocal<Value> key = props->Get(context, i);
if (key.IsEmpty()) {
return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
}
VALUE rb_key = convert_v8_to_ruby(isolate, context, key.ToLocalChecked());
MaybeLocal<Value> prop_value = object->Get(context, key.ToLocalChecked());
// this may have failed due to Get raising
if (prop_value.IsEmpty() || trycatch.HasCaught()) {
return new_empty_failed_conv_obj();
}
VALUE rb_value = convert_v8_to_ruby(
isolate, context, prop_value.ToLocalChecked());
rb_hash_aset(rb_hash, rb_key, rb_value);
}
}
return rb_hash;
}
if (value->IsSymbol()) {
v8::String::Utf8Value symbol_name(isolate,
Local<Symbol>::Cast(value)->Name());
VALUE str_symbol = rb_enc_str_new(
*symbol_name,
symbol_name.length(),
rb_enc_find("utf-8")
);
return ID2SYM(rb_intern_str(str_symbol));
}
MaybeLocal<String> rstr_maybe = value->ToString(context);
if (rstr_maybe.IsEmpty()) {
return Qnil;
} else {
Local<String> rstr = rstr_maybe.ToLocalChecked();
return rb_enc_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate), rb_enc_find("utf-8"));
}
}
static VALUE convert_v8_to_ruby(Isolate* isolate,
const Persistent<Context>& context,
Local<Value> value) {
HandleScope scope(isolate);
return convert_v8_to_ruby(isolate,
Local<Context>::New(isolate, context),
value);
}
static VALUE convert_v8_to_ruby(Isolate* isolate,
const Persistent<Context>& context,
const Persistent<Value>& value) {
HandleScope scope(isolate);
return convert_v8_to_ruby(isolate,
Local<Context>::New(isolate, context),
Local<Value>::New(isolate, value));
}
static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context, VALUE value) {
EscapableHandleScope scope(isolate);
Local<Array> array;
Local<Object> object;
VALUE hash_as_array;
VALUE pair;
int i;
long length;
long fixnum;
VALUE klass;
switch (TYPE(value)) {
case T_FIXNUM:
fixnum = NUM2LONG(value);
if (fixnum > INT_MAX)
{
return scope.Escape(Number::New(isolate, (double)fixnum));
}
return scope.Escape(Integer::New(isolate, (int)fixnum));
case T_FLOAT:
return scope.Escape(Number::New(isolate, NUM2DBL(value)));
case T_STRING:
return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
case T_NIL:
return scope.Escape(Null(isolate));
case T_TRUE:
return scope.Escape(True(isolate));
case T_FALSE:
return scope.Escape(False(isolate));
case T_ARRAY:
length = RARRAY_LEN(value);
array = Array::New(isolate, (int)length);
for(i=0; i<length; i++) {
array->Set(context, i, convert_ruby_to_v8(isolate, context, rb_ary_entry(value, i)));
}
return scope.Escape(array);
case T_HASH:
object = Object::New(isolate);
hash_as_array = rb_funcall(value, rb_intern("to_a"), 0);
length = RARRAY_LEN(hash_as_array);
for(i=0; i<length; i++) {
pair = rb_ary_entry(hash_as_array, i);
object->Set(context, convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 0)),
convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 1)));
}
return scope.Escape(object);
case T_SYMBOL:
value = rb_funcall(value, rb_intern("to_s"), 0);
return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
case T_DATA:
klass = rb_funcall(value, rb_intern("class"), 0);
if (klass == rb_cTime || klass == rb_cDateTime)
{
if (klass == rb_cDateTime)
{
value = rb_funcall(value, rb_intern("to_time"), 0);
}
value = rb_funcall(value, rb_intern("to_f"), 0);
return scope.Escape(Date::New(context, NUM2DBL(value) * 1000).ToLocalChecked());
}
case T_OBJECT:
case T_CLASS:
case T_ICLASS:
case T_MODULE:
case T_REGEXP:
case T_MATCH:
case T_STRUCT:
case T_BIGNUM:
case T_FILE:
case T_UNDEF:
case T_NODE:
default:
return scope.Escape(String::NewFromUtf8Literal(isolate, "Undefined Conversion"));
}
}
static void unblock_eval(void *ptr) {
EvalParams* eval = (EvalParams*)ptr;
eval->context_info->isolate_info->interrupted = true;
}
/*
* The implementations of the run_extra_code(), create_snapshot_data_blob() and
* warm_up_snapshot_data_blob() functions have been derived from V8's test suite.
*/
static bool run_extra_code(Isolate *isolate, Local<v8::Context> context,
const char *utf8_source, const char *name) {
Context::Scope context_scope(context);
TryCatch try_catch(isolate);
Local<String> source_string;
if (!String::NewFromUtf8(isolate, utf8_source).ToLocal(&source_string)) {
return false;
}
Local<String> resource_name =
String::NewFromUtf8(isolate, name).ToLocalChecked();
ScriptOrigin origin(resource_name);
ScriptCompiler::Source source(source_string, origin);
Local<Script> script;
if (!ScriptCompiler::Compile(context, &source).ToLocal(&script))
return false;
if (script->Run(context).IsEmpty()) return false;
return true;
}
static StartupData
create_snapshot_data_blob(const char *embedded_source = nullptr) {
Isolate *isolate = Isolate::Allocate();
// Optionally run a script to embed, and serialize to create a snapshot blob.
SnapshotCreator snapshot_creator(isolate);
{
HandleScope scope(isolate);
Local<v8::Context> context = v8::Context::New(isolate);
if (embedded_source != nullptr &&
!run_extra_code(isolate, context, embedded_source, "<embedded>")) {
return {};
}
snapshot_creator.SetDefaultContext(context);
}
return snapshot_creator.CreateBlob(
SnapshotCreator::FunctionCodeHandling::kClear);
}
StartupData warm_up_snapshot_data_blob(StartupData cold_snapshot_blob,
const char *warmup_source) {
// Use following steps to create a warmed up snapshot blob from a cold one:
// - Create a new isolate from the cold snapshot.
// - Create a new context to run the warmup script. This will trigger
// compilation of executed functions.
// - Create a new context. This context will be unpolluted.
// - Serialize the isolate and the second context into a new snapshot blob.
StartupData result = {nullptr, 0};
if (cold_snapshot_blob.raw_size > 0 && cold_snapshot_blob.data != nullptr &&
warmup_source != NULL) {
SnapshotCreator snapshot_creator(nullptr, &cold_snapshot_blob);
Isolate *isolate = snapshot_creator.GetIsolate();
{
HandleScope scope(isolate);
Local<Context> context = Context::New(isolate);
if (!run_extra_code(isolate, context, warmup_source, "<warm-up>")) {
return result;
}
}
{
HandleScope handle_scope(isolate);
isolate->ContextDisposedNotification(false);
Local<Context> context = Context::New(isolate);
snapshot_creator.SetDefaultContext(context);
}
result = snapshot_creator.CreateBlob(
SnapshotCreator::FunctionCodeHandling::kKeep);
}
return result;
}
static VALUE rb_snapshot_size(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
return INT2NUM(snapshot_info->raw_size);
}
static VALUE rb_snapshot_load(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
if(TYPE(str) != T_STRING) {
rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
rb_obj_class(str));
}
init_v8();
StartupData startup_data = create_snapshot_data_blob(RSTRING_PTR(str));
if (startup_data.data == NULL && startup_data.raw_size == 0) {
rb_raise(rb_eSnapshotError, "Could not create snapshot, most likely the source is incorrect");
}
snapshot_info->data = startup_data.data;
snapshot_info->raw_size = startup_data.raw_size;
return Qnil;
}
static VALUE rb_snapshot_dump(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
return rb_str_new(snapshot_info->data, snapshot_info->raw_size);
}
static VALUE rb_snapshot_warmup_unsafe(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
if(TYPE(str) != T_STRING) {
rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
rb_obj_class(str));
}
init_v8();
StartupData cold_startup_data = {snapshot_info->data, snapshot_info->raw_size};
StartupData warm_startup_data = warm_up_snapshot_data_blob(cold_startup_data, RSTRING_PTR(str));
if (warm_startup_data.data == NULL && warm_startup_data.raw_size == 0) {
rb_raise(rb_eSnapshotError, "Could not warm up snapshot, most likely the source is incorrect");
} else {
delete[] snapshot_info->data;
snapshot_info->data = warm_startup_data.data;
snapshot_info->raw_size = warm_startup_data.raw_size;
}
return self;
}
void IsolateInfo::init(SnapshotInfo* snapshot_info) {
allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = allocator;
if (snapshot_info) {
int raw_size = snapshot_info->raw_size;
char* data = new char[raw_size];
memcpy(data, snapshot_info->data, raw_size);
startup_data = new StartupData;
startup_data->data = data;
startup_data->raw_size = raw_size;
create_params.snapshot_blob = startup_data;
}
isolate = Isolate::New(create_params);
}
static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
init_v8();
SnapshotInfo* snapshot_info = nullptr;
if (!NIL_P(snapshot)) {
Data_Get_Struct(snapshot, SnapshotInfo, snapshot_info);
}
isolate_info->init(snapshot_info);
isolate_info->hold();
return Qnil;
}
static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
if (current_platform == NULL) return Qfalse;
double duration = NUM2DBL(idle_time_in_ms) / 1000.0;
double now = current_platform->MonotonicallyIncreasingTime();
return isolate_info->isolate->IdleNotificationDeadline(now + duration) ? Qtrue : Qfalse;
}
static VALUE rb_isolate_low_memory_notification(VALUE self) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
if (current_platform == NULL) return Qfalse;
isolate_info->isolate->LowMemoryNotification();
return Qnil;
}
static VALUE rb_isolate_pump_message_loop(VALUE self) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
if (current_platform == NULL) return Qfalse;
if (platform::PumpMessageLoop(current_platform.get(), isolate_info->isolate)){
return Qtrue;
} else {
return Qfalse;
}
}
static VALUE rb_context_init_unsafe(VALUE self, VALUE isolate, VALUE snap) {
ContextInfo* context_info;
Data_Get_Struct(self, ContextInfo, context_info);
init_v8();
IsolateInfo* isolate_info;
if (NIL_P(isolate) || !rb_obj_is_kind_of(isolate, rb_cIsolate)) {
isolate_info = new IsolateInfo();
SnapshotInfo *snapshot_info = nullptr;
if (!NIL_P(snap) && rb_obj_is_kind_of(snap, rb_cSnapshot)) {
Data_Get_Struct(snap, SnapshotInfo, snapshot_info);
}
isolate_info->init(snapshot_info);
} else { // given isolate or snapshot
Data_Get_Struct(isolate, IsolateInfo, isolate_info);
}
context_info->isolate_info = isolate_info;
isolate_info->hold();
{
// the ruby lock is needed if this isn't a new isolate
IsolateInfo::Lock ruby_lock(isolate_info->mutex);
Locker lock(isolate_info->isolate);
Isolate::Scope isolate_scope(isolate_info->isolate);
HandleScope handle_scope(isolate_info->isolate);
Local<Context> context = Context::New(isolate_info->isolate);
context_info->context = new Persistent<Context>();
context_info->context->Reset(isolate_info->isolate, context);
}
if (Qnil == rb_cDateTime && rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, rb_str_new2("DateTime")) == Qtrue)
{
rb_cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime"));
}
return Qnil;
}
static VALUE convert_result_to_ruby(VALUE self /* context */,
EvalResult& result) {
ContextInfo *context_info;
Data_Get_Struct(self, ContextInfo, context_info);
Isolate *isolate = context_info->isolate_info->isolate;
Persistent<Context> *p_ctx = context_info->context;
VALUE message = Qnil;
VALUE backtrace = Qnil;
{
Locker lock(isolate);
if (result.message) {
message = convert_v8_to_ruby(isolate, *p_ctx, *result.message);
result.message->Reset();
delete result.message;
result.message = nullptr;
}
if (result.backtrace) {
backtrace = convert_v8_to_ruby(isolate, *p_ctx, *result.backtrace);
result.backtrace->Reset();
delete result.backtrace;
}
}
// NOTE: this is very important, we can not do an rb_raise from within
// a v8 scope, if we do the scope is never cleaned up properly and we leak
if (!result.parsed) {
if(TYPE(message) == T_STRING) {
rb_raise(rb_eParseError, "%s", RSTRING_PTR(message));
} else {
rb_raise(rb_eParseError, "Unknown JavaScript Error during parse");
}
}
if (!result.executed) {
VALUE ruby_exception = rb_iv_get(self, "@current_exception");
if (ruby_exception == Qnil) {
bool mem_softlimit_reached = (bool)isolate->GetData(MEM_SOFTLIMIT_REACHED);
// If we were terminated or have the memory softlimit flag set
if (result.terminated || mem_softlimit_reached) {
ruby_exception = mem_softlimit_reached ? rb_eV8OutOfMemoryError : rb_eScriptTerminatedError;
} else {
ruby_exception = rb_eScriptRuntimeError;
}
// exception report about what happened
if (TYPE(backtrace) == T_STRING) {
rb_raise(ruby_exception, "%s", RSTRING_PTR(backtrace));
} else if(TYPE(message) == T_STRING) {
rb_raise(ruby_exception, "%s", RSTRING_PTR(message));
} else {
rb_raise(ruby_exception, "Unknown JavaScript Error during execution");
}
} else {
VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0);
rb_raise(CLASS_OF(ruby_exception), "%s", RSTRING_PTR(rb_str));
}
}
VALUE ret = Qnil;
// New scope for return value
{
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Value> tmp = Local<Value>::New(isolate, *result.value);
if (result.json) {
Local<String> rstr = tmp->ToString(p_ctx->Get(isolate)).ToLocalChecked();
VALUE json_string = rb_enc_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate), rb_enc_find("utf-8"));
ret = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string);
} else {
ret = convert_v8_to_ruby(isolate, *p_ctx, tmp);
}
result.value->Reset();
delete result.value;
}
if (rb_funcall(ret, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
// TODO try to recover stack trace from the conversion error
rb_raise(rb_eScriptRuntimeError, "Error converting JS object to Ruby object");
}
return ret;
}
static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
EvalParams eval_params;
EvalResult eval_result;
ContextInfo* context_info;
Data_Get_Struct(self, ContextInfo, context_info);
Isolate* isolate = context_info->isolate_info->isolate;
if(TYPE(str) != T_STRING) {
rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
rb_obj_class(str));
}
if(filename != Qnil && TYPE(filename) != T_STRING) {
rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be nil or a string)",
rb_obj_class(filename));
}
{
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str),
NewStringType::kNormal, (int)RSTRING_LEN(str)).ToLocalChecked();
Local<String> local_filename;
if (filename != Qnil) {
local_filename = String::NewFromUtf8(isolate, RSTRING_PTR(filename),
NewStringType::kNormal, (int)RSTRING_LEN(filename)).ToLocalChecked();
eval_params.filename = &local_filename;
} else {
eval_params.filename = NULL;
}
eval_params.context_info = context_info;
eval_params.eval = &eval;
eval_params.result = &eval_result;
eval_params.timeout = 0;
eval_params.max_memory = 0;
VALUE timeout = rb_iv_get(self, "@timeout");
if (timeout != Qnil) {
eval_params.timeout = (useconds_t)NUM2LONG(timeout);
}
VALUE mem_softlimit = rb_iv_get(self, "@max_memory");
if (mem_softlimit != Qnil) {
eval_params.max_memory = (size_t)NUM2ULONG(mem_softlimit);
}
eval_result.message = NULL;
eval_result.backtrace = NULL;
rb_thread_call_without_gvl(nogvl_context_eval, &eval_params, unblock_eval, &eval_params);
}
return convert_result_to_ruby(self, eval_result);
}
typedef struct {
VALUE callback;
int length;
VALUE ruby_args;
bool failed;