mini_racer 0.2.8 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@
2
2
  #include <ruby.h>
3
3
  #include <ruby/thread.h>
4
4
  #include <ruby/io.h>
5
+ #include <ruby/version.h>
5
6
  #include <v8.h>
6
7
  #include <v8-profiler.h>
7
8
  #include <libplatform/libplatform.h>
@@ -11,6 +12,15 @@
11
12
  #include <mutex>
12
13
  #include <atomic>
13
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
14
24
 
15
25
  using namespace v8;
16
26
 
@@ -25,6 +35,7 @@ public:
25
35
  ArrayBuffer::Allocator* allocator;
26
36
  StartupData* startup_data;
27
37
  bool interrupted;
38
+ bool added_gc_cb;
28
39
  pid_t pid;
29
40
  VALUE mutex;
30
41
 
@@ -42,15 +53,12 @@ public:
42
53
 
43
54
 
44
55
  IsolateInfo() : isolate(nullptr), allocator(nullptr), startup_data(nullptr),
45
- interrupted(false), pid(getpid()), refs_count(0) {
56
+ interrupted(false), added_gc_cb(false), pid(getpid()), refs_count(0) {
46
57
  VALUE cMutex = rb_const_get(rb_cThread, rb_intern("Mutex"));
47
58
  mutex = rb_class_new_instance(0, nullptr, cMutex);
48
59
  }
49
60
 
50
- ~IsolateInfo() {
51
- void free_isolate(IsolateInfo*);
52
- free_isolate(this);
53
- }
61
+ ~IsolateInfo();
54
62
 
55
63
  void init(SnapshotInfo* snapshot_info = nullptr);
56
64
 
@@ -117,6 +125,7 @@ typedef struct {
117
125
  useconds_t timeout;
118
126
  EvalResult* result;
119
127
  size_t max_memory;
128
+ size_t marshal_stackdepth;
120
129
  } EvalParams;
121
130
 
122
131
  typedef struct {
@@ -127,13 +136,153 @@ typedef struct {
127
136
  Local<Function> fun;
128
137
  Local<Value> *argv;
129
138
  EvalResult result;
139
+ size_t max_memory;
140
+ size_t marshal_stackdepth;
130
141
  } FunctionCall;
131
142
 
132
- enum IsolateFlags {
133
- IN_GVL,
134
- DO_TERMINATE,
135
- MEM_SOFTLIMIT_VALUE,
136
- MEM_SOFTLIMIT_REACHED,
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
+ }
137
286
  };
138
287
 
139
288
  static VALUE rb_cContext;
@@ -155,18 +304,45 @@ static VALUE rb_cDateTime = Qnil;
155
304
  static std::unique_ptr<Platform> current_platform = NULL;
156
305
  static std::mutex platform_lock;
157
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
+
158
334
  static VALUE rb_platform_set_flag_as_str(VALUE _klass, VALUE flag_as_str) {
159
335
  bool platform_already_initialized = false;
160
336
 
161
- if(TYPE(flag_as_str) != T_STRING) {
162
- rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE" (should be a string)",
163
- rb_obj_class(flag_as_str));
164
- }
337
+ Check_Type(flag_as_str, T_STRING);
165
338
 
166
339
  platform_lock.lock();
167
340
 
168
341
  if (current_platform == NULL) {
169
- V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), (int)RSTRING_LEN(flag_as_str));
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));
170
346
  } else {
171
347
  platform_already_initialized = true;
172
348
  }
@@ -189,7 +365,11 @@ static void init_v8() {
189
365
 
190
366
  if (current_platform == NULL) {
191
367
  V8::InitializeICU();
192
- current_platform = platform::NewDefaultPlatform();
368
+ if (single_threaded) {
369
+ current_platform = platform::NewSingleThreadedDefaultPlatform();
370
+ } else {
371
+ current_platform = platform::NewDefaultPlatform();
372
+ }
193
373
  V8::InitializePlatform(current_platform.get());
194
374
  V8::Initialize();
195
375
  }
@@ -198,16 +378,18 @@ static void init_v8() {
198
378
  }
199
379
 
200
380
  static void gc_callback(Isolate *isolate, GCType type, GCCallbackFlags flags) {
201
- if((bool)isolate->GetData(MEM_SOFTLIMIT_REACHED)) return;
381
+ if (IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_REACHED)) {
382
+ return;
383
+ }
202
384
 
203
- size_t softlimit = *(size_t*) isolate->GetData(MEM_SOFTLIMIT_VALUE);
385
+ size_t softlimit = IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_MAX);
204
386
 
205
387
  HeapStatistics stats;
206
388
  isolate->GetHeapStatistics(&stats);
207
389
  size_t used = stats.used_heap_size();
208
390
 
209
391
  if(used > softlimit) {
210
- isolate->SetData(MEM_SOFTLIMIT_REACHED, (void*)true);
392
+ IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_REACHED, true);
211
393
  isolate->TerminateExecution();
212
394
  }
213
395
  }
@@ -232,26 +414,32 @@ static void prepare_result(MaybeLocal<Value> v8res,
232
414
  Local<Value> local_value = v8res.ToLocalChecked();
233
415
  if ((local_value->IsObject() || local_value->IsArray()) &&
234
416
  !local_value->IsDate() && !local_value->IsFunction()) {
235
- Local<Object> JSON = context->Global()->Get(String::NewFromUtf8(isolate, "JSON"))
236
- ->ToObject(context).ToLocalChecked();
417
+ MaybeLocal<v8::Value> ml = context->Global()->Get(
418
+ context, String::NewFromUtf8Literal(isolate, "JSON"));
237
419
 
238
- Local<Function> stringify = JSON->Get(v8::String::NewFromUtf8(isolate, "stringify"))
239
- .As<Function>();
240
-
241
- Local<Object> object = local_value->ToObject(context).ToLocalChecked();
242
- const unsigned argc = 1;
243
- Local<Value> argv[argc] = { object };
244
- MaybeLocal<Value> json = stringify->Call(context, JSON, argc, argv);
245
-
246
- if (json.IsEmpty()) {
420
+ if (ml.IsEmpty()) { // exception
247
421
  evalRes.executed = false;
248
422
  } else {
249
- evalRes.json = true;
250
- Persistent<Value>* persistent = new Persistent<Value>();
251
- persistent->Reset(isolate, json.ToLocalChecked());
252
- evalRes.value = persistent;
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
+ }
253
442
  }
254
-
255
443
  } else {
256
444
  Persistent<Value>* persistent = new Persistent<Value>();
257
445
  persistent->Reset(isolate, local_value);
@@ -290,7 +478,7 @@ static void prepare_result(MaybeLocal<Value> v8res,
290
478
  } else if(trycatch.HasTerminated()) {
291
479
  evalRes.terminated = true;
292
480
  evalRes.message = new Persistent<Value>();
293
- Local<String> tmp = String::NewFromUtf8(isolate, "JavaScript was terminated (either by timeout or explicitly)");
481
+ Local<String> tmp = String::NewFromUtf8Literal(isolate, "JavaScript was terminated (either by timeout or explicitly)");
294
482
  evalRes.message->Reset(isolate, tmp);
295
483
  }
296
484
  if (!trycatch.StackTrace(context).IsEmpty()) {
@@ -302,12 +490,13 @@ static void prepare_result(MaybeLocal<Value> v8res,
302
490
  }
303
491
  }
304
492
 
305
- void*
493
+ static void*
306
494
  nogvl_context_eval(void* arg) {
307
495
 
308
496
  EvalParams* eval_params = (EvalParams*)arg;
309
497
  EvalResult* result = eval_params->result;
310
- Isolate* isolate = eval_params->context_info->isolate_info->isolate;
498
+ IsolateInfo* isolate_info = eval_params->context_info->isolate_info;
499
+ Isolate* isolate = isolate_info->isolate;
311
500
 
312
501
  Isolate::Scope isolate_scope(isolate);
313
502
  HandleScope handle_scope(isolate);
@@ -316,14 +505,15 @@ nogvl_context_eval(void* arg) {
316
505
  Context::Scope context_scope(context);
317
506
  v8::ScriptOrigin *origin = NULL;
318
507
 
319
- // in gvl flag
320
- isolate->SetData(IN_GVL, (void*)false);
321
- // terminate ASAP
322
- isolate->SetData(DO_TERMINATE, (void*)false);
323
- // Memory softlimit
324
- isolate->SetData(MEM_SOFTLIMIT_VALUE, (void*)false);
325
- // Memory softlimit hit flag
326
- isolate->SetData(MEM_SOFTLIMIT_REACHED, (void*)false);
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
+ }
327
517
 
328
518
  MaybeLocal<Script> parsed_script;
329
519
 
@@ -349,9 +539,8 @@ nogvl_context_eval(void* arg) {
349
539
  result->message->Reset(isolate, trycatch.Exception());
350
540
  } else {
351
541
  // parsing successful
352
- if (eval_params->max_memory > 0) {
353
- isolate->SetData(MEM_SOFTLIMIT_VALUE, &eval_params->max_memory);
354
- isolate->AddGCEpilogueCallback(gc_callback);
542
+ if (eval_params->marshal_stackdepth > 0) {
543
+ StackCounter::SetMax(isolate, eval_params->marshal_stackdepth);
355
544
  }
356
545
 
357
546
  maybe_value = parsed_script.ToLocalChecked()->Run(context);
@@ -359,11 +548,17 @@ nogvl_context_eval(void* arg) {
359
548
 
360
549
  prepare_result(maybe_value, trycatch, isolate, context, *result);
361
550
 
362
- isolate->SetData(IN_GVL, (void*)true);
551
+ IsolateData::Set(isolate, IsolateData::IN_GVL, true);
363
552
 
364
553
  return NULL;
365
554
  }
366
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
+
367
562
  // assumes isolate locking is in place
368
563
  static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
369
564
  Local<Value> value) {
@@ -371,6 +566,18 @@ static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
371
566
  Isolate::Scope isolate_scope(isolate);
372
567
  HandleScope scope(isolate);
373
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
+
374
581
  if (value->IsNull() || value->IsUndefined()){
375
582
  return Qnil;
376
583
  }
@@ -395,8 +602,11 @@ static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
395
602
  VALUE rb_array = rb_ary_new();
396
603
  Local<Array> arr = Local<Array>::Cast(value);
397
604
  for(uint32_t i=0; i < arr->Length(); i++) {
398
- Local<Value> element = arr->Get(i);
399
- VALUE rb_elem = convert_v8_to_ruby(isolate, context, element);
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());
400
610
  if (rb_funcall(rb_elem, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
401
611
  return rb_elem;
402
612
  }
@@ -426,26 +636,43 @@ static VALUE convert_v8_to_ruby(Isolate* isolate, Local<Context> context,
426
636
  if (!maybe_props.IsEmpty()) {
427
637
  Local<Array> props = maybe_props.ToLocalChecked();
428
638
  for(uint32_t i=0; i < props->Length(); i++) {
429
- Local<Value> key = props->Get(i);
430
- VALUE rb_key = convert_v8_to_ruby(isolate, context, key);
431
- Local<Value> prop_value = object->Get(key);
432
- // this may have failed due to Get raising
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());
433
644
 
434
- if (trycatch.HasCaught()) {
435
- // TODO isolate code that translates execption to ruby
436
- // exception so we can properly return it
437
- return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
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();
438
649
  }
439
650
 
440
- VALUE rb_value = convert_v8_to_ruby(isolate, context, prop_value);
651
+ VALUE rb_value = convert_v8_to_ruby(
652
+ isolate, context, prop_value.ToLocalChecked());
441
653
  rb_hash_aset(rb_hash, rb_key, rb_value);
442
654
  }
443
655
  }
444
656
  return rb_hash;
445
657
  }
446
658
 
447
- Local<String> rstr = value->ToString(context).ToLocalChecked();
448
- return rb_enc_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate), rb_enc_find("utf-8"));
659
+ if (value->IsSymbol()) {
660
+ v8::String::Utf8Value symbol_name(isolate,
661
+ Local<Symbol>::Cast(value)->Name());
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
+ }
449
676
  }
450
677
 
451
678
  static VALUE convert_v8_to_ruby(Isolate* isolate,
@@ -489,7 +716,7 @@ static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context,
489
716
  case T_FLOAT:
490
717
  return scope.Escape(Number::New(isolate, NUM2DBL(value)));
491
718
  case T_STRING:
492
- return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
719
+ return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, RSTRING_LENINT(value)).ToLocalChecked());
493
720
  case T_NIL:
494
721
  return scope.Escape(Null(isolate));
495
722
  case T_TRUE:
@@ -500,7 +727,8 @@ static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context,
500
727
  length = RARRAY_LEN(value);
501
728
  array = Array::New(isolate, (int)length);
502
729
  for(i=0; i<length; i++) {
503
- array->Set(i, convert_ruby_to_v8(isolate, context, rb_ary_entry(value, i)));
730
+ Maybe<bool> success = array->Set(context, i, convert_ruby_to_v8(isolate, context, rb_ary_entry(value, i)));
731
+ (void)(success);
504
732
  }
505
733
  return scope.Escape(array);
506
734
  case T_HASH:
@@ -509,13 +737,14 @@ static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context,
509
737
  length = RARRAY_LEN(hash_as_array);
510
738
  for(i=0; i<length; i++) {
511
739
  pair = rb_ary_entry(hash_as_array, i);
512
- object->Set(convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 0)),
740
+ Maybe<bool> success = object->Set(context, convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 0)),
513
741
  convert_ruby_to_v8(isolate, context, rb_ary_entry(pair, 1)));
742
+ (void)(success);
514
743
  }
515
744
  return scope.Escape(object);
516
745
  case T_SYMBOL:
517
746
  value = rb_funcall(value, rb_intern("to_s"), 0);
518
- return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
747
+ return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, RSTRING_LENINT(value)).ToLocalChecked());
519
748
  case T_DATA:
520
749
  klass = rb_funcall(value, rb_intern("class"), 0);
521
750
  if (klass == rb_cTime || klass == rb_cDateTime)
@@ -539,9 +768,9 @@ static Local<Value> convert_ruby_to_v8(Isolate* isolate, Local<Context> context,
539
768
  case T_UNDEF:
540
769
  case T_NODE:
541
770
  default:
542
- return scope.Escape(String::NewFromUtf8(isolate, "Undefined Conversion"));
771
+ return scope.Escape(String::NewFromUtf8Literal(isolate, "Undefined Conversion"));
772
+ }
543
773
  }
544
- }
545
774
 
546
775
  static void unblock_eval(void *ptr) {
547
776
  EvalParams* eval = (EvalParams*)ptr;
@@ -552,54 +781,45 @@ static void unblock_eval(void *ptr) {
552
781
  * The implementations of the run_extra_code(), create_snapshot_data_blob() and
553
782
  * warm_up_snapshot_data_blob() functions have been derived from V8's test suite.
554
783
  */
555
- bool run_extra_code(Isolate *isolate, Local<v8::Context> context,
784
+ static bool run_extra_code(Isolate *isolate, Local<v8::Context> context,
556
785
  const char *utf8_source, const char *name) {
557
786
  Context::Scope context_scope(context);
558
787
  TryCatch try_catch(isolate);
559
788
  Local<String> source_string;
560
- if (!String::NewFromUtf8(isolate, utf8_source,
561
- NewStringType::kNormal)
562
- .ToLocal(&source_string)) {
789
+ if (!String::NewFromUtf8(isolate, utf8_source).ToLocal(&source_string)) {
563
790
  return false;
564
791
  }
565
- Local<v8::String> resource_name =
566
- String::NewFromUtf8(isolate, name, NewStringType::kNormal)
567
- .ToLocalChecked();
792
+ Local<String> resource_name =
793
+ String::NewFromUtf8(isolate, name).ToLocalChecked();
568
794
  ScriptOrigin origin(resource_name);
569
795
  ScriptCompiler::Source source(source_string, origin);
570
796
  Local<Script> script;
571
797
  if (!ScriptCompiler::Compile(context, &source).ToLocal(&script))
572
798
  return false;
573
- if (script->Run(context).IsEmpty())
574
- return false;
575
- // CHECK(!try_catch.HasCaught());
799
+ if (script->Run(context).IsEmpty()) return false;
576
800
  return true;
577
801
  }
578
802
 
579
- StartupData
803
+ static StartupData
580
804
  create_snapshot_data_blob(const char *embedded_source = nullptr) {
581
- // Create a new isolate and a new context from scratch, optionally run
582
- // a script to embed, and serialize to create a snapshot blob.
583
- StartupData result = {nullptr, 0};
584
- {
585
- SnapshotCreator snapshot_creator;
586
- Isolate *isolate = snapshot_creator.GetIsolate();
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);
587
809
  {
588
810
  HandleScope scope(isolate);
589
- Local<Context> context = Context::New(isolate);
811
+ Local<v8::Context> context = v8::Context::New(isolate);
590
812
  if (embedded_source != nullptr &&
591
- !run_extra_code(isolate, context, embedded_source,
592
- "<embedded>")) {
593
- return result;
813
+ !run_extra_code(isolate, context, embedded_source, "<embedded>")) {
814
+ return {};
594
815
  }
595
816
  snapshot_creator.SetDefaultContext(context);
596
817
  }
597
- result = snapshot_creator.CreateBlob(
818
+ return snapshot_creator.CreateBlob(
598
819
  SnapshotCreator::FunctionCodeHandling::kClear);
599
820
  }
600
- return result;
601
- }
602
821
 
822
+ static
603
823
  StartupData warm_up_snapshot_data_blob(StartupData cold_snapshot_blob,
604
824
  const char *warmup_source) {
605
825
  // Use following steps to create a warmed up snapshot blob from a cold one:
@@ -633,21 +853,18 @@ StartupData warm_up_snapshot_data_blob(StartupData cold_snapshot_blob,
633
853
  return result;
634
854
  }
635
855
 
636
- static VALUE rb_snapshot_size(VALUE self, VALUE str) {
856
+ static VALUE rb_snapshot_size(VALUE self) {
637
857
  SnapshotInfo* snapshot_info;
638
- Data_Get_Struct(self, SnapshotInfo, snapshot_info);
858
+ TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
639
859
 
640
860
  return INT2NUM(snapshot_info->raw_size);
641
861
  }
642
862
 
643
863
  static VALUE rb_snapshot_load(VALUE self, VALUE str) {
644
864
  SnapshotInfo* snapshot_info;
645
- Data_Get_Struct(self, SnapshotInfo, snapshot_info);
865
+ TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
646
866
 
647
- if(TYPE(str) != T_STRING) {
648
- rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
649
- rb_obj_class(str));
650
- }
867
+ Check_Type(str, T_STRING);
651
868
 
652
869
  init_v8();
653
870
 
@@ -663,21 +880,18 @@ static VALUE rb_snapshot_load(VALUE self, VALUE str) {
663
880
  return Qnil;
664
881
  }
665
882
 
666
- static VALUE rb_snapshot_dump(VALUE self, VALUE str) {
883
+ static VALUE rb_snapshot_dump(VALUE self) {
667
884
  SnapshotInfo* snapshot_info;
668
- Data_Get_Struct(self, SnapshotInfo, snapshot_info);
885
+ TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
669
886
 
670
887
  return rb_str_new(snapshot_info->data, snapshot_info->raw_size);
671
888
  }
672
889
 
673
890
  static VALUE rb_snapshot_warmup_unsafe(VALUE self, VALUE str) {
674
891
  SnapshotInfo* snapshot_info;
675
- Data_Get_Struct(self, SnapshotInfo, snapshot_info);
892
+ TypedData_Get_Struct(self, SnapshotInfo, &snapshot_type, snapshot_info);
676
893
 
677
- if(TYPE(str) != T_STRING) {
678
- rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
679
- rb_obj_class(str));
680
- }
894
+ Check_Type(str, T_STRING);
681
895
 
682
896
  init_v8();
683
897
 
@@ -719,13 +933,13 @@ void IsolateInfo::init(SnapshotInfo* snapshot_info) {
719
933
 
720
934
  static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) {
721
935
  IsolateInfo* isolate_info;
722
- Data_Get_Struct(self, IsolateInfo, isolate_info);
936
+ TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
723
937
 
724
938
  init_v8();
725
939
 
726
940
  SnapshotInfo* snapshot_info = nullptr;
727
941
  if (!NIL_P(snapshot)) {
728
- Data_Get_Struct(snapshot, SnapshotInfo, snapshot_info);
942
+ TypedData_Get_Struct(snapshot, SnapshotInfo, &snapshot_type, snapshot_info);
729
943
  }
730
944
 
731
945
  isolate_info->init(snapshot_info);
@@ -736,7 +950,7 @@ static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) {
736
950
 
737
951
  static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) {
738
952
  IsolateInfo* isolate_info;
739
- Data_Get_Struct(self, IsolateInfo, isolate_info);
953
+ TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
740
954
 
741
955
  if (current_platform == NULL) return Qfalse;
742
956
 
@@ -745,9 +959,32 @@ static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) {
745
959
  return isolate_info->isolate->IdleNotificationDeadline(now + duration) ? Qtrue : Qfalse;
746
960
  }
747
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
+ isolate_info->isolate->LowMemoryNotification();
969
+ return Qnil;
970
+ }
971
+
972
+ static VALUE rb_isolate_pump_message_loop(VALUE self) {
973
+ IsolateInfo* isolate_info;
974
+ TypedData_Get_Struct(self, IsolateInfo, &isolate_type, isolate_info);
975
+
976
+ if (current_platform == NULL) return Qfalse;
977
+
978
+ if (platform::PumpMessageLoop(current_platform.get(), isolate_info->isolate)){
979
+ return Qtrue;
980
+ } else {
981
+ return Qfalse;
982
+ }
983
+ }
984
+
748
985
  static VALUE rb_context_init_unsafe(VALUE self, VALUE isolate, VALUE snap) {
749
986
  ContextInfo* context_info;
750
- Data_Get_Struct(self, ContextInfo, context_info);
987
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
751
988
 
752
989
  init_v8();
753
990
 
@@ -758,11 +995,11 @@ static VALUE rb_context_init_unsafe(VALUE self, VALUE isolate, VALUE snap) {
758
995
 
759
996
  SnapshotInfo *snapshot_info = nullptr;
760
997
  if (!NIL_P(snap) && rb_obj_is_kind_of(snap, rb_cSnapshot)) {
761
- Data_Get_Struct(snap, SnapshotInfo, snapshot_info);
998
+ TypedData_Get_Struct(snap, SnapshotInfo, &snapshot_type, snapshot_info);
762
999
  }
763
1000
  isolate_info->init(snapshot_info);
764
1001
  } else { // given isolate or snapshot
765
- Data_Get_Struct(isolate, IsolateInfo, isolate_info);
1002
+ TypedData_Get_Struct(isolate, IsolateInfo, &isolate_type, isolate_info);
766
1003
  }
767
1004
 
768
1005
  context_info->isolate_info = isolate_info;
@@ -792,7 +1029,7 @@ static VALUE rb_context_init_unsafe(VALUE self, VALUE isolate, VALUE snap) {
792
1029
  static VALUE convert_result_to_ruby(VALUE self /* context */,
793
1030
  EvalResult& result) {
794
1031
  ContextInfo *context_info;
795
- Data_Get_Struct(self, ContextInfo, context_info);
1032
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
796
1033
 
797
1034
  Isolate *isolate = context_info->isolate_info->isolate;
798
1035
  Persistent<Context> *p_ctx = context_info->context;
@@ -819,7 +1056,7 @@ static VALUE convert_result_to_ruby(VALUE self /* context */,
819
1056
  // a v8 scope, if we do the scope is never cleaned up properly and we leak
820
1057
  if (!result.parsed) {
821
1058
  if(TYPE(message) == T_STRING) {
822
- rb_raise(rb_eParseError, "%s", RSTRING_PTR(message));
1059
+ rb_raise(rb_eParseError, "%" PRIsVALUE, message);
823
1060
  } else {
824
1061
  rb_raise(rb_eParseError, "Unknown JavaScript Error during parse");
825
1062
  }
@@ -828,9 +1065,13 @@ static VALUE convert_result_to_ruby(VALUE self /* context */,
828
1065
  if (!result.executed) {
829
1066
  VALUE ruby_exception = rb_iv_get(self, "@current_exception");
830
1067
  if (ruby_exception == Qnil) {
831
- bool mem_softlimit_reached = (bool)isolate->GetData(MEM_SOFTLIMIT_REACHED);
1068
+ bool mem_softlimit_reached = IsolateData::Get(isolate, IsolateData::MEM_SOFTLIMIT_REACHED);
1069
+ bool marshal_stack_maxdepth_reached = IsolateData::Get(isolate, IsolateData::MARSHAL_STACKDEPTH_REACHED);
832
1070
  // If we were terminated or have the memory softlimit flag set
833
- if (result.terminated || mem_softlimit_reached) {
1071
+ if (marshal_stack_maxdepth_reached) {
1072
+ ruby_exception = rb_eScriptRuntimeError;
1073
+ message = rb_utf8_str_new_literal("Marshal object depth too deep. Script terminated.");
1074
+ } else if (result.terminated || mem_softlimit_reached) {
834
1075
  ruby_exception = mem_softlimit_reached ? rb_eV8OutOfMemoryError : rb_eScriptTerminatedError;
835
1076
  } else {
836
1077
  ruby_exception = rb_eScriptRuntimeError;
@@ -838,15 +1079,17 @@ static VALUE convert_result_to_ruby(VALUE self /* context */,
838
1079
 
839
1080
  // exception report about what happened
840
1081
  if (TYPE(backtrace) == T_STRING) {
841
- rb_raise(ruby_exception, "%s", RSTRING_PTR(backtrace));
1082
+ rb_raise(ruby_exception, "%" PRIsVALUE, backtrace);
842
1083
  } else if(TYPE(message) == T_STRING) {
843
- rb_raise(ruby_exception, "%s", RSTRING_PTR(message));
1084
+ rb_raise(ruby_exception, "%" PRIsVALUE, message);
844
1085
  } else {
845
1086
  rb_raise(ruby_exception, "Unknown JavaScript Error during execution");
846
1087
  }
1088
+ } else if (rb_obj_is_kind_of(ruby_exception, rb_eException)) {
1089
+ rb_exc_raise(ruby_exception);
847
1090
  } else {
848
1091
  VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0);
849
- rb_raise(CLASS_OF(ruby_exception), "%s", RSTRING_PTR(rb_str));
1092
+ rb_raise(CLASS_OF(ruby_exception), "%" PRIsVALUE, rb_str);
850
1093
  }
851
1094
  }
852
1095
 
@@ -862,9 +1105,10 @@ static VALUE convert_result_to_ruby(VALUE self /* context */,
862
1105
 
863
1106
  if (result.json) {
864
1107
  Local<String> rstr = tmp->ToString(p_ctx->Get(isolate)).ToLocalChecked();
865
- VALUE json_string = rb_enc_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate), rb_enc_find("utf-8"));
1108
+ VALUE json_string = rb_utf8_str_new(*String::Utf8Value(isolate, rstr), rstr->Utf8Length(isolate));
866
1109
  ret = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string);
867
1110
  } else {
1111
+ StackCounter::Reset(isolate);
868
1112
  ret = convert_v8_to_ruby(isolate, *p_ctx, tmp);
869
1113
  }
870
1114
 
@@ -887,16 +1131,13 @@ static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
887
1131
  EvalResult eval_result;
888
1132
  ContextInfo* context_info;
889
1133
 
890
- Data_Get_Struct(self, ContextInfo, context_info);
1134
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
891
1135
  Isolate* isolate = context_info->isolate_info->isolate;
892
1136
 
893
- if(TYPE(str) != T_STRING) {
894
- rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be a string)",
895
- rb_obj_class(str));
896
- }
897
- if(filename != Qnil && TYPE(filename) != T_STRING) {
898
- rb_raise(rb_eArgError, "wrong type argument %" PRIsVALUE " (should be nil or a string)",
899
- rb_obj_class(filename));
1137
+ Check_Type(str, T_STRING);
1138
+
1139
+ if (!NIL_P(filename)) {
1140
+ Check_Type(filename, T_STRING);
900
1141
  }
901
1142
 
902
1143
  {
@@ -905,13 +1146,13 @@ static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
905
1146
  HandleScope handle_scope(isolate);
906
1147
 
907
1148
  Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str),
908
- NewStringType::kNormal, (int)RSTRING_LEN(str)).ToLocalChecked();
1149
+ NewStringType::kNormal, RSTRING_LENINT(str)).ToLocalChecked();
909
1150
 
910
1151
  Local<String> local_filename;
911
1152
 
912
1153
  if (filename != Qnil) {
913
1154
  local_filename = String::NewFromUtf8(isolate, RSTRING_PTR(filename),
914
- NewStringType::kNormal, (int)RSTRING_LEN(filename)).ToLocalChecked();
1155
+ NewStringType::kNormal, RSTRING_LENINT(filename)).ToLocalChecked();
915
1156
  eval_params.filename = &local_filename;
916
1157
  } else {
917
1158
  eval_params.filename = NULL;
@@ -922,6 +1163,7 @@ static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
922
1163
  eval_params.result = &eval_result;
923
1164
  eval_params.timeout = 0;
924
1165
  eval_params.max_memory = 0;
1166
+ eval_params.marshal_stackdepth = 0;
925
1167
  VALUE timeout = rb_iv_get(self, "@timeout");
926
1168
  if (timeout != Qnil) {
927
1169
  eval_params.timeout = (useconds_t)NUM2LONG(timeout);
@@ -932,6 +1174,11 @@ static VALUE rb_context_eval_unsafe(VALUE self, VALUE str, VALUE filename) {
932
1174
  eval_params.max_memory = (size_t)NUM2ULONG(mem_softlimit);
933
1175
  }
934
1176
 
1177
+ VALUE stack_depth = rb_iv_get(self, "@marshal_stack_depth");
1178
+ if (stack_depth != Qnil) {
1179
+ eval_params.marshal_stackdepth = (size_t)NUM2ULONG(stack_depth);
1180
+ }
1181
+
935
1182
  eval_result.message = NULL;
936
1183
  eval_result.backtrace = NULL;
937
1184
 
@@ -969,7 +1216,7 @@ VALUE rescue_callback(VALUE rdata, VALUE exception) {
969
1216
  return exception;
970
1217
  }
971
1218
 
972
- void*
1219
+ static void*
973
1220
  gvl_ruby_callback(void* data) {
974
1221
 
975
1222
  FunctionCallbackInfo<Value>* args = (FunctionCallbackInfo<Value>*)data;
@@ -985,7 +1232,7 @@ gvl_ruby_callback(void* data) {
985
1232
  HandleScope scope(args->GetIsolate());
986
1233
  Local<External> external = Local<External>::Cast(args->Data());
987
1234
 
988
- self = *(VALUE*)(external->Value());
1235
+ self = (VALUE)(external->Value());
989
1236
  callback = rb_iv_get(self, "@callback");
990
1237
 
991
1238
  parent = rb_iv_get(self, "@parent");
@@ -993,7 +1240,7 @@ gvl_ruby_callback(void* data) {
993
1240
  return NULL;
994
1241
  }
995
1242
 
996
- Data_Get_Struct(parent, ContextInfo, context_info);
1243
+ TypedData_Get_Struct(parent, ContextInfo, &context_type, context_info);
997
1244
 
998
1245
  if (length > 0) {
999
1246
  ruby_args = rb_ary_tmp_new(length);
@@ -1001,6 +1248,7 @@ gvl_ruby_callback(void* data) {
1001
1248
 
1002
1249
  for (int i = 0; i < length; i++) {
1003
1250
  Local<Value> value = ((*args)[i]).As<Value>();
1251
+ StackCounter::Reset(args->GetIsolate());
1004
1252
  VALUE tmp = convert_v8_to_ruby(args->GetIsolate(),
1005
1253
  *context_info->context, value);
1006
1254
  rb_ary_push(ruby_args, tmp);
@@ -1014,22 +1262,26 @@ gvl_ruby_callback(void* data) {
1014
1262
  callback_data.ruby_args = ruby_args;
1015
1263
  callback_data.failed = false;
1016
1264
 
1017
- if ((bool)args->GetIsolate()->GetData(DO_TERMINATE) == true) {
1018
- args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Terminated execution during transition from Ruby to JS"));
1265
+ if (IsolateData::Get(args->GetIsolate(), IsolateData::DO_TERMINATE)) {
1266
+ args->GetIsolate()->ThrowException(
1267
+ String::NewFromUtf8Literal(args->GetIsolate(),
1268
+ "Terminated execution during transition from Ruby to JS"));
1019
1269
  args->GetIsolate()->TerminateExecution();
1020
1270
  if (length > 0) {
1021
1271
  rb_ary_clear(ruby_args);
1022
- rb_gc_force_recycle(ruby_args);
1023
1272
  }
1024
1273
  return NULL;
1025
1274
  }
1026
1275
 
1027
- result = rb_rescue2((VALUE(*)(...))&protected_callback, (VALUE)(&callback_data),
1028
- (VALUE(*)(...))&rescue_callback, (VALUE)(&callback_data), rb_eException, (VALUE)0);
1276
+ VALUE callback_data_value = (VALUE)&callback_data;
1277
+
1278
+ // TODO: use rb_vrescue2 in Ruby 2.7 and above
1279
+ result = rb_rescue2(MR_METHOD_FUNC(protected_callback), callback_data_value,
1280
+ MR_METHOD_FUNC(rescue_callback), callback_data_value, rb_eException, (VALUE)0);
1029
1281
 
1030
1282
  if(callback_data.failed) {
1031
1283
  rb_iv_set(parent, "@current_exception", result);
1032
- args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Ruby exception"));
1284
+ args->GetIsolate()->ThrowException(String::NewFromUtf8Literal(args->GetIsolate(), "Ruby exception"));
1033
1285
  }
1034
1286
  else {
1035
1287
  HandleScope scope(args->GetIsolate());
@@ -1039,26 +1291,24 @@ gvl_ruby_callback(void* data) {
1039
1291
 
1040
1292
  if (length > 0) {
1041
1293
  rb_ary_clear(ruby_args);
1042
- rb_gc_force_recycle(ruby_args);
1043
1294
  }
1044
1295
 
1045
- if ((bool)args->GetIsolate()->GetData(DO_TERMINATE) == true) {
1046
- Isolate* isolate = args->GetIsolate();
1047
- isolate->TerminateExecution();
1296
+ if (IsolateData::Get(args->GetIsolate(), IsolateData::DO_TERMINATE)) {
1297
+ args->GetIsolate()->TerminateExecution();
1048
1298
  }
1049
1299
 
1050
1300
  return NULL;
1051
1301
  }
1052
1302
 
1053
1303
  static void ruby_callback(const FunctionCallbackInfo<Value>& args) {
1054
- bool has_gvl = (bool)args.GetIsolate()->GetData(IN_GVL);
1304
+ bool has_gvl = IsolateData::Get(args.GetIsolate(), IsolateData::IN_GVL);
1055
1305
 
1056
1306
  if(has_gvl) {
1057
1307
  gvl_ruby_callback((void*)&args);
1058
1308
  } else {
1059
- args.GetIsolate()->SetData(IN_GVL, (void*)true);
1309
+ IsolateData::Set(args.GetIsolate(), IsolateData::IN_GVL, true);
1060
1310
  rb_thread_call_with_gvl(gvl_ruby_callback, (void*)(&args));
1061
- args.GetIsolate()->SetData(IN_GVL, (void*)false);
1311
+ IsolateData::Set(args.GetIsolate(), IsolateData::IN_GVL, false);
1062
1312
  }
1063
1313
  }
1064
1314
 
@@ -1075,7 +1325,7 @@ static VALUE rb_external_function_notify_v8(VALUE self) {
1075
1325
  bool parse_error = false;
1076
1326
  bool attach_error = false;
1077
1327
 
1078
- Data_Get_Struct(parent, ContextInfo, context_info);
1328
+ TypedData_Get_Struct(parent, ContextInfo, &context_type, context_info);
1079
1329
  Isolate* isolate = context_info->isolate_info->isolate;
1080
1330
 
1081
1331
  {
@@ -1088,32 +1338,32 @@ static VALUE rb_external_function_notify_v8(VALUE self) {
1088
1338
 
1089
1339
  Local<String> v8_str =
1090
1340
  String::NewFromUtf8(isolate, RSTRING_PTR(name),
1091
- NewStringType::kNormal, (int)RSTRING_LEN(name))
1341
+ NewStringType::kNormal, RSTRING_LENINT(name))
1092
1342
  .ToLocalChecked();
1093
1343
 
1094
- // copy self so we can access from v8 external
1095
- VALUE* self_copy;
1096
- Data_Get_Struct(self, VALUE, self_copy);
1097
- *self_copy = self;
1098
-
1099
- Local<Value> external = External::New(isolate, self_copy);
1344
+ // Note that self (rb_cExternalFunction) is a pure Ruby T_OBJECT,
1345
+ // not a T_DATA type like most other classes in this file
1346
+ Local<Value> external = External::New(isolate, (void *)self);
1100
1347
 
1101
1348
  if (parent_object == Qnil) {
1102
- context->Global()->Set(
1103
- v8_str, FunctionTemplate::New(isolate, ruby_callback, external)
1349
+ Maybe<bool> success = context->Global()->Set(
1350
+ context,
1351
+ v8_str,
1352
+ FunctionTemplate::New(isolate, ruby_callback, external)
1104
1353
  ->GetFunction(context)
1105
1354
  .ToLocalChecked());
1355
+ (void)success;
1106
1356
 
1107
1357
  } else {
1108
1358
  Local<String> eval =
1109
1359
  String::NewFromUtf8(isolate, RSTRING_PTR(parent_object_eval),
1110
1360
  NewStringType::kNormal,
1111
- (int)RSTRING_LEN(parent_object_eval))
1361
+ RSTRING_LENINT(parent_object_eval))
1112
1362
  .ToLocalChecked();
1113
1363
 
1114
1364
  MaybeLocal<Script> parsed_script = Script::Compile(context, eval);
1115
1365
  if (parsed_script.IsEmpty()) {
1116
- parse_error = true;
1366
+ parse_error = true;
1117
1367
  } else {
1118
1368
  MaybeLocal<Value> maybe_value =
1119
1369
  parsed_script.ToLocalChecked()->Run(context);
@@ -1122,12 +1372,14 @@ static VALUE rb_external_function_notify_v8(VALUE self) {
1122
1372
  if (!maybe_value.IsEmpty()) {
1123
1373
  Local<Value> value = maybe_value.ToLocalChecked();
1124
1374
  if (value->IsObject()) {
1125
- value.As<Object>()->Set(
1126
- v8_str, FunctionTemplate::New(
1127
- isolate, ruby_callback, external)
1375
+ Maybe<bool> success = value.As<Object>()->Set(
1376
+ context,
1377
+ v8_str,
1378
+ FunctionTemplate::New(isolate, ruby_callback, external)
1128
1379
  ->GetFunction(context)
1129
1380
  .ToLocalChecked());
1130
- attach_error = false;
1381
+ (void)success;
1382
+ attach_error = false;
1131
1383
  }
1132
1384
  }
1133
1385
  }
@@ -1148,7 +1400,7 @@ static VALUE rb_external_function_notify_v8(VALUE self) {
1148
1400
 
1149
1401
  static VALUE rb_context_isolate_mutex(VALUE self) {
1150
1402
  ContextInfo* context_info;
1151
- Data_Get_Struct(self, ContextInfo, context_info);
1403
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1152
1404
 
1153
1405
  if (!context_info->isolate_info) {
1154
1406
  rb_raise(rb_eScriptRuntimeError, "Context has no Isolate available anymore");
@@ -1157,35 +1409,39 @@ static VALUE rb_context_isolate_mutex(VALUE self) {
1157
1409
  return context_info->isolate_info->mutex;
1158
1410
  }
1159
1411
 
1160
- void free_isolate(IsolateInfo* isolate_info) {
1161
-
1162
- if (isolate_info->isolate) {
1163
- Locker lock(isolate_info->isolate);
1164
- }
1165
-
1166
- if (isolate_info->isolate) {
1167
- if (isolate_info->interrupted) {
1168
- fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n");
1412
+ IsolateInfo::~IsolateInfo() {
1413
+ if (isolate) {
1414
+ if (this->interrupted) {
1415
+ fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, "
1416
+ "it can not be disposed and memory will not be "
1417
+ "reclaimed till the Ruby process exits.\n");
1169
1418
  } else {
1170
-
1171
- if (isolate_info->pid != getpid()) {
1172
- fprintf(stderr, "WARNING: V8 isolate was forked, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n");
1419
+ if (this->pid != getpid() && !single_threaded) {
1420
+ fprintf(stderr, "WARNING: V8 isolate was forked, "
1421
+ "it can not be disposed and "
1422
+ "memory will not be reclaimed "
1423
+ "till the Ruby process exits.\n"
1424
+ "It is VERY likely your process will hang.\n"
1425
+ "If you wish to use v8 in forked environment "
1426
+ "please ensure the platform is initialized with:\n"
1427
+ "MiniRacer::Platform.set_flags! :single_threaded\n"
1428
+ );
1173
1429
  } else {
1174
- isolate_info->isolate->Dispose();
1430
+ isolate->Dispose();
1175
1431
  }
1176
1432
  }
1177
- isolate_info->isolate = NULL;
1433
+ isolate = nullptr;
1178
1434
  }
1179
1435
 
1180
- if (isolate_info->startup_data) {
1181
- delete[] isolate_info->startup_data->data;
1182
- delete isolate_info->startup_data;
1436
+ if (startup_data) {
1437
+ delete[] startup_data->data;
1438
+ delete startup_data;
1183
1439
  }
1184
1440
 
1185
- delete isolate_info->allocator;
1441
+ delete allocator;
1186
1442
  }
1187
1443
 
1188
- static void *free_context_raw(void* arg) {
1444
+ static void free_context_raw(void *arg) {
1189
1445
  ContextInfo* context_info = (ContextInfo*)arg;
1190
1446
  IsolateInfo* isolate_info = context_info->isolate_info;
1191
1447
  Persistent<Context>* context = context_info->context;
@@ -1200,37 +1456,37 @@ static void *free_context_raw(void* arg) {
1200
1456
  if (isolate_info) {
1201
1457
  isolate_info->release();
1202
1458
  }
1459
+ }
1203
1460
 
1204
- xfree(context_info);
1461
+ static void *free_context_thr(void* arg) {
1462
+ if (ruby_exiting.load() == 0) {
1463
+ free_context_raw(arg);
1464
+ xfree(arg);
1465
+ }
1205
1466
  return NULL;
1206
1467
  }
1207
1468
 
1208
1469
  // destroys everything except freeing the ContextInfo struct (see deallocate())
1209
1470
  static void free_context(ContextInfo* context_info) {
1210
-
1211
1471
  IsolateInfo* isolate_info = context_info->isolate_info;
1212
1472
 
1213
- ContextInfo* context_info_copy = ALLOC(ContextInfo);
1214
- context_info_copy->isolate_info = context_info->isolate_info;
1215
- context_info_copy->context = context_info->context;
1216
-
1217
1473
  if (isolate_info && isolate_info->refs() > 1) {
1218
- pthread_t free_context_thread;
1219
- if (pthread_create(&free_context_thread, NULL, free_context_raw, (void*)context_info_copy)) {
1220
- fprintf(stderr, "WARNING failed to release memory in MiniRacer, thread to release could not be created, process will leak memory\n");
1221
- }
1222
-
1474
+ pthread_t free_context_thread;
1475
+ ContextInfo* context_info_copy = ALLOC(ContextInfo);
1476
+
1477
+ context_info_copy->isolate_info = context_info->isolate_info;
1478
+ context_info_copy->context = context_info->context;
1479
+ if (pthread_create(&free_context_thread, thread_attr_p,
1480
+ free_context_thr, (void*)context_info_copy)) {
1481
+ fprintf(stderr, "WARNING failed to release memory in MiniRacer, thread to release could not be created, process will leak memory\n");
1482
+ xfree(context_info_copy);
1483
+ }
1223
1484
  } else {
1224
- free_context_raw(context_info_copy);
1485
+ free_context_raw(context_info);
1225
1486
  }
1226
1487
 
1227
- if (context_info->context && isolate_info && isolate_info->isolate) {
1228
- context_info->context = NULL;
1229
- }
1230
-
1231
- if (isolate_info) {
1232
- context_info->isolate_info = NULL;
1233
- }
1488
+ context_info->context = NULL;
1489
+ context_info->isolate_info = NULL;
1234
1490
  }
1235
1491
 
1236
1492
  static void deallocate_isolate(void* data) {
@@ -1245,7 +1501,12 @@ static void mark_isolate(void* data) {
1245
1501
  isolate_info->mark();
1246
1502
  }
1247
1503
 
1248
- void deallocate(void* data) {
1504
+ static size_t isolate_memsize(const void *ptr) {
1505
+ const IsolateInfo *isolate_info = (const IsolateInfo *)ptr;
1506
+ return sizeof(*isolate_info);
1507
+ }
1508
+
1509
+ static void deallocate(void* data) {
1249
1510
  ContextInfo* context_info = (ContextInfo*)data;
1250
1511
 
1251
1512
  free_context(context_info);
@@ -1253,6 +1514,11 @@ void deallocate(void* data) {
1253
1514
  xfree(data);
1254
1515
  }
1255
1516
 
1517
+ static size_t context_memsize(const void *ptr)
1518
+ {
1519
+ return sizeof(ContextInfo);
1520
+ }
1521
+
1256
1522
  static void mark_context(void* data) {
1257
1523
  ContextInfo* context_info = (ContextInfo*)data;
1258
1524
  if (context_info->isolate_info) {
@@ -1260,48 +1526,39 @@ static void mark_context(void* data) {
1260
1526
  }
1261
1527
  }
1262
1528
 
1263
- void deallocate_external_function(void * data) {
1264
- xfree(data);
1265
- }
1266
-
1267
- void deallocate_snapshot(void * data) {
1529
+ static void deallocate_snapshot(void * data) {
1268
1530
  SnapshotInfo* snapshot_info = (SnapshotInfo*)data;
1269
1531
  delete[] snapshot_info->data;
1270
1532
  xfree(snapshot_info);
1271
1533
  }
1272
1534
 
1273
- VALUE allocate_external_function(VALUE klass) {
1274
- VALUE* self = ALLOC(VALUE);
1275
- return Data_Wrap_Struct(klass, NULL, deallocate_external_function, (void*)self);
1535
+ static size_t snapshot_memsize(const void *data) {
1536
+ SnapshotInfo* snapshot_info = (SnapshotInfo*)data;
1537
+ return sizeof(*snapshot_info) + snapshot_info->raw_size;
1276
1538
  }
1277
1539
 
1278
- VALUE allocate(VALUE klass) {
1279
- ContextInfo* context_info = ALLOC(ContextInfo);
1280
- context_info->isolate_info = NULL;
1281
- context_info->context = NULL;
1282
-
1283
- return Data_Wrap_Struct(klass, mark_context, deallocate, (void*)context_info);
1540
+ static VALUE allocate(VALUE klass) {
1541
+ ContextInfo* context_info;
1542
+ return TypedData_Make_Struct(klass, ContextInfo, &context_type, context_info);
1284
1543
  }
1285
1544
 
1286
- VALUE allocate_snapshot(VALUE klass) {
1287
- SnapshotInfo* snapshot_info = ALLOC(SnapshotInfo);
1288
- snapshot_info->data = NULL;
1289
- snapshot_info->raw_size = 0;
1545
+ static VALUE allocate_snapshot(VALUE klass) {
1546
+ SnapshotInfo* snapshot_info;
1290
1547
 
1291
- return Data_Wrap_Struct(klass, NULL, deallocate_snapshot, (void*)snapshot_info);
1548
+ return TypedData_Make_Struct(klass, SnapshotInfo, &snapshot_type, snapshot_info);
1292
1549
  }
1293
1550
 
1294
- VALUE allocate_isolate(VALUE klass) {
1551
+ static VALUE allocate_isolate(VALUE klass) {
1295
1552
  IsolateInfo* isolate_info = new IsolateInfo();
1296
1553
 
1297
- return Data_Wrap_Struct(klass, mark_isolate, deallocate_isolate, (void*)isolate_info);
1554
+ return TypedData_Wrap_Struct(klass, &isolate_type, isolate_info);
1298
1555
  }
1299
1556
 
1300
1557
  static VALUE
1301
1558
  rb_heap_stats(VALUE self) {
1302
1559
 
1303
1560
  ContextInfo* context_info;
1304
- Data_Get_Struct(self, ContextInfo, context_info);
1561
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1305
1562
  Isolate* isolate;
1306
1563
  v8::HeapStatistics stats;
1307
1564
 
@@ -1333,7 +1590,9 @@ rb_heap_stats(VALUE self) {
1333
1590
  // https://github.com/bnoordhuis/node-heapdump/blob/master/src/heapdump.cc
1334
1591
  class FileOutputStream : public OutputStream {
1335
1592
  public:
1336
- FileOutputStream(FILE* stream) : stream_(stream) {}
1593
+ int err;
1594
+
1595
+ FileOutputStream(int fd) : fd(fd) { err = 0; }
1337
1596
 
1338
1597
  virtual int GetChunkSize() {
1339
1598
  return 65536;
@@ -1342,17 +1601,27 @@ class FileOutputStream : public OutputStream {
1342
1601
  virtual void EndOfStream() {}
1343
1602
 
1344
1603
  virtual WriteResult WriteAsciiChunk(char* data, int size) {
1345
- const size_t len = static_cast<size_t>(size);
1346
- size_t off = 0;
1347
-
1348
- while (off < len && !feof(stream_) && !ferror(stream_))
1349
- off += fwrite(data + off, 1, len - off, stream_);
1350
-
1351
- return off == len ? kContinue : kAbort;
1604
+ size_t len = static_cast<size_t>(size);
1605
+
1606
+ while (len) {
1607
+ ssize_t w = write(fd, data, len);
1608
+
1609
+ if (w > 0) {
1610
+ data += w;
1611
+ len -= w;
1612
+ } else if (w < 0) {
1613
+ err = errno;
1614
+ return kAbort;
1615
+ } else { /* w == 0, could be out-of-space */
1616
+ err = -1;
1617
+ return kAbort;
1618
+ }
1619
+ }
1620
+ return kContinue;
1352
1621
  }
1353
1622
 
1354
1623
  private:
1355
- FILE* stream_;
1624
+ int fd;
1356
1625
  };
1357
1626
 
1358
1627
 
@@ -1365,13 +1634,11 @@ rb_heap_snapshot(VALUE self, VALUE file) {
1365
1634
 
1366
1635
  if (!fptr) return Qfalse;
1367
1636
 
1368
- FILE* fp;
1369
- fp = fdopen(fptr->fd, "w");
1370
- if (fp == NULL) return Qfalse;
1371
-
1637
+ // prepare for unbuffered write(2) below:
1638
+ rb_funcall(file, rb_intern("flush"), 0);
1372
1639
 
1373
1640
  ContextInfo* context_info;
1374
- Data_Get_Struct(self, ContextInfo, context_info);
1641
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1375
1642
  Isolate* isolate;
1376
1643
  isolate = context_info->isolate_info ? context_info->isolate_info->isolate : NULL;
1377
1644
 
@@ -1385,11 +1652,14 @@ rb_heap_snapshot(VALUE self, VALUE file) {
1385
1652
 
1386
1653
  const HeapSnapshot* const snap = heap_profiler->TakeHeapSnapshot();
1387
1654
 
1388
- FileOutputStream stream(fp);
1655
+ FileOutputStream stream(fptr->fd);
1389
1656
  snap->Serialize(&stream, HeapSnapshot::kJSON);
1390
1657
 
1391
1658
  const_cast<HeapSnapshot*>(snap)->Delete();
1392
1659
 
1660
+ /* TODO: perhaps rb_sys_fail here */
1661
+ if (stream.err) return Qfalse;
1662
+
1393
1663
  return Qtrue;
1394
1664
  }
1395
1665
 
@@ -1397,12 +1667,12 @@ static VALUE
1397
1667
  rb_context_stop(VALUE self) {
1398
1668
 
1399
1669
  ContextInfo* context_info;
1400
- Data_Get_Struct(self, ContextInfo, context_info);
1670
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1401
1671
 
1402
1672
  Isolate* isolate = context_info->isolate_info->isolate;
1403
1673
 
1404
1674
  // flag for termination
1405
- isolate->SetData(DO_TERMINATE, (void*)true);
1675
+ IsolateData::Set(isolate, IsolateData::DO_TERMINATE, true);
1406
1676
 
1407
1677
  isolate->TerminateExecution();
1408
1678
  rb_funcall(self, rb_intern("stop_attached"), 0);
@@ -1414,7 +1684,7 @@ static VALUE
1414
1684
  rb_context_dispose(VALUE self) {
1415
1685
 
1416
1686
  ContextInfo* context_info;
1417
- Data_Get_Struct(self, ContextInfo, context_info);
1687
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1418
1688
 
1419
1689
  free_context(context_info);
1420
1690
 
@@ -1428,12 +1698,24 @@ nogvl_context_call(void *args) {
1428
1698
  if (!call) {
1429
1699
  return NULL;
1430
1700
  }
1431
- Isolate* isolate = call->context_info->isolate_info->isolate;
1701
+ IsolateInfo *isolate_info = call->context_info->isolate_info;
1702
+ Isolate* isolate = isolate_info->isolate;
1432
1703
 
1433
- // in gvl flag
1434
- isolate->SetData(IN_GVL, (void*)false);
1435
- // terminate ASAP
1436
- isolate->SetData(DO_TERMINATE, (void*)false);
1704
+ IsolateData::Set(isolate, IsolateData::IN_GVL, false);
1705
+ IsolateData::Set(isolate, IsolateData::DO_TERMINATE, false);
1706
+
1707
+ if (call->max_memory > 0) {
1708
+ IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_MAX, call->max_memory);
1709
+ IsolateData::Set(isolate, IsolateData::MEM_SOFTLIMIT_REACHED, false);
1710
+ if (!isolate_info->added_gc_cb) {
1711
+ isolate->AddGCEpilogueCallback(gc_callback);
1712
+ isolate_info->added_gc_cb = true;
1713
+ }
1714
+ }
1715
+
1716
+ if (call->marshal_stackdepth > 0) {
1717
+ StackCounter::SetMax(isolate, call->marshal_stackdepth);
1718
+ }
1437
1719
 
1438
1720
  Isolate::Scope isolate_scope(isolate);
1439
1721
  EscapableHandleScope handle_scope(isolate);
@@ -1450,7 +1732,7 @@ nogvl_context_call(void *args) {
1450
1732
  MaybeLocal<v8::Value> res = fun->Call(context, context->Global(), call->argc, call->argv);
1451
1733
  prepare_result(res, trycatch, isolate, context, eval_res);
1452
1734
 
1453
- isolate->SetData(IN_GVL, (void*)true);
1735
+ IsolateData::Set(isolate, IsolateData::IN_GVL, true);
1454
1736
 
1455
1737
  return NULL;
1456
1738
  }
@@ -1465,7 +1747,7 @@ static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1465
1747
  FunctionCall call;
1466
1748
  VALUE *call_argv = NULL;
1467
1749
 
1468
- Data_Get_Struct(self, ContextInfo, context_info);
1750
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1469
1751
  Isolate* isolate = context_info->isolate_info->isolate;
1470
1752
 
1471
1753
  if (argc < 1) {
@@ -1473,9 +1755,7 @@ static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1473
1755
  }
1474
1756
 
1475
1757
  VALUE function_name = argv[0];
1476
- if (TYPE(function_name) != T_STRING) {
1477
- rb_raise(rb_eTypeError, "first argument should be a String");
1478
- }
1758
+ Check_Type(function_name, T_STRING);
1479
1759
 
1480
1760
  char *fname = RSTRING_PTR(function_name);
1481
1761
  if (!fname) {
@@ -1492,6 +1772,20 @@ static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1492
1772
  call_argv = argv + 1;
1493
1773
  }
1494
1774
 
1775
+ call.max_memory = 0;
1776
+ VALUE mem_softlimit = rb_iv_get(self, "@max_memory");
1777
+ if (mem_softlimit != Qnil) {
1778
+ unsigned long sl_int = NUM2ULONG(mem_softlimit);
1779
+ call.max_memory = (size_t)sl_int;
1780
+ }
1781
+
1782
+ call.marshal_stackdepth = 0;
1783
+ VALUE marshal_stackdepth = rb_iv_get(self, "@marshal_stack_depth");
1784
+ if (marshal_stackdepth != Qnil) {
1785
+ unsigned long sl_int = NUM2ULONG(marshal_stackdepth);
1786
+ call.marshal_stackdepth = (size_t)sl_int;
1787
+ }
1788
+
1495
1789
  bool missingFunction = false;
1496
1790
  {
1497
1791
  Locker lock(isolate);
@@ -1503,29 +1797,24 @@ static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1503
1797
 
1504
1798
  // examples of such usage can be found in
1505
1799
  // https://github.com/v8/v8/blob/36b32aa28db5e993312f4588d60aad5c8330c8a5/test/cctest/test-api.cc#L15711
1506
- Local<String> fname = String::NewFromUtf8(isolate, call.function_name);
1507
- MaybeLocal<v8::Value> val = context->Global()->Get(fname);
1800
+ MaybeLocal<String> fname = String::NewFromUtf8(isolate, call.function_name);
1801
+ MaybeLocal<v8::Value> val;
1802
+ if (!fname.IsEmpty()) {
1803
+ val = context->Global()->Get(context, fname.ToLocalChecked());
1804
+ }
1508
1805
 
1509
1806
  if (val.IsEmpty() || !val.ToLocalChecked()->IsFunction()) {
1510
1807
  missingFunction = true;
1511
1808
  } else {
1512
-
1513
1809
  Local<v8::Function> fun = Local<v8::Function>::Cast(val.ToLocalChecked());
1810
+ VALUE tmp;
1514
1811
  call.fun = fun;
1515
- int fun_argc = call.argc;
1516
-
1517
- if (fun_argc > 0) {
1518
- call.argv = (v8::Local<Value> *) malloc(sizeof(void *) * fun_argc);
1519
- if (!call.argv) {
1520
- return Qnil;
1521
- }
1522
- for(int i=0; i < fun_argc; i++) {
1523
- call.argv[i] = convert_ruby_to_v8(isolate, context, call_argv[i]);
1524
- }
1812
+ call.argv = (v8::Local<Value> *)RB_ALLOCV_N(void *, tmp, call.argc);
1813
+ for(int i=0; i < call.argc; i++) {
1814
+ call.argv[i] = convert_ruby_to_v8(isolate, context, call_argv[i]);
1525
1815
  }
1526
1816
  rb_thread_call_without_gvl(nogvl_context_call, &call, unblock_function, &call);
1527
- free(call.argv);
1528
-
1817
+ RB_ALLOCV_END(tmp);
1529
1818
  }
1530
1819
  }
1531
1820
 
@@ -1538,7 +1827,7 @@ static VALUE rb_context_call_unsafe(int argc, VALUE *argv, VALUE self) {
1538
1827
 
1539
1828
  static VALUE rb_context_create_isolate_value(VALUE self) {
1540
1829
  ContextInfo* context_info;
1541
- Data_Get_Struct(self, ContextInfo, context_info);
1830
+ TypedData_Get_Struct(self, ContextInfo, &context_type, context_info);
1542
1831
  IsolateInfo *isolate_info = context_info->isolate_info;
1543
1832
 
1544
1833
  if (!isolate_info) {
@@ -1546,12 +1835,18 @@ static VALUE rb_context_create_isolate_value(VALUE self) {
1546
1835
  }
1547
1836
 
1548
1837
  isolate_info->hold();
1549
- return Data_Wrap_Struct(rb_cIsolate, NULL, &deallocate_isolate, isolate_info);
1838
+ return TypedData_Wrap_Struct(rb_cIsolate, &isolate_type, isolate_info);
1839
+ }
1840
+
1841
+ static void set_ruby_exiting(VALUE value) {
1842
+ (void)value;
1843
+
1844
+ ruby_exiting.store(1);
1550
1845
  }
1551
1846
 
1552
1847
  extern "C" {
1553
1848
 
1554
- void Init_mini_racer_extension ( void )
1849
+ __attribute__((visibility("default"))) void Init_mini_racer_extension ( void )
1555
1850
  {
1556
1851
  VALUE rb_mMiniRacer = rb_define_module("MiniRacer");
1557
1852
  rb_cContext = rb_define_class_under(rb_mMiniRacer, "Context", rb_cObject);
@@ -1591,7 +1886,6 @@ extern "C" {
1591
1886
  rb_define_alloc_func(rb_cIsolate, allocate_isolate);
1592
1887
 
1593
1888
  rb_define_private_method(rb_cExternalFunction, "notify_v8", (VALUE(*)(...))&rb_external_function_notify_v8, 0);
1594
- rb_define_alloc_func(rb_cExternalFunction, allocate_external_function);
1595
1889
 
1596
1890
  rb_define_method(rb_cSnapshot, "size", (VALUE(*)(...))&rb_snapshot_size, 0);
1597
1891
  rb_define_method(rb_cSnapshot, "dump", (VALUE(*)(...))&rb_snapshot_dump, 0);
@@ -1599,8 +1893,19 @@ extern "C" {
1599
1893
  rb_define_private_method(rb_cSnapshot, "load", (VALUE(*)(...))&rb_snapshot_load, 1);
1600
1894
 
1601
1895
  rb_define_method(rb_cIsolate, "idle_notification", (VALUE(*)(...))&rb_isolate_idle_notification, 1);
1896
+ rb_define_method(rb_cIsolate, "low_memory_notification", (VALUE(*)(...))&rb_isolate_low_memory_notification, 0);
1897
+ rb_define_method(rb_cIsolate, "pump_message_loop", (VALUE(*)(...))&rb_isolate_pump_message_loop, 0);
1602
1898
  rb_define_private_method(rb_cIsolate, "init_with_snapshot",(VALUE(*)(...))&rb_isolate_init_with_snapshot, 1);
1603
1899
 
1604
1900
  rb_define_singleton_method(rb_cPlatform, "set_flag_as_str!", (VALUE(*)(...))&rb_platform_set_flag_as_str, 1);
1901
+
1902
+ rb_set_end_proc(set_ruby_exiting, Qnil);
1903
+
1904
+ static pthread_attr_t attr;
1905
+ if (pthread_attr_init(&attr) == 0) {
1906
+ if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0) {
1907
+ thread_attr_p = &attr;
1908
+ }
1909
+ }
1605
1910
  }
1606
1911
  }