mini_racer 0.17.0.pre4 → 0.17.0.pre6

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,1915 +0,0 @@
1
- #include <stdio.h>
2
- #include <ruby.h>
3
- #include <ruby/thread.h>
4
- #include <ruby/io.h>
5
- #include <ruby/version.h>
6
- #include <v8.h>
7
- #include <v8-profiler.h>
8
- #include <libplatform/libplatform.h>
9
- #include <ruby/encoding.h>
10
- #include <pthread.h>
11
- #include <unistd.h>
12
- #include <mutex>
13
- #include <atomic>
14
- #include <math.h>
15
- #include <errno.h>
16
-
17
- /* workaround C Ruby <= 2.x problems w/ clang in C++ mode */
18
- #if defined(ENGINE_IS_CRUBY) && \
19
- RUBY_API_VERSION_MAJOR == 2 && RUBY_API_VERSION_MINOR <= 6
20
- # define MR_METHOD_FUNC(fn) RUBY_METHOD_FUNC(fn)
21
- #else
22
- # define MR_METHOD_FUNC(fn) fn
23
- #endif
24
-
25
- using namespace v8;
26
-
27
- typedef struct {
28
- const char* data;
29
- int raw_size;
30
- } SnapshotInfo;
31
-
32
- class IsolateInfo {
33
- public:
34
- Isolate* isolate;
35
- ArrayBuffer::Allocator* allocator;
36
- StartupData* startup_data;
37
- bool interrupted;
38
- bool added_gc_cb;
39
- pid_t pid;
40
- VALUE mutex;
41
-
42
- class Lock {
43
- VALUE &mutex;
44
-
45
- public:
46
- Lock(VALUE &mutex) : mutex(mutex) {
47
- rb_mutex_lock(mutex);
48
- }
49
- ~Lock() {
50
- rb_mutex_unlock(mutex);
51
- }
52
- };
53
-
54
-
55
- IsolateInfo() : isolate(nullptr), allocator(nullptr), startup_data(nullptr),
56
- interrupted(false), added_gc_cb(false), pid(getpid()), refs_count(0) {
57
- VALUE cMutex = rb_const_get(rb_cThread, rb_intern("Mutex"));
58
- mutex = rb_class_new_instance(0, nullptr, cMutex);
59
- }
60
-
61
- ~IsolateInfo();
62
-
63
- void init(SnapshotInfo* snapshot_info = nullptr);
64
-
65
- void mark() {
66
- rb_gc_mark(mutex);
67
- }
68
-
69
- Lock createLock() {
70
- Lock lock(mutex);
71
- return lock;
72
- }
73
-
74
- void hold() {
75
- refs_count++;
76
- }
77
- void release() {
78
- if (--refs_count <= 0) {
79
- delete this;
80
- }
81
- }
82
-
83
- int refs() {
84
- return refs_count;
85
- }
86
-
87
- static void* operator new(size_t size) {
88
- return ruby_xmalloc(size);
89
- }
90
-
91
- static void operator delete(void *block) {
92
- xfree(block);
93
- }
94
- private:
95
- // how many references to this isolate exist
96
- // we can't rely on Ruby's GC for this, because Ruby could destroy the
97
- // isolate before destroying the contexts that depend on them. We'd need to
98
- // keep a list of linked contexts in the isolate to destroy those first when
99
- // isolate destruction was requested. Keeping such a list would require
100
- // notification from the context VALUEs when they are constructed and
101
- // destroyed. With a ref count, those notifications are still needed, but
102
- // we keep a simple int rather than a list of pointers.
103
- std::atomic_int refs_count;
104
- };
105
-
106
- typedef struct {
107
- IsolateInfo* isolate_info;
108
- Persistent<Context>* context;
109
- } ContextInfo;
110
-
111
- typedef struct {
112
- bool parsed;
113
- bool executed;
114
- bool terminated;
115
- bool json;
116
- Persistent<Value>* value;
117
- Persistent<Value>* message;
118
- Persistent<Value>* backtrace;
119
- } EvalResult;
120
-
121
- typedef struct {
122
- ContextInfo* context_info;
123
- Local<String>* eval;
124
- Local<String>* filename;
125
- useconds_t timeout;
126
- EvalResult* result;
127
- size_t max_memory;
128
- size_t marshal_stackdepth;
129
- } EvalParams;
130
-
131
- typedef struct {
132
- ContextInfo *context_info;
133
- char *function_name;
134
- int argc;
135
- bool error;
136
- Local<Function> fun;
137
- Local<Value> *argv;
138
- EvalResult result;
139
- size_t max_memory;
140
- size_t marshal_stackdepth;
141
- } FunctionCall;
142
-
143
- class IsolateData {
144
- public:
145
- enum Flag {
146
- // first flags are bitfield
147
- // max count: sizeof(uintptr_t) * 8
148
- IN_GVL, // whether we are inside of ruby gvl or not
149
- DO_TERMINATE, // terminate as soon as possible
150
- MEM_SOFTLIMIT_REACHED, // we've hit the memory soft limit
151
- MEM_SOFTLIMIT_MAX, // maximum memory value
152
- MARSHAL_STACKDEPTH_REACHED, // we've hit our max stack depth
153
- MARSHAL_STACKDEPTH_VALUE, // current stackdepth
154
- MARSHAL_STACKDEPTH_MAX, // maximum stack depth during marshal
155
- };
156
-
157
- static void Init(Isolate *isolate) {
158
- // zero out all fields in the bitfield
159
- isolate->SetData(0, 0);
160
- }
161
-
162
- static uintptr_t Get(Isolate *isolate, Flag flag) {
163
- Bitfield u = { reinterpret_cast<uint64_t>(isolate->GetData(0)) };
164
- switch (flag) {
165
- case IN_GVL: return u.IN_GVL;
166
- case DO_TERMINATE: return u.DO_TERMINATE;
167
- case MEM_SOFTLIMIT_REACHED: return u.MEM_SOFTLIMIT_REACHED;
168
- case MEM_SOFTLIMIT_MAX: return static_cast<uintptr_t>(u.MEM_SOFTLIMIT_MAX) << 10;
169
- case MARSHAL_STACKDEPTH_REACHED: return u.MARSHAL_STACKDEPTH_REACHED;
170
- case MARSHAL_STACKDEPTH_VALUE: return u.MARSHAL_STACKDEPTH_VALUE;
171
- case MARSHAL_STACKDEPTH_MAX: return u.MARSHAL_STACKDEPTH_MAX;
172
- }
173
-
174
- // avoid compiler warning
175
- return u.IN_GVL;
176
- }
177
-
178
- static void Set(Isolate *isolate, Flag flag, uintptr_t value) {
179
- Bitfield u = { reinterpret_cast<uint64_t>(isolate->GetData(0)) };
180
- switch (flag) {
181
- case IN_GVL: u.IN_GVL = value; break;
182
- case DO_TERMINATE: u.DO_TERMINATE = value; break;
183
- case MEM_SOFTLIMIT_REACHED: u.MEM_SOFTLIMIT_REACHED = value; break;
184
- // drop least significant 10 bits 'store memory amount in kb'
185
- case MEM_SOFTLIMIT_MAX: u.MEM_SOFTLIMIT_MAX = value >> 10; break;
186
- case MARSHAL_STACKDEPTH_REACHED: u.MARSHAL_STACKDEPTH_REACHED = value; break;
187
- case MARSHAL_STACKDEPTH_VALUE: u.MARSHAL_STACKDEPTH_VALUE = value; break;
188
- case MARSHAL_STACKDEPTH_MAX: u.MARSHAL_STACKDEPTH_MAX = value; break;
189
- }
190
- isolate->SetData(0, reinterpret_cast<void*>(u.dataPtr));
191
- }
192
-
193
- private:
194
- struct Bitfield {
195
- // WARNING: this would explode on platforms below 64 bit ptrs
196
- // compiler will fail here, making it clear for them.
197
- // Additionally, using the other part of the union to reinterpret the
198
- // memory is undefined behavior according to spec, but is / has been stable
199
- // across major compilers for decades.
200
- static_assert(sizeof(uintptr_t) >= sizeof(uint64_t), "mini_racer not supported on this platform. ptr size must be at least 64 bit.");
201
- union {
202
- uint64_t dataPtr: 64;
203
- // order in this struct matters. For cpu performance keep larger subobjects
204
- // aligned on their boundaries (8 16 32), try not to straddle
205
- struct {
206
- size_t MEM_SOFTLIMIT_MAX:22;
207
- bool IN_GVL:1;
208
- bool DO_TERMINATE:1;
209
- bool MEM_SOFTLIMIT_REACHED:1;
210
- bool MARSHAL_STACKDEPTH_REACHED:1;
211
- uint8_t :0; // align to next 8bit bound
212
- size_t MARSHAL_STACKDEPTH_VALUE:10;
213
- uint8_t :0; // align to next 8bit bound
214
- size_t MARSHAL_STACKDEPTH_MAX:10;
215
- };
216
- };
217
- };
218
- };
219
-
220
- struct StackCounter {
221
- static void Reset(Isolate* isolate) {
222
- if (IsolateData::Get(isolate, IsolateData::MARSHAL_STACKDEPTH_MAX) > 0) {
223
- IsolateData::Set(isolate, IsolateData::MARSHAL_STACKDEPTH_VALUE, 0);
224
- IsolateData::Set(isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED, false);
225
- }
226
- }
227
-
228
- static void SetMax(Isolate* isolate, size_t marshalMaxStackDepth) {
229
- if (marshalMaxStackDepth > 0) {
230
- IsolateData::Set(isolate, IsolateData::MARSHAL_STACKDEPTH_MAX, marshalMaxStackDepth);
231
- IsolateData::Set(isolate, IsolateData::MARSHAL_STACKDEPTH_VALUE, 0);
232
- IsolateData::Set(isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED, false);
233
- }
234
- }
235
-
236
- StackCounter(Isolate* isolate) {
237
- this->isActive = IsolateData::Get(isolate, IsolateData::MARSHAL_STACKDEPTH_MAX) > 0;
238
-
239
- if (this->isActive) {
240
- this->isolate = isolate;
241
- this->IncDepth(1);
242
- }
243
- }
244
-
245
- bool IsTooDeep() {
246
- if (!this->IsActive()) {
247
- return false;
248
- }
249
-
250
- size_t depth = IsolateData::Get(this->isolate, IsolateData::MARSHAL_STACKDEPTH_VALUE);
251
- size_t maxDepth = IsolateData::Get(this->isolate, IsolateData::MARSHAL_STACKDEPTH_MAX);
252
- if (depth > maxDepth) {
253
- IsolateData::Set(this->isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED, true);
254
- return true;
255
- }
256
-
257
- return false;
258
- }
259
-
260
- bool IsActive() {
261
- return this->isActive && !IsolateData::Get(this->isolate, IsolateData::DO_TERMINATE);
262
- }
263
-
264
- ~StackCounter() {
265
- if (this->IsActive()) {
266
- this->IncDepth(-1);
267
- }
268
- }
269
-
270
- private:
271
- Isolate* isolate;
272
- bool isActive;
273
-
274
- void IncDepth(int direction) {
275
- int inc = direction > 0 ? 1 : -1;
276
-
277
- size_t depth = IsolateData::Get(this->isolate, IsolateData::MARSHAL_STACKDEPTH_VALUE);
278
-
279
- // don't decrement past 0
280
- if (inc > 0 || depth > 0) {
281
- depth += inc;
282
- }
283
-
284
- IsolateData::Set(this->isolate, IsolateData::MARSHAL_STACKDEPTH_VALUE, depth);
285
- }
286
- };
287
-
288
- static VALUE rb_cContext;
289
- static VALUE rb_cSnapshot;
290
- static VALUE rb_cIsolate;
291
-
292
- static VALUE rb_eScriptTerminatedError;
293
- static VALUE rb_eV8OutOfMemoryError;
294
- static VALUE rb_eParseError;
295
- static VALUE rb_eScriptRuntimeError;
296
- static VALUE rb_cJavaScriptFunction;
297
- static VALUE rb_eSnapshotError;
298
- static VALUE rb_ePlatformAlreadyInitializedError;
299
- static VALUE rb_mJSON;
300
-
301
- static VALUE rb_cFailedV8Conversion;
302
- static VALUE rb_cDateTime = Qnil;
303
-
304
- static std::unique_ptr<Platform> current_platform = NULL;
305
- static std::mutex platform_lock;
306
-
307
- static pthread_attr_t *thread_attr_p;
308
- static std::atomic_int ruby_exiting(0);
309
- static bool single_threaded = false;
310
-
311
- static void mark_context(void *);
312
- static void deallocate(void *);
313
- static size_t context_memsize(const void *);
314
- static const rb_data_type_t context_type = {
315
- "mini_racer/context_info",
316
- { mark_context, deallocate, context_memsize }
317
- };
318
-
319
- static void deallocate_snapshot(void *);
320
- static size_t snapshot_memsize(const void *);
321
- static const rb_data_type_t snapshot_type = {
322
- "mini_racer/snapshot_info",
323
- { NULL, deallocate_snapshot, snapshot_memsize }
324
- };
325
-
326
- static void mark_isolate(void *);
327
- static void deallocate_isolate(void *);
328
- static size_t isolate_memsize(const void *);
329
- static const rb_data_type_t isolate_type = {
330
- "mini_racer/isolate_info",
331
- { mark_isolate, deallocate_isolate, isolate_memsize }
332
- };
333
-
334
- static VALUE rb_platform_set_flag_as_str(VALUE _klass, VALUE flag_as_str) {
335
- bool platform_already_initialized = false;
336
-
337
- Check_Type(flag_as_str, T_STRING);
338
-
339
- platform_lock.lock();
340
-
341
- if (current_platform == NULL) {
342
- if (!strcmp(RSTRING_PTR(flag_as_str), "--single_threaded")) {
343
- single_threaded = true;
344
- }
345
- V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), RSTRING_LENINT(flag_as_str));
346
- } else {
347
- platform_already_initialized = true;
348
- }
349
-
350
- platform_lock.unlock();
351
-
352
- // important to raise outside of the lock
353
- if (platform_already_initialized) {
354
- rb_raise(rb_ePlatformAlreadyInitializedError, "The V8 platform is already initialized");
355
- }
356
-
357
- return Qnil;
358
- }
359
-
360
- static void init_v8() {
361
- // no need to wait for the lock if already initialized
362
- if (current_platform != NULL) return;
363
-
364
- platform_lock.lock();
365
-
366
- if (current_platform == NULL) {
367
- V8::InitializeICU();
368
- if (single_threaded) {
369
- current_platform = platform::NewSingleThreadedDefaultPlatform();
370
- } else {
371
- current_platform = platform::NewDefaultPlatform();
372
- }
373
- V8::InitializePlatform(current_platform.get());
374
- V8::Initialize();
375
- }
376
-
377
- platform_lock.unlock();
378
- }
379
-
380
- static void gc_callback(Isolate *isolate, GCType type, GCCallbackFlags flags) {
381
- if (IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_REACHED)) {
382
- return;
383
- }
384
-
385
- size_t softlimit = IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_MAX);
386
-
387
- HeapStatistics stats;
388
- isolate->GetHeapStatistics(&stats);
389
- size_t used = stats.used_heap_size();
390
-
391
- if(used > softlimit) {
392
- IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_REACHED, true);
393
- isolate->TerminateExecution();
394
- }
395
- }
396
-
397
- // to be called with active lock and scope
398
- static void prepare_result(MaybeLocal<Value> v8res,
399
- TryCatch& trycatch,
400
- Isolate* isolate,
401
- Local<Context> context,
402
- EvalResult& evalRes /* out */) {
403
-
404
- // just don't touch .parsed
405
- evalRes.terminated = false;
406
- evalRes.json = false;
407
- evalRes.value = nullptr;
408
- evalRes.message = nullptr;
409
- evalRes.backtrace = nullptr;
410
- evalRes.executed = !v8res.IsEmpty();
411
-
412
- if (evalRes.executed) {
413
- // arrays and objects get converted to json
414
- Local<Value> local_value = v8res.ToLocalChecked();
415
- if ((local_value->IsObject() || local_value->IsArray()) &&
416
- !local_value->IsDate() && !local_value->IsFunction()) {
417
- MaybeLocal<v8::Value> ml = context->Global()->Get(
418
- context, String::NewFromUtf8Literal(isolate, "JSON"));
419
-
420
- if (ml.IsEmpty()) { // exception
421
- evalRes.executed = false;
422
- } else {
423
- Local<Object> JSON = ml.ToLocalChecked().As<Object>();
424
-
425
- Local<Function> stringify = JSON->Get(
426
- context, v8::String::NewFromUtf8Literal(isolate, "stringify"))
427
- .ToLocalChecked().As<Function>();
428
-
429
- Local<Object> object = local_value->ToObject(context).ToLocalChecked();
430
- const unsigned argc = 1;
431
- Local<Value> argv[argc] = { object };
432
- MaybeLocal<Value> json = stringify->Call(context, JSON, argc, argv);
433
-
434
- if (json.IsEmpty()) {
435
- evalRes.executed = false;
436
- } else {
437
- evalRes.json = true;
438
- Persistent<Value>* persistent = new Persistent<Value>();
439
- persistent->Reset(isolate, json.ToLocalChecked());
440
- evalRes.value = persistent;
441
- }
442
- }
443
- } else {
444
- Persistent<Value>* persistent = new Persistent<Value>();
445
- persistent->Reset(isolate, local_value);
446
- evalRes.value = persistent;
447
- }
448
- }
449
-
450
- if (!evalRes.executed || !evalRes.parsed) {
451
- if (trycatch.HasCaught()) {
452
- if (!trycatch.Exception()->IsNull()) {
453
- evalRes.message = new Persistent<Value>();
454
- Local<Message> message = trycatch.Message();
455
- char buf[1000];
456
- int len, line, column;
457
-
458
- if (!message->GetLineNumber(context).To(&line)) {
459
- line = 0;
460
- }
461
-
462
- if (!message->GetStartColumn(context).To(&column)) {
463
- column = 0;
464
- }
465
-
466
- len = snprintf(buf, sizeof(buf), "%s at %s:%i:%i", *String::Utf8Value(isolate, message->Get()),
467
- *String::Utf8Value(isolate, message->GetScriptResourceName()->ToString(context).ToLocalChecked()),
468
- line,
469
- column);
470
-
471
- if ((size_t) len >= sizeof(buf)) {
472
- len = sizeof(buf) - 1;
473
- buf[len] = '\0';
474
- }
475
-
476
- Local<String> v8_message = String::NewFromUtf8(isolate, buf, NewStringType::kNormal, len).ToLocalChecked();
477
- evalRes.message->Reset(isolate, v8_message);
478
- } else if(trycatch.HasTerminated()) {
479
- evalRes.terminated = true;
480
- evalRes.message = new Persistent<Value>();
481
- Local<String> tmp = String::NewFromUtf8Literal(isolate, "JavaScript was terminated (either by timeout or explicitly)");
482
- evalRes.message->Reset(isolate, tmp);
483
- }
484
- if (!trycatch.StackTrace(context).IsEmpty()) {
485
- evalRes.backtrace = new Persistent<Value>();
486
- evalRes.backtrace->Reset(isolate,
487
- trycatch.StackTrace(context).ToLocalChecked()->ToString(context).ToLocalChecked());
488
- }
489
- }
490
- }
491
- }
492
-
493
- static void*
494
- nogvl_context_eval(void* arg) {
495
-
496
- EvalParams* eval_params = (EvalParams*)arg;
497
- EvalResult* result = eval_params->result;
498
- IsolateInfo* isolate_info = eval_params->context_info->isolate_info;
499
- Isolate* isolate = isolate_info->isolate;
500
-
501
- Isolate::Scope isolate_scope(isolate);
502
- HandleScope handle_scope(isolate);
503
- TryCatch trycatch(isolate);
504
- Local<Context> context = eval_params->context_info->context->Get(isolate);
505
- Context::Scope context_scope(context);
506
- v8::ScriptOrigin *origin = NULL;
507
-
508
- IsolateData::Init(isolate);
509
-
510
- if (eval_params->max_memory > 0) {
511
- IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_MAX, eval_params->max_memory);
512
- if (!isolate_info->added_gc_cb) {
513
- isolate->AddGCEpilogueCallback(gc_callback);
514
- isolate_info->added_gc_cb = true;
515
- }
516
- }
517
-
518
- MaybeLocal<Script> parsed_script;
519
-
520
- if (eval_params->filename) {
521
- origin = new v8::ScriptOrigin(isolate, *eval_params->filename);
522
- }
523
-
524
- parsed_script = Script::Compile(context, *eval_params->eval, origin);
525
-
526
- if (origin) {
527
- delete origin;
528
- }
529
-
530
- result->parsed = !parsed_script.IsEmpty();
531
- result->executed = false;
532
- result->terminated = false;
533
- result->json = false;
534
- result->value = NULL;
535
-
536
- MaybeLocal<Value> maybe_value;
537
- if (!result->parsed) {
538
- result->message = new Persistent<Value>();
539
- result->message->Reset(isolate, trycatch.Exception());
540
- } else {
541
- // parsing successful
542
- if (eval_params->marshal_stackdepth > 0) {
543
- StackCounter::SetMax(isolate, eval_params->marshal_stackdepth);
544
- }
545
-
546
- maybe_value = parsed_script.ToLocalChecked()->Run(context);
547
- }
548
-
549
- prepare_result(maybe_value, trycatch, isolate, context, *result);
550
-
551
- IsolateData::Set(isolate, IsolateData::IN_GVL, true);
552
-
553
- return NULL;
554
- }
555
-
556
- static VALUE new_empty_failed_conv_obj() {
557
- // TODO isolate code that translates execption to ruby
558
- // exception so we can properly return it
559
- return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
560
- }
561
-
562
- // assumes isolate locking is in place
563
- static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
564
- Local<Value> value) {
565
-
566
- Isolate::Scope isolate_scope(isolate);
567
- HandleScope scope(isolate);
568
-
569
- StackCounter stackCounter(isolate);
570
-
571
- if (IsolateData::Get(isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED)) {
572
- return Qnil;
573
- }
574
-
575
- if (stackCounter.IsTooDeep()) {
576
- IsolateData::Set(isolate, IsolateData::DO_TERMINATE, true);
577
- isolate->TerminateExecution();
578
- return Qnil;
579
- }
580
-
581
- if (value->IsNull() || value->IsUndefined()){
582
- return Qnil;
583
- }
584
-
585
- if (value->IsInt32()) {
586
- return INT2FIX(value->Int32Value(context).ToChecked());
587
- }
588
-
589
- if (value->IsNumber()) {
590
- return rb_float_new(value->NumberValue(context).ToChecked());
591
- }
592
-
593
- if (value->IsTrue()) {
594
- return Qtrue;
595
- }
596
-
597
- if (value->IsFalse()) {
598
- return Qfalse;
599
- }
600
-
601
- if (value->IsArray()) {
602
- VALUE rb_array = rb_ary_new();
603
- Local<Array> arr = Local<Array>::Cast(value);
604
- for(uint32_t i=0; i < arr->Length(); i++) {
605
- MaybeLocal<Value> element = arr->Get(context, i);
606
- if (element.IsEmpty()) {
607
- continue;
608
- }
609
- VALUE rb_elem = convert_v8_to_ruby(isolate, context, element.ToLocalChecked());
610
- if (rb_funcall(rb_elem, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
611
- return rb_elem;
612
- }
613
- rb_ary_push(rb_array, rb_elem);
614
- }
615
- return rb_array;
616
- }
617
-
618
- if (value->IsFunction()){
619
- return rb_funcall(rb_cJavaScriptFunction, rb_intern("new"), 0);
620
- }
621
-
622
- if (value->IsDate()){
623
- double ts = Local<Date>::Cast(value)->ValueOf();
624
- double secs = ts/1000;
625
- long nanos = round((secs - floor(secs)) * 1000000);
626
-
627
- return rb_time_new(secs, nanos);
628
- }
629
-
630
- if (value->IsObject()) {
631
- VALUE rb_hash = rb_hash_new();
632
- TryCatch trycatch(isolate);
633
-
634
- Local<Object> object = value->ToObject(context).ToLocalChecked();
635
- auto maybe_props = object->GetOwnPropertyNames(context);
636
- if (!maybe_props.IsEmpty()) {
637
- Local<Array> props = maybe_props.ToLocalChecked();
638
- for(uint32_t i=0; i < props->Length(); i++) {
639
- MaybeLocal<Value> key = props->Get(context, i);
640
- if (key.IsEmpty()) {
641
- return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
642
- }
643
- VALUE rb_key = convert_v8_to_ruby(isolate, context, key.ToLocalChecked());
644
-
645
- MaybeLocal<Value> prop_value = object->Get(context, key.ToLocalChecked());
646
- // this may have failed due to Get raising
647
- if (prop_value.IsEmpty() || trycatch.HasCaught()) {
648
- return new_empty_failed_conv_obj();
649
- }
650
-
651
- VALUE rb_value = convert_v8_to_ruby(
652
- isolate, context, prop_value.ToLocalChecked());
653
- rb_hash_aset(rb_hash, rb_key, rb_value);
654
- }
655
- }
656
- return rb_hash;
657
- }
658
-
659
- if (value->IsSymbol()) {
660
- v8::String::Utf8Value symbol_name(isolate,
661
- Local<Symbol>::Cast(value)->Description(isolate));
662
-
663
- VALUE str_symbol = rb_utf8_str_new(*symbol_name, symbol_name.length());
664
-
665
- return rb_str_intern(str_symbol);
666
- }
667
-
668
- MaybeLocal<String> rstr_maybe = value->ToString(context);
669
-
670
- if (rstr_maybe.IsEmpty()) {
671
- return Qnil;
672
- } else {
673
- Local<String> rstr = rstr_maybe.ToLocalChecked();
674
- return rb_utf8_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate));
675
- }
676
- }
677
-
678
- static VALUE convert_v8_to_ruby(Isolate* isolate,
679
- const Persistent<Context>& context,
680
- Local<Value> value) {
681
- HandleScope scope(isolate);
682
- return convert_v8_to_ruby(isolate,
683
- Local<Context>::New(isolate, context),
684
- value);
685
- }
686
-
687
- static VALUE convert_v8_to_ruby(Isolate* isolate,
688
- const Persistent<Context>& context,
689
- const Persistent<Value>& value) {
690
- HandleScope scope(isolate);
691
- return convert_v8_to_ruby(isolate,
692
- Local<Context>::New(isolate, context),
693
- Local<Value>::New(isolate, value));
694
- }
695
-
696
- static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context, VALUE value) {
697
- EscapableHandleScope scope(isolate);
698
-
699
- Local<Array> array;
700
- Local<Object> object;
701
- VALUE hash_as_array;
702
- VALUE pair;
703
- int i;
704
- long length;
705
- long fixnum;
706
- VALUE klass;
707
-
708
- switch (TYPE(value)) {
709
- case T_FIXNUM:
710
- fixnum = NUM2LONG(value);
711
- if (fixnum > INT_MAX)
712
- {
713
- return scope.Escape(Number::New(isolate, (double)fixnum));
714
- }
715
- return scope.Escape(Integer::New(isolate, (int)fixnum));
716
- case T_FLOAT:
717
- return scope.Escape(Number::New(isolate, NUM2DBL(value)));
718
- case T_STRING:
719
- return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, RSTRING_LENINT(value)).ToLocalChecked());
720
- case T_NIL:
721
- return scope.Escape(Null(isolate));
722
- case T_TRUE:
723
- return scope.Escape(True(isolate));
724
- case T_FALSE:
725
- return scope.Escape(False(isolate));
726
- case T_ARRAY:
727
- length = RARRAY_LEN(value);
728
- array = Array::New(isolate, (int)length);
729
- for(i=0; i<length; i++) {
730
- Maybe<bool> success = array->Set(context, i, convert_ruby_to_v8(isolate, context, rb_ary_entry(value, i)));
731
- (void)(success);
732
- }
733
- return scope.Escape(array);
734
- case T_HASH:
735
- object = Object::New(isolate);
736
- hash_as_array = rb_funcall(value, rb_intern("to_a"), 0);
737
- length = RARRAY_LEN(hash_as_array);
738
- for(i=0; i<length; i++) {
739
- pair = rb_ary_entry(hash_as_array, i);
740
- Maybe<bool> success = object->Set(context, convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 0)),
741
- convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 1)));
742
- (void)(success);
743
- }
744
- return scope.Escape(object);
745
- case T_SYMBOL:
746
- value = rb_funcall(value, rb_intern("to_s"), 0);
747
- return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, RSTRING_LENINT(value)).ToLocalChecked());
748
- case T_DATA:
749
- klass = rb_funcall(value, rb_intern("class"), 0);
750
- if (klass == rb_cTime || klass == rb_cDateTime)
751
- {
752
- if (klass == rb_cDateTime)
753
- {
754
- value = rb_funcall(value, rb_intern("to_time"), 0);
755
- }
756
- value = rb_funcall(value, rb_intern("to_f"), 0);
757
- return scope.Escape(Date::New(context, NUM2DBL(value) * 1000).ToLocalChecked());
758
- }
759
- case T_OBJECT:
760
- case T_CLASS:
761
- case T_ICLASS:
762
- case T_MODULE:
763
- case T_REGEXP:
764
- case T_MATCH:
765
- case T_STRUCT:
766
- case T_BIGNUM:
767
- case T_FILE:
768
- case T_UNDEF:
769
- case T_NODE:
770
- default:
771
- return scope.Escape(String::NewFromUtf8Literal(isolate, "Undefined Conversion"));
772
- }
773
- }
774
-
775
- static void unblock_eval(void *ptr) {
776
- EvalParams* eval = (EvalParams*)ptr;
777
- eval->context_info->isolate_info->interrupted = true;
778
- }
779
-
780
- /*
781
- * The implementations of the run_extra_code(), create_snapshot_data_blob() and
782
- * warm_up_snapshot_data_blob() functions have been derived from V8's test suite.
783
- */
784
- static bool run_extra_code(Isolate *isolate, Local<v8::Context> context,
785
- const char *utf8_source, const char *name) {
786
- Context::Scope context_scope(context);
787
- TryCatch try_catch(isolate);
788
- Local<String> source_string;
789
- if (!String::NewFromUtf8(isolate, utf8_source).ToLocal(&source_string)) {
790
- return false;
791
- }
792
- Local<String> resource_name =
793
- String::NewFromUtf8(isolate, name).ToLocalChecked();
794
- ScriptOrigin origin(isolate, resource_name);
795
- ScriptCompiler::Source source(source_string, origin);
796
- Local<Script> script;
797
- if (!ScriptCompiler::Compile(context, &source).ToLocal(&script))
798
- return false;
799
- if (script->Run(context).IsEmpty()) return false;
800
- return true;
801
- }
802
-
803
- static StartupData
804
- create_snapshot_data_blob(const char *embedded_source = nullptr) {
805
- Isolate *isolate = Isolate::Allocate();
806
-
807
- // Optionally run a script to embed, and serialize to create a snapshot blob.
808
- SnapshotCreator snapshot_creator(isolate);
809
- {
810
- HandleScope scope(isolate);
811
- Local<v8::Context> context = v8::Context::New(isolate);
812
- if (embedded_source != nullptr &&
813
- !run_extra_code(isolate, context, embedded_source, "<embedded>")) {
814
- return {};
815
- }
816
- snapshot_creator.SetDefaultContext(context);
817
- }
818
- return snapshot_creator.CreateBlob(
819
- SnapshotCreator::FunctionCodeHandling::kClear);
820
- }
821
-
822
- static
823
- StartupData warm_up_snapshot_data_blob(StartupData cold_snapshot_blob,
824
- const char *warmup_source) {
825
- // Use following steps to create a warmed up snapshot blob from a cold one:
826
- // - Create a new isolate from the cold snapshot.
827
- // - Create a new context to run the warmup script. This will trigger
828
- // compilation of executed functions.
829
- // - Create a new context. This context will be unpolluted.
830
- // - Serialize the isolate and the second context into a new snapshot blob.
831
- StartupData result = {nullptr, 0};
832
-
833
- if (cold_snapshot_blob.raw_size > 0 && cold_snapshot_blob.data != nullptr &&
834
- warmup_source != NULL) {
835
- SnapshotCreator snapshot_creator(nullptr, &cold_snapshot_blob);
836
- Isolate *isolate = snapshot_creator.GetIsolate();
837
- {
838
- HandleScope scope(isolate);
839
- Local<Context> context = Context::New(isolate);
840
- if (!run_extra_code(isolate, context, warmup_source, "<warm-up>")) {
841
- return result;
842
- }
843
- }
844
- {
845
- HandleScope handle_scope(isolate);
846
- isolate->ContextDisposedNotification(false);
847
- Local<Context> context = Context::New(isolate);
848
- snapshot_creator.SetDefaultContext(context);
849
- }
850
- result = snapshot_creator.CreateBlob(
851
- SnapshotCreator::FunctionCodeHandling::kKeep);
852
- }
853
- return result;
854
- }
855
-
856
- static VALUE rb_snapshot_size(VALUE self) {
857
- SnapshotInfo* snapshot_info;
858
- TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
859
-
860
- return INT2NUM(snapshot_info->raw_size);
861
- }
862
-
863
- static VALUE rb_snapshot_load(VALUE self, VALUE str) {
864
- SnapshotInfo* snapshot_info;
865
- TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
866
-
867
- Check_Type(str, T_STRING);
868
-
869
- init_v8();
870
-
871
- StartupData startup_data = create_snapshot_data_blob(RSTRING_PTR(str));
872
-
873
- if (startup_data.data == NULL && startup_data.raw_size == 0) {
874
- rb_raise(rb_eSnapshotError, "Could not create snapshot, most likely the source is incorrect");
875
- }
876
-
877
- snapshot_info->data = startup_data.data;
878
- snapshot_info->raw_size = startup_data.raw_size;
879
-
880
- return Qnil;
881
- }
882
-
883
- static VALUE rb_snapshot_dump(VALUE self) {
884
- SnapshotInfo* snapshot_info;
885
- TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
886
-
887
- return rb_str_new(snapshot_info->data, snapshot_info->raw_size);
888
- }
889
-
890
- static VALUE rb_snapshot_warmup_unsafe(VALUE self, VALUE str) {
891
- SnapshotInfo* snapshot_info;
892
- TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
893
-
894
- Check_Type(str, T_STRING);
895
-
896
- init_v8();
897
-
898
- StartupData cold_startup_data = {snapshot_info->data, snapshot_info->raw_size};
899
- StartupData warm_startup_data = warm_up_snapshot_data_blob(cold_startup_data, RSTRING_PTR(str));
900
-
901
- if (warm_startup_data.data == NULL && warm_startup_data.raw_size == 0) {
902
- rb_raise(rb_eSnapshotError, "Could not warm up snapshot, most likely the source is incorrect");
903
- } else {
904
- delete[] snapshot_info->data;
905
-
906
- snapshot_info->data = warm_startup_data.data;
907
- snapshot_info->raw_size = warm_startup_data.raw_size;
908
- }
909
-
910
- return self;
911
- }
912
-
913
- void IsolateInfo::init(SnapshotInfo* snapshot_info) {
914
- allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
915
-
916
- Isolate::CreateParams create_params;
917
- create_params.array_buffer_allocator = allocator;
918
-
919
- if (snapshot_info) {
920
- int raw_size = snapshot_info->raw_size;
921
- char* data = new char[raw_size];
922
- memcpy(data, snapshot_info->data, raw_size);
923
-
924
- startup_data = new StartupData;
925
- startup_data->data = data;
926
- startup_data->raw_size = raw_size;
927
-
928
- create_params.snapshot_blob = startup_data;
929
- }
930
-
931
- isolate = Isolate::New(create_params);
932
- }
933
-
934
- static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) {
935
- IsolateInfo* isolate_info;
936
- TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
937
-
938
- init_v8();
939
-
940
- SnapshotInfo* snapshot_info = nullptr;
941
- if (!NIL_P(snapshot)) {
942
- TypedData_Get_Struct(snapshot, SnapshotInfo, &snapshot_type, snapshot_info);
943
- }
944
-
945
- isolate_info->init(snapshot_info);
946
- isolate_info->hold();
947
-
948
- return Qnil;
949
- }
950
-
951
- static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) {
952
- IsolateInfo* isolate_info;
953
- TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
954
-
955
- if (current_platform == NULL) return Qfalse;
956
-
957
- double duration = NUM2DBL(idle_time_in_ms) / 1000.0;
958
- double now = current_platform->MonotonicallyIncreasingTime();
959
- return isolate_info->isolate->IdleNotificationDeadline(now + duration) ? Qtrue : Qfalse;
960
- }
961
-
962
- static VALUE rb_isolate_low_memory_notification(VALUE self) {
963
- IsolateInfo* isolate_info;
964
- TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
965
-
966
- if (current_platform == NULL) return Qfalse;
967
-
968
- Locker guard { isolate_info->isolate };
969
-
970
- isolate_info->isolate->LowMemoryNotification();
971
- return Qnil;
972
- }
973
-
974
- static VALUE rb_isolate_pump_message_loop(VALUE self) {
975
- IsolateInfo* isolate_info;
976
- TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
977
-
978
- if (current_platform == NULL) return Qfalse;
979
-
980
- Locker guard { isolate_info->isolate };
981
-
982
- if (platform::PumpMessageLoop(current_platform.get(), isolate_info->isolate)){
983
- return Qtrue;
984
- } else {
985
- return Qfalse;
986
- }
987
- }
988
-
989
- static VALUE rb_context_init_unsafe(VALUE self, VALUE isolate, VALUE snap) {
990
- ContextInfo* context_info;
991
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
992
-
993
- init_v8();
994
-
995
- IsolateInfo* isolate_info;
996
-
997
- if (NIL_P(isolate) || !rb_obj_is_kind_of(isolate, rb_cIsolate)) {
998
- isolate_info = new IsolateInfo();
999
-
1000
- SnapshotInfo *snapshot_info = nullptr;
1001
- if (!NIL_P(snap) && rb_obj_is_kind_of(snap, rb_cSnapshot)) {
1002
- TypedData_Get_Struct(snap, SnapshotInfo, &snapshot_type, snapshot_info);
1003
- }
1004
- isolate_info->init(snapshot_info);
1005
- } else { // given isolate or snapshot
1006
- TypedData_Get_Struct(isolate, IsolateInfo, &isolate_type, isolate_info);
1007
- }
1008
-
1009
- context_info->isolate_info = isolate_info;
1010
- isolate_info->hold();
1011
-
1012
- {
1013
- // the ruby lock is needed if this isn't a new isolate
1014
- IsolateInfo::Lock ruby_lock(isolate_info->mutex);
1015
- Locker lock(isolate_info->isolate);
1016
- Isolate::Scope isolate_scope(isolate_info->isolate);
1017
- HandleScope handle_scope(isolate_info->isolate);
1018
-
1019
- Local<Context> context = Context::New(isolate_info->isolate);
1020
-
1021
- context_info->context = new Persistent<Context>();
1022
- context_info->context->Reset(isolate_info->isolate, context);
1023
- }
1024
-
1025
- if (Qnil == rb_cDateTime && rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, rb_str_new2("DateTime")) == Qtrue)
1026
- {
1027
- rb_cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime"));
1028
- }
1029
-
1030
- return Qnil;
1031
- }
1032
-
1033
- static VALUE convert_result_to_ruby(VALUE self /* context */,
1034
- EvalResult& result) {
1035
- ContextInfo *context_info;
1036
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1037
-
1038
- Isolate *isolate = context_info->isolate_info->isolate;
1039
- Persistent<Context> *p_ctx = context_info->context;
1040
-
1041
- VALUE message = Qnil;
1042
- VALUE backtrace = Qnil;
1043
- {
1044
- Locker lock(isolate);
1045
- if (result.message) {
1046
- message = convert_v8_to_ruby(isolate, *p_ctx, *result.message);
1047
- result.message->Reset();
1048
- delete result.message;
1049
- result.message = nullptr;
1050
- }
1051
-
1052
- if (result.backtrace) {
1053
- backtrace = convert_v8_to_ruby(isolate, *p_ctx, *result.backtrace);
1054
- result.backtrace->Reset();
1055
- delete result.backtrace;
1056
- }
1057
- }
1058
-
1059
- // NOTE: this is very important, we can not do an rb_raise from within
1060
- // a v8 scope, if we do the scope is never cleaned up properly and we leak
1061
- if (!result.parsed) {
1062
- if(TYPE(message) == T_STRING) {
1063
- rb_raise(rb_eParseError, "%" PRIsVALUE, message);
1064
- } else {
1065
- rb_raise(rb_eParseError, "Unknown JavaScript Error during parse");
1066
- }
1067
- }
1068
-
1069
- if (!result.executed) {
1070
- VALUE ruby_exception = rb_iv_get(self, "@current_exception");
1071
- if (ruby_exception == Qnil) {
1072
- bool mem_softlimit_reached = IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_REACHED);
1073
- bool marshal_stack_maxdepth_reached = IsolateData::Get(isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED);
1074
- // If we were terminated or have the memory softlimit flag set
1075
- if (marshal_stack_maxdepth_reached) {
1076
- ruby_exception = rb_eScriptRuntimeError;
1077
- message = rb_utf8_str_new_literal("Marshal object depth too deep. Script terminated.");
1078
- } else if (result.terminated || mem_softlimit_reached) {
1079
- ruby_exception = mem_softlimit_reached ? rb_eV8OutOfMemoryError : rb_eScriptTerminatedError;
1080
- } else {
1081
- ruby_exception = rb_eScriptRuntimeError;
1082
- }
1083
-
1084
- // exception report about what happened
1085
- if (TYPE(backtrace) == T_STRING) {
1086
- rb_raise(ruby_exception, "%" PRIsVALUE, backtrace);
1087
- } else if(TYPE(message) == T_STRING) {
1088
- rb_raise(ruby_exception, "%" PRIsVALUE, message);
1089
- } else {
1090
- rb_raise(ruby_exception, "Unknown JavaScript Error during execution");
1091
- }
1092
- } else if (rb_obj_is_kind_of(ruby_exception, rb_eException)) {
1093
- rb_exc_raise(ruby_exception);
1094
- } else {
1095
- VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0);
1096
- rb_raise(CLASS_OF(ruby_exception), "%" PRIsVALUE, rb_str);
1097
- }
1098
- }
1099
-
1100
- VALUE ret = Qnil;
1101
-
1102
- // New scope for return value
1103
- {
1104
- Locker lock(isolate);
1105
- Isolate::Scope isolate_scope(isolate);
1106
- HandleScope handle_scope(isolate);
1107
-
1108
- Local<Value> tmp = Local<Value>::New(isolate, *result.value);
1109
-
1110
- if (result.json) {
1111
- Local<String> rstr = tmp->ToString(p_ctx->Get(isolate)).ToLocalChecked();
1112
- VALUE json_string = rb_utf8_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate));
1113
- ret = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string);
1114
- } else {
1115
- StackCounter::Reset(isolate);
1116
- ret = convert_v8_to_ruby(isolate, *p_ctx, tmp);
1117
- }
1118
-
1119
- result.value->Reset();
1120
- delete result.value;
1121
- }
1122
-
1123
- if (rb_funcall(ret, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
1124
- // TODO try to recover stack trace from the conversion error
1125
- rb_raise(rb_eScriptRuntimeError, "Error converting JS object to Ruby object");
1126
- }
1127
-
1128
-
1129
- return ret;
1130
- }
1131
-
1132
- static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
1133
-
1134
- EvalParams eval_params;
1135
- EvalResult eval_result;
1136
- ContextInfo* context_info;
1137
-
1138
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1139
- Isolate* isolate = context_info->isolate_info->isolate;
1140
-
1141
- Check_Type(str, T_STRING);
1142
-
1143
- if (!NIL_P(filename)) {
1144
- Check_Type(filename, T_STRING);
1145
- }
1146
-
1147
- {
1148
- Locker lock(isolate);
1149
- Isolate::Scope isolate_scope(isolate);
1150
- HandleScope handle_scope(isolate);
1151
-
1152
- Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str),
1153
- NewStringType::kNormal, RSTRING_LENINT(str)).ToLocalChecked();
1154
-
1155
- Local<String> local_filename;
1156
-
1157
- if (filename != Qnil) {
1158
- local_filename = String::NewFromUtf8(isolate, RSTRING_PTR(filename),
1159
- NewStringType::kNormal, RSTRING_LENINT(filename)).ToLocalChecked();
1160
- eval_params.filename = &local_filename;
1161
- } else {
1162
- eval_params.filename = NULL;
1163
- }
1164
-
1165
- eval_params.context_info = context_info;
1166
- eval_params.eval = &eval;
1167
- eval_params.result = &eval_result;
1168
- eval_params.timeout = 0;
1169
- eval_params.max_memory = 0;
1170
- eval_params.marshal_stackdepth = 0;
1171
- VALUE timeout = rb_iv_get(self, "@timeout");
1172
- if (timeout != Qnil) {
1173
- eval_params.timeout = (useconds_t)NUM2LONG(timeout);
1174
- }
1175
-
1176
- VALUE mem_softlimit = rb_iv_get(self, "@max_memory");
1177
- if (mem_softlimit != Qnil) {
1178
- eval_params.max_memory = (size_t)NUM2ULONG(mem_softlimit);
1179
- }
1180
-
1181
- VALUE stack_depth = rb_iv_get(self, "@marshal_stack_depth");
1182
- if (stack_depth != Qnil) {
1183
- eval_params.marshal_stackdepth = (size_t)NUM2ULONG(stack_depth);
1184
- }
1185
-
1186
- eval_result.message = NULL;
1187
- eval_result.backtrace = NULL;
1188
-
1189
- rb_thread_call_without_gvl(nogvl_context_eval, &eval_params, unblock_eval, &eval_params);
1190
- }
1191
-
1192
- return convert_result_to_ruby(self, eval_result);
1193
- }
1194
-
1195
- typedef struct {
1196
- VALUE callback;
1197
- int length;
1198
- VALUE ruby_args;
1199
- bool failed;
1200
- } protected_callback_data;
1201
-
1202
- static VALUE protected_callback(VALUE rdata) {
1203
- protected_callback_data* data = (protected_callback_data*)rdata;
1204
- VALUE result;
1205
-
1206
- if (data->length > 0) {
1207
- result = rb_funcall2(data->callback, rb_intern("call"), data->length,
1208
- RARRAY_PTR(data->ruby_args));
1209
- RB_GC_GUARD(data->ruby_args);
1210
- } else {
1211
- result = rb_funcall(data->callback, rb_intern("call"), 0);
1212
- }
1213
- return result;
1214
- }
1215
-
1216
- static
1217
- VALUE rescue_callback(VALUE rdata, VALUE exception) {
1218
- protected_callback_data* data = (protected_callback_data*)rdata;
1219
- data->failed = true;
1220
- return exception;
1221
- }
1222
-
1223
- static void*
1224
- gvl_ruby_callback(void* data) {
1225
-
1226
- FunctionCallbackInfo<Value>* args = (FunctionCallbackInfo<Value>*)data;
1227
- VALUE ruby_args = Qnil;
1228
- int length = args->Length();
1229
- VALUE callback;
1230
- VALUE result;
1231
- VALUE self;
1232
- VALUE parent;
1233
- ContextInfo* context_info;
1234
-
1235
- {
1236
- HandleScope scope(args->GetIsolate());
1237
- Local<External> external = Local<External>::Cast(args->Data());
1238
-
1239
- self = (VALUE)(external->Value());
1240
- callback = rb_iv_get(self, "@callback");
1241
-
1242
- parent = rb_iv_get(self, "@parent");
1243
- if (NIL_P(parent) || !rb_obj_is_kind_of(parent, rb_cContext)) {
1244
- return NULL;
1245
- }
1246
-
1247
- TypedData_Get_Struct(parent, ContextInfo, &context_type, context_info);
1248
-
1249
- if (length > 0) {
1250
- ruby_args = rb_ary_tmp_new(length);
1251
- }
1252
-
1253
- for (int i = 0; i < length; i++) {
1254
- Local<Value> value = ((*args)[i]).As<Value>();
1255
- StackCounter::Reset(args->GetIsolate());
1256
- VALUE tmp = convert_v8_to_ruby(args->GetIsolate(),
1257
- *context_info->context, value);
1258
- rb_ary_push(ruby_args, tmp);
1259
- }
1260
- }
1261
-
1262
- // may raise exception stay clear of handle scope
1263
- protected_callback_data callback_data;
1264
- callback_data.length = length;
1265
- callback_data.callback = callback;
1266
- callback_data.ruby_args = ruby_args;
1267
- callback_data.failed = false;
1268
-
1269
- if (IsolateData::Get(args->GetIsolate(), IsolateData::DO_TERMINATE)) {
1270
- args->GetIsolate()->ThrowException(
1271
- String::NewFromUtf8Literal(args->GetIsolate(),
1272
- "Terminated execution during transition from Ruby to JS"));
1273
- args->GetIsolate()->TerminateExecution();
1274
- if (length > 0) {
1275
- rb_ary_clear(ruby_args);
1276
- }
1277
- return NULL;
1278
- }
1279
-
1280
- VALUE callback_data_value = (VALUE)&callback_data;
1281
-
1282
- // TODO: use rb_vrescue2 in Ruby 2.7 and above
1283
- result = rb_rescue2(MR_METHOD_FUNC(protected_callback), callback_data_value,
1284
- MR_METHOD_FUNC(rescue_callback), callback_data_value, rb_eException, (VALUE)0);
1285
-
1286
- if(callback_data.failed) {
1287
- rb_iv_set(parent, "@current_exception", result);
1288
- args->GetIsolate()->ThrowException(String::NewFromUtf8Literal(args->GetIsolate(), "Ruby exception"));
1289
- }
1290
- else {
1291
- HandleScope scope(args->GetIsolate());
1292
- Handle<Value> v8_result = convert_ruby_to_v8(args->GetIsolate(), context_info->context->Get(args->GetIsolate()), result);
1293
- args->GetReturnValue().Set(v8_result);
1294
- }
1295
-
1296
- if (length > 0) {
1297
- rb_ary_clear(ruby_args);
1298
- }
1299
-
1300
- if (IsolateData::Get(args->GetIsolate(), IsolateData::DO_TERMINATE)) {
1301
- args->GetIsolate()->TerminateExecution();
1302
- }
1303
-
1304
- return NULL;
1305
- }
1306
-
1307
- static void ruby_callback(const FunctionCallbackInfo<Value>& args) {
1308
- bool has_gvl = IsolateData::Get(args.GetIsolate(), IsolateData::IN_GVL);
1309
-
1310
- if(has_gvl) {
1311
- gvl_ruby_callback((void*)&args);
1312
- } else {
1313
- IsolateData::Set(args.GetIsolate(), IsolateData::IN_GVL, true);
1314
- rb_thread_call_with_gvl(gvl_ruby_callback, (void*)(&args));
1315
- IsolateData::Set(args.GetIsolate(), IsolateData::IN_GVL, false);
1316
- }
1317
- }
1318
-
1319
-
1320
- static VALUE rb_external_function_notify_v8(VALUE self) {
1321
-
1322
- ContextInfo* context_info;
1323
-
1324
- VALUE parent = rb_iv_get(self, "@parent");
1325
- VALUE name = rb_iv_get(self, "@name");
1326
- VALUE parent_object = rb_iv_get(self, "@parent_object");
1327
- VALUE parent_object_eval = rb_iv_get(self, "@parent_object_eval");
1328
-
1329
- bool parse_error = false;
1330
- bool attach_error = false;
1331
-
1332
- TypedData_Get_Struct(parent, ContextInfo, &context_type, context_info);
1333
- Isolate* isolate = context_info->isolate_info->isolate;
1334
-
1335
- {
1336
- Locker lock(isolate);
1337
- Isolate::Scope isolate_scope(isolate);
1338
- HandleScope handle_scope(isolate);
1339
-
1340
- Local<Context> context = context_info->context->Get(isolate);
1341
- Context::Scope context_scope(context);
1342
-
1343
- Local<String> v8_str =
1344
- String::NewFromUtf8(isolate, RSTRING_PTR(name),
1345
- NewStringType::kNormal, RSTRING_LENINT(name))
1346
- .ToLocalChecked();
1347
-
1348
- // Note that self (rb_cExternalFunction) is a pure Ruby T_OBJECT,
1349
- // not a T_DATA type like most other classes in this file
1350
- Local<Value> external = External::New(isolate, (void *)self);
1351
-
1352
- if (parent_object == Qnil) {
1353
- Maybe<bool> success = context->Global()->Set(
1354
- context,
1355
- v8_str,
1356
- FunctionTemplate::New(isolate, ruby_callback, external)
1357
- ->GetFunction(context)
1358
- .ToLocalChecked());
1359
- (void)success;
1360
-
1361
- } else {
1362
- Local<String> eval =
1363
- String::NewFromUtf8(isolate, RSTRING_PTR(parent_object_eval),
1364
- NewStringType::kNormal,
1365
- RSTRING_LENINT(parent_object_eval))
1366
- .ToLocalChecked();
1367
-
1368
- MaybeLocal<Script> parsed_script = Script::Compile(context, eval);
1369
- if (parsed_script.IsEmpty()) {
1370
- parse_error = true;
1371
- } else {
1372
- MaybeLocal<Value> maybe_value =
1373
- parsed_script.ToLocalChecked()->Run(context);
1374
- attach_error = true;
1375
-
1376
- if (!maybe_value.IsEmpty()) {
1377
- Local<Value> value = maybe_value.ToLocalChecked();
1378
- if (value->IsObject()) {
1379
- Maybe<bool> success = value.As<Object>()->Set(
1380
- context,
1381
- v8_str,
1382
- FunctionTemplate::New(isolate, ruby_callback, external)
1383
- ->GetFunction(context)
1384
- .ToLocalChecked());
1385
- (void)success;
1386
- attach_error = false;
1387
- }
1388
- }
1389
- }
1390
- }
1391
- }
1392
-
1393
- // always raise out of V8 context
1394
- if (parse_error) {
1395
- rb_raise(rb_eParseError, "Invalid object %" PRIsVALUE, parent_object);
1396
- }
1397
-
1398
- if (attach_error) {
1399
- rb_raise(rb_eParseError, "Was expecting %" PRIsVALUE" to be an object", parent_object);
1400
- }
1401
-
1402
- return Qnil;
1403
- }
1404
-
1405
- static VALUE rb_context_isolate_mutex(VALUE self) {
1406
- ContextInfo* context_info;
1407
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1408
-
1409
- if (!context_info->isolate_info) {
1410
- rb_raise(rb_eScriptRuntimeError, "Context has no Isolate available anymore");
1411
- }
1412
-
1413
- return context_info->isolate_info->mutex;
1414
- }
1415
-
1416
- IsolateInfo::~IsolateInfo() {
1417
- if (isolate) {
1418
- if (this->interrupted) {
1419
- fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, "
1420
- "it can not be disposed and memory will not be "
1421
- "reclaimed till the Ruby process exits.\n");
1422
- } else {
1423
- if (this->pid != getpid() && !single_threaded) {
1424
- fprintf(stderr, "WARNING: V8 isolate was forked, "
1425
- "it can not be disposed and "
1426
- "memory will not be reclaimed "
1427
- "till the Ruby process exits.\n"
1428
- "It is VERY likely your process will hang.\n"
1429
- "If you wish to use v8 in forked environment "
1430
- "please ensure the platform is initialized with:\n"
1431
- "MiniRacer::Platform.set_flags! :single_threaded\n"
1432
- );
1433
- } else {
1434
- isolate->Dispose();
1435
- }
1436
- }
1437
- isolate = nullptr;
1438
- }
1439
-
1440
- if (startup_data) {
1441
- delete[] startup_data->data;
1442
- delete startup_data;
1443
- }
1444
-
1445
- delete allocator;
1446
- }
1447
-
1448
- static void free_context_raw(void *arg) {
1449
- ContextInfo* context_info = (ContextInfo*)arg;
1450
- IsolateInfo* isolate_info = context_info->isolate_info;
1451
- Persistent<Context>* context = context_info->context;
1452
-
1453
- if (context && isolate_info && isolate_info->isolate) {
1454
- Locker lock(isolate_info->isolate);
1455
- v8::Isolate::Scope isolate_scope(isolate_info->isolate);
1456
- context->Reset();
1457
- delete context;
1458
- }
1459
-
1460
- if (isolate_info) {
1461
- isolate_info->release();
1462
- }
1463
- }
1464
-
1465
- static void *free_context_thr(void* arg) {
1466
- if (ruby_exiting.load() == 0) {
1467
- free_context_raw(arg);
1468
- xfree(arg);
1469
- }
1470
- return NULL;
1471
- }
1472
-
1473
- // destroys everything except freeing the ContextInfo struct (see deallocate())
1474
- static void free_context(ContextInfo* context_info) {
1475
- IsolateInfo* isolate_info = context_info->isolate_info;
1476
-
1477
- if (isolate_info && isolate_info->refs() > 1) {
1478
- pthread_t free_context_thread;
1479
- ContextInfo* context_info_copy = ALLOC(ContextInfo);
1480
-
1481
- context_info_copy->isolate_info = context_info->isolate_info;
1482
- context_info_copy->context = context_info->context;
1483
- if (pthread_create(&free_context_thread, thread_attr_p,
1484
- free_context_thr, (void*)context_info_copy)) {
1485
- fprintf(stderr, "WARNING failed to release memory in MiniRacer, thread to release could not be created, process will leak memory\n");
1486
- xfree(context_info_copy);
1487
- }
1488
- } else {
1489
- free_context_raw(context_info);
1490
- }
1491
-
1492
- context_info->context = NULL;
1493
- context_info->isolate_info = NULL;
1494
- }
1495
-
1496
- static void deallocate_isolate(void* data) {
1497
-
1498
- IsolateInfo* isolate_info = (IsolateInfo*) data;
1499
-
1500
- isolate_info->release();
1501
- }
1502
-
1503
- static void mark_isolate(void* data) {
1504
- IsolateInfo* isolate_info = (IsolateInfo*) data;
1505
- isolate_info->mark();
1506
- }
1507
-
1508
- static size_t isolate_memsize(const void *ptr) {
1509
- const IsolateInfo *isolate_info = (const IsolateInfo *)ptr;
1510
- return sizeof(*isolate_info);
1511
- }
1512
-
1513
- static void deallocate(void* data) {
1514
- ContextInfo* context_info = (ContextInfo*)data;
1515
-
1516
- free_context(context_info);
1517
-
1518
- xfree(data);
1519
- }
1520
-
1521
- static size_t context_memsize(const void *ptr)
1522
- {
1523
- return sizeof(ContextInfo);
1524
- }
1525
-
1526
- static void mark_context(void* data) {
1527
- ContextInfo* context_info = (ContextInfo*)data;
1528
- if (context_info->isolate_info) {
1529
- context_info->isolate_info->mark();
1530
- }
1531
- }
1532
-
1533
- static void deallocate_snapshot(void * data) {
1534
- SnapshotInfo* snapshot_info = (SnapshotInfo*)data;
1535
- delete[] snapshot_info->data;
1536
- xfree(snapshot_info);
1537
- }
1538
-
1539
- static size_t snapshot_memsize(const void *data) {
1540
- SnapshotInfo* snapshot_info = (SnapshotInfo*)data;
1541
- return sizeof(*snapshot_info) + snapshot_info->raw_size;
1542
- }
1543
-
1544
- static VALUE allocate(VALUE klass) {
1545
- ContextInfo* context_info;
1546
- return TypedData_Make_Struct(klass, ContextInfo, &context_type, context_info);
1547
- }
1548
-
1549
- static VALUE allocate_snapshot(VALUE klass) {
1550
- SnapshotInfo* snapshot_info;
1551
-
1552
- return TypedData_Make_Struct(klass, SnapshotInfo, &snapshot_type, snapshot_info);
1553
- }
1554
-
1555
- static VALUE allocate_isolate(VALUE klass) {
1556
- IsolateInfo* isolate_info = new IsolateInfo();
1557
-
1558
- return TypedData_Wrap_Struct(klass, &isolate_type, isolate_info);
1559
- }
1560
-
1561
- static VALUE
1562
- rb_heap_stats(VALUE self) {
1563
-
1564
- ContextInfo* context_info;
1565
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1566
- Isolate* isolate;
1567
- v8::HeapStatistics stats;
1568
-
1569
- isolate = context_info->isolate_info ? context_info->isolate_info->isolate : NULL;
1570
-
1571
- VALUE rval = rb_hash_new();
1572
-
1573
- if (!isolate) {
1574
-
1575
- rb_hash_aset(rval, ID2SYM(rb_intern("total_physical_size")), ULONG2NUM(0));
1576
- rb_hash_aset(rval, ID2SYM(rb_intern("total_heap_size_executable")), ULONG2NUM(0));
1577
- rb_hash_aset(rval, ID2SYM(rb_intern("total_heap_size")), ULONG2NUM(0));
1578
- rb_hash_aset(rval, ID2SYM(rb_intern("used_heap_size")), ULONG2NUM(0));
1579
- rb_hash_aset(rval, ID2SYM(rb_intern("heap_size_limit")), ULONG2NUM(0));
1580
-
1581
- } else {
1582
- isolate->GetHeapStatistics(&stats);
1583
-
1584
- rb_hash_aset(rval, ID2SYM(rb_intern("total_physical_size")), ULONG2NUM(stats.total_physical_size()));
1585
- rb_hash_aset(rval, ID2SYM(rb_intern("total_heap_size_executable")), ULONG2NUM(stats.total_heap_size_executable()));
1586
- rb_hash_aset(rval, ID2SYM(rb_intern("total_heap_size")), ULONG2NUM(stats.total_heap_size()));
1587
- rb_hash_aset(rval, ID2SYM(rb_intern("used_heap_size")), ULONG2NUM(stats.used_heap_size()));
1588
- rb_hash_aset(rval, ID2SYM(rb_intern("heap_size_limit")), ULONG2NUM(stats.heap_size_limit()));
1589
- }
1590
-
1591
- return rval;
1592
- }
1593
-
1594
- // https://github.com/bnoordhuis/node-heapdump/blob/master/src/heapdump.cc
1595
- class FileOutputStream : public OutputStream {
1596
- public:
1597
- int err;
1598
-
1599
- FileOutputStream(int fd) : fd(fd) { err = 0; }
1600
-
1601
- virtual int GetChunkSize() {
1602
- return 65536;
1603
- }
1604
-
1605
- virtual void EndOfStream() {}
1606
-
1607
- virtual WriteResult WriteAsciiChunk(char* data, int size) {
1608
- size_t len = static_cast<size_t>(size);
1609
-
1610
- while (len) {
1611
- ssize_t w = write(fd, data, len);
1612
-
1613
- if (w > 0) {
1614
- data += w;
1615
- len -= w;
1616
- } else if (w < 0) {
1617
- err = errno;
1618
- return kAbort;
1619
- } else { /* w == 0, could be out-of-space */
1620
- err = -1;
1621
- return kAbort;
1622
- }
1623
- }
1624
- return kContinue;
1625
- }
1626
-
1627
- private:
1628
- int fd;
1629
- };
1630
-
1631
-
1632
- static VALUE
1633
- rb_heap_snapshot(VALUE self, VALUE file) {
1634
-
1635
- rb_io_t *fptr;
1636
-
1637
- fptr = RFILE(file)->fptr;
1638
-
1639
- if (!fptr) return Qfalse;
1640
-
1641
- // prepare for unbuffered write(2) below:
1642
- rb_funcall(file, rb_intern("flush"), 0);
1643
-
1644
- ContextInfo* context_info;
1645
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1646
- Isolate* isolate;
1647
- isolate = context_info->isolate_info ? context_info->isolate_info->isolate : NULL;
1648
-
1649
- if (!isolate) return Qfalse;
1650
-
1651
- Locker lock(isolate);
1652
- Isolate::Scope isolate_scope(isolate);
1653
- HandleScope handle_scope(isolate);
1654
-
1655
- HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1656
-
1657
- const HeapSnapshot* const snap = heap_profiler->TakeHeapSnapshot();
1658
-
1659
- FileOutputStream stream(fptr->fd);
1660
- snap->Serialize(&stream, HeapSnapshot::kJSON);
1661
-
1662
- const_cast<HeapSnapshot*>(snap)->Delete();
1663
-
1664
- /* TODO: perhaps rb_sys_fail here */
1665
- if (stream.err) return Qfalse;
1666
-
1667
- return Qtrue;
1668
- }
1669
-
1670
- static VALUE
1671
- rb_context_stop(VALUE self) {
1672
-
1673
- ContextInfo* context_info;
1674
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1675
-
1676
- Isolate* isolate = context_info->isolate_info->isolate;
1677
-
1678
- // flag for termination
1679
- IsolateData::Set(isolate, IsolateData::DO_TERMINATE, true);
1680
-
1681
- isolate->TerminateExecution();
1682
- rb_funcall(self, rb_intern("stop_attached"), 0);
1683
-
1684
- return Qnil;
1685
- }
1686
-
1687
- static VALUE
1688
- rb_context_dispose(VALUE self) {
1689
-
1690
- ContextInfo* context_info;
1691
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1692
-
1693
- free_context(context_info);
1694
-
1695
- return Qnil;
1696
- }
1697
-
1698
- static void*
1699
- nogvl_context_call(void *args) {
1700
-
1701
- FunctionCall *call = (FunctionCall *) args;
1702
- if (!call) {
1703
- return NULL;
1704
- }
1705
- IsolateInfo *isolate_info = call->context_info->isolate_info;
1706
- Isolate* isolate = isolate_info->isolate;
1707
-
1708
- IsolateData::Set(isolate, IsolateData::IN_GVL, false);
1709
- IsolateData::Set(isolate, IsolateData::DO_TERMINATE, false);
1710
-
1711
- if (call->max_memory > 0) {
1712
- IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_MAX, call->max_memory);
1713
- IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_REACHED, false);
1714
- if (!isolate_info->added_gc_cb) {
1715
- isolate->AddGCEpilogueCallback(gc_callback);
1716
- isolate_info->added_gc_cb = true;
1717
- }
1718
- }
1719
-
1720
- if (call->marshal_stackdepth > 0) {
1721
- StackCounter::SetMax(isolate, call->marshal_stackdepth);
1722
- }
1723
-
1724
- Isolate::Scope isolate_scope(isolate);
1725
- EscapableHandleScope handle_scope(isolate);
1726
- TryCatch trycatch(isolate);
1727
-
1728
- Local<Context> context = call->context_info->context->Get(isolate);
1729
- Context::Scope context_scope(context);
1730
-
1731
- Local<Function> fun = call->fun;
1732
-
1733
- EvalResult& eval_res = call->result;
1734
- eval_res.parsed = true;
1735
-
1736
- MaybeLocal<v8::Value> res = fun->Call(context, context->Global(), call->argc, call->argv);
1737
- prepare_result(res, trycatch, isolate, context, eval_res);
1738
-
1739
- IsolateData::Set(isolate, IsolateData::IN_GVL, true);
1740
-
1741
- return NULL;
1742
- }
1743
-
1744
- static void unblock_function(void *args) {
1745
- FunctionCall *call = (FunctionCall *) args;
1746
- call->context_info->isolate_info->interrupted = true;
1747
- }
1748
-
1749
- static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1750
- ContextInfo* context_info;
1751
- FunctionCall call;
1752
- VALUE *call_argv = NULL;
1753
-
1754
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1755
- Isolate* isolate = context_info->isolate_info->isolate;
1756
-
1757
- if (argc < 1) {
1758
- rb_raise(rb_eArgError, "need at least one argument %d", argc);
1759
- }
1760
-
1761
- VALUE function_name = argv[0];
1762
- Check_Type(function_name, T_STRING);
1763
-
1764
- char *fname = RSTRING_PTR(function_name);
1765
- if (!fname) {
1766
- return Qnil;
1767
- }
1768
-
1769
- call.context_info = context_info;
1770
- call.error = false;
1771
- call.function_name = fname;
1772
- call.argc = argc - 1;
1773
- call.argv = NULL;
1774
- if (call.argc > 0) {
1775
- // skip first argument which is the function name
1776
- call_argv = argv + 1;
1777
- }
1778
-
1779
- call.max_memory = 0;
1780
- VALUE mem_softlimit = rb_iv_get(self, "@max_memory");
1781
- if (mem_softlimit != Qnil) {
1782
- unsigned long sl_int = NUM2ULONG(mem_softlimit);
1783
- call.max_memory = (size_t)sl_int;
1784
- }
1785
-
1786
- call.marshal_stackdepth = 0;
1787
- VALUE marshal_stackdepth = rb_iv_get(self, "@marshal_stack_depth");
1788
- if (marshal_stackdepth != Qnil) {
1789
- unsigned long sl_int = NUM2ULONG(marshal_stackdepth);
1790
- call.marshal_stackdepth = (size_t)sl_int;
1791
- }
1792
-
1793
- bool missingFunction = false;
1794
- {
1795
- Locker lock(isolate);
1796
- Isolate::Scope isolate_scope(isolate);
1797
- HandleScope handle_scope(isolate);
1798
-
1799
- Local<Context> context = context_info->context->Get(isolate);
1800
- Context::Scope context_scope(context);
1801
-
1802
- // examples of such usage can be found in
1803
- // https://github.com/v8/v8/blob/36b32aa28db5e993312f4588d60aad5c8330c8a5/test/cctest/test-api.cc#L15711
1804
- MaybeLocal<String> fname = String::NewFromUtf8(isolate, call.function_name);
1805
- MaybeLocal<v8::Value> val;
1806
- if (!fname.IsEmpty()) {
1807
- val = context->Global()->Get(context, fname.ToLocalChecked());
1808
- }
1809
-
1810
- if (val.IsEmpty() || !val.ToLocalChecked()->IsFunction()) {
1811
- missingFunction = true;
1812
- } else {
1813
- Local<v8::Function> fun = Local<v8::Function>::Cast(val.ToLocalChecked());
1814
- VALUE tmp;
1815
- call.fun = fun;
1816
- call.argv = (v8::Local<Value> *)RB_ALLOCV_N(void *, tmp, call.argc);
1817
- for(int i=0; i < call.argc; i++) {
1818
- call.argv[i] = convert_ruby_to_v8(isolate, context, call_argv[i]);
1819
- }
1820
- rb_thread_call_without_gvl(nogvl_context_call, &call, unblock_function, &call);
1821
- RB_ALLOCV_END(tmp);
1822
- }
1823
- }
1824
-
1825
- if (missingFunction) {
1826
- rb_raise(rb_eScriptRuntimeError, "Unknown JavaScript method invoked");
1827
- }
1828
-
1829
- return convert_result_to_ruby(self, call.result);
1830
- }
1831
-
1832
- static VALUE rb_context_create_isolate_value(VALUE self) {
1833
- ContextInfo* context_info;
1834
- TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1835
- IsolateInfo *isolate_info = context_info->isolate_info;
1836
-
1837
- if (!isolate_info) {
1838
- return Qnil;
1839
- }
1840
-
1841
- isolate_info->hold();
1842
- return TypedData_Wrap_Struct(rb_cIsolate, &isolate_type, isolate_info);
1843
- }
1844
-
1845
- static void set_ruby_exiting(VALUE value) {
1846
- (void)value;
1847
-
1848
- ruby_exiting.store(1);
1849
- }
1850
-
1851
- extern "C" {
1852
-
1853
- __attribute__((visibility("default"))) void Init_mini_racer_extension ( void )
1854
- {
1855
- VALUE rb_mMiniRacer = rb_define_module("MiniRacer");
1856
- rb_cContext = rb_define_class_under(rb_mMiniRacer, "Context", rb_cObject);
1857
- rb_cSnapshot = rb_define_class_under(rb_mMiniRacer, "Snapshot", rb_cObject);
1858
- rb_cIsolate = rb_define_class_under(rb_mMiniRacer, "Isolate", rb_cObject);
1859
- VALUE rb_cPlatform = rb_define_class_under(rb_mMiniRacer, "Platform", rb_cObject);
1860
-
1861
- VALUE rb_eError = rb_define_class_under(rb_mMiniRacer, "Error", rb_eStandardError);
1862
-
1863
- VALUE rb_eEvalError = rb_define_class_under(rb_mMiniRacer, "EvalError", rb_eError);
1864
- rb_eScriptTerminatedError = rb_define_class_under(rb_mMiniRacer, "ScriptTerminatedError", rb_eEvalError);
1865
- rb_eV8OutOfMemoryError = rb_define_class_under(rb_mMiniRacer, "V8OutOfMemoryError", rb_eEvalError);
1866
- rb_eParseError = rb_define_class_under(rb_mMiniRacer, "ParseError", rb_eEvalError);
1867
- rb_eScriptRuntimeError = rb_define_class_under(rb_mMiniRacer, "RuntimeError", rb_eEvalError);
1868
-
1869
- rb_cJavaScriptFunction = rb_define_class_under(rb_mMiniRacer, "JavaScriptFunction", rb_cObject);
1870
- rb_eSnapshotError = rb_define_class_under(rb_mMiniRacer, "SnapshotError", rb_eError);
1871
- rb_ePlatformAlreadyInitializedError = rb_define_class_under(rb_mMiniRacer, "PlatformAlreadyInitialized", rb_eError);
1872
- rb_cFailedV8Conversion = rb_define_class_under(rb_mMiniRacer, "FailedV8Conversion", rb_cObject);
1873
- rb_mJSON = rb_define_module("JSON");
1874
-
1875
- VALUE rb_cExternalFunction = rb_define_class_under(rb_cContext, "ExternalFunction", rb_cObject);
1876
-
1877
- rb_define_method(rb_cContext, "stop", (VALUE(*)(...))&rb_context_stop, 0);
1878
- rb_define_method(rb_cContext, "dispose_unsafe", (VALUE(*)(...))&rb_context_dispose, 0);
1879
- rb_define_method(rb_cContext, "heap_stats", (VALUE(*)(...))&rb_heap_stats, 0);
1880
- rb_define_method(rb_cContext, "write_heap_snapshot_unsafe", (VALUE(*)(...))&rb_heap_snapshot, 1);
1881
-
1882
- rb_define_private_method(rb_cContext, "create_isolate_value",(VALUE(*)(...))&rb_context_create_isolate_value, 0);
1883
- rb_define_private_method(rb_cContext, "eval_unsafe",(VALUE(*)(...))&rb_context_eval_unsafe, 2);
1884
- rb_define_private_method(rb_cContext, "call_unsafe", (VALUE(*)(...))&rb_context_call_unsafe, -1);
1885
- rb_define_private_method(rb_cContext, "isolate_mutex", (VALUE(*)(...))&rb_context_isolate_mutex, 0);
1886
- rb_define_private_method(rb_cContext, "init_unsafe",(VALUE(*)(...))&rb_context_init_unsafe, 2);
1887
-
1888
- rb_define_alloc_func(rb_cContext, allocate);
1889
- rb_define_alloc_func(rb_cSnapshot, allocate_snapshot);
1890
- rb_define_alloc_func(rb_cIsolate, allocate_isolate);
1891
-
1892
- rb_define_private_method(rb_cExternalFunction, "notify_v8", (VALUE(*)(...))&rb_external_function_notify_v8, 0);
1893
-
1894
- rb_define_method(rb_cSnapshot, "size", (VALUE(*)(...))&rb_snapshot_size, 0);
1895
- rb_define_method(rb_cSnapshot, "dump", (VALUE(*)(...))&rb_snapshot_dump, 0);
1896
- rb_define_method(rb_cSnapshot, "warmup_unsafe!", (VALUE(*)(...))&rb_snapshot_warmup_unsafe, 1);
1897
- rb_define_private_method(rb_cSnapshot, "load", (VALUE(*)(...))&rb_snapshot_load, 1);
1898
-
1899
- rb_define_method(rb_cIsolate, "idle_notification", (VALUE(*)(...))&rb_isolate_idle_notification, 1);
1900
- rb_define_method(rb_cIsolate, "low_memory_notification", (VALUE(*)(...))&rb_isolate_low_memory_notification, 0);
1901
- rb_define_method(rb_cIsolate, "pump_message_loop", (VALUE(*)(...))&rb_isolate_pump_message_loop, 0);
1902
- rb_define_private_method(rb_cIsolate, "init_with_snapshot",(VALUE(*)(...))&rb_isolate_init_with_snapshot, 1);
1903
-
1904
- rb_define_singleton_method(rb_cPlatform, "set_flag_as_str!", (VALUE(*)(...))&rb_platform_set_flag_as_str, 1);
1905
-
1906
- rb_set_end_proc(set_ruby_exiting, Qnil);
1907
-
1908
- static pthread_attr_t attr;
1909
- if (pthread_attr_init(&attr) == 0) {
1910
- if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0) {
1911
- thread_attr_p = &attr;
1912
- }
1913
- }
1914
- }
1915
- }