-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathmini_racer_extension.c
More file actions
1767 lines (1598 loc) · 47.3 KB
/
mini_racer_extension.c
File metadata and controls
1767 lines (1598 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#if defined(__linux__) && !defined(__GLIBC__)
// musl compatibility for glibc-linked libraries (e.g. libv8-node)
// some versions of libv8-node are accidentally linked against glibc symbols
// or compiled with a toolchain that emits these C23 compatibility symbols
unsigned long long __isoc23_strtoull(const char *nptr, char **endptr, int base) {
return strtoull(nptr, endptr, base);
}
unsigned long __isoc23_strtoul(const char *nptr, char **endptr, int base) {
return strtoul(nptr, endptr, base);
}
long long __isoc23_strtoll(const char *nptr, char **endptr, int base) {
return strtoll(nptr, endptr, base);
}
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
return strtol(nptr, endptr, base);
}
double __isoc23_strtod(const char *nptr, char **endptr) {
return strtod(nptr, endptr);
}
float __isoc23_strtof(const char *nptr, char **endptr) {
return strtof(nptr, endptr);
}
#endif
#include "ruby.h"
#include "ruby/encoding.h"
#include "ruby/version.h"
#include "ruby/thread.h"
#include "serde.c"
#include "mini_racer_v8.h"
// for debugging
#define RB_PUTS(v) \
do { \
fflush(stdout); \
rb_funcall(rb_mKernel, rb_intern("puts"), 1, v); \
} while (0)
#if RUBY_API_VERSION_CODE < 3*10000+4*100 // 3.4.0
static inline void rb_thread_lock_native_thread(void)
{
// Without rb_thread_lock_native_thread, V8 in single-threaded mode is
// prone to crash with debug checks like this...
//
// # Fatal error in ../deps/v8/src/base/platform/platform-posix.cc, line 1350
// # Debug check failed: MainThreadIsCurrentThread().
//
// ...because the Ruby runtime clobbers thread-local variables when it
// context-switches threads. You have been warned.
}
#endif
#define countof(x) (sizeof(x) / sizeof(*(x)))
#define endof(x) ((x) + countof(x))
// mostly RO: assigned once by platform_set_flag1 while holding |flags_mtx|,
// from then on read-only and accessible without holding locks
int single_threaded;
// work around missing pthread_barrier_t on macOS
typedef struct Barrier
{
pthread_mutex_t mtx;
pthread_cond_t cv;
int count, in, out;
} Barrier;
static inline int barrier_init(Barrier *b, int count)
{
int r;
if ((r = pthread_mutex_init(&b->mtx, NULL)))
return r;
if ((r = pthread_cond_init(&b->cv, NULL))) {
pthread_mutex_destroy(&b->mtx);
return r;
}
b->count = count;
b->out = 0;
b->in = 0;
return 0;
}
static inline void barrier_destroy(Barrier *b)
{
pthread_mutex_destroy(&b->mtx);
pthread_cond_destroy(&b->cv);
}
static inline int barrier_wait(Barrier *b)
{
int last;
pthread_mutex_lock(&b->mtx);
while (b->out)
pthread_cond_wait(&b->cv, &b->mtx);
if (++b->in == b->count) {
b->in = 0;
b->out = b->count;
pthread_cond_broadcast(&b->cv);
} else {
do
pthread_cond_wait(&b->cv, &b->mtx);
while (b->in);
}
last = (--b->out == 0);
if (last)
pthread_cond_broadcast(&b->cv);
pthread_mutex_unlock(&b->mtx);
return last;
}
typedef struct Context
{
int depth; // call depth, protected by |rr_mtx|
// protected by |mtx|; RW for ruby threads, RO for v8 thread;
// atomic because context_stop (which can be called from other ruby
// threads) writes it without holding |mtx|, to avoid deadlocking
// 1=shut down v8, 2=free memory; note that only the v8 thread
// frees the memory and it intentionally stays around until
// the ruby object is gc'd, otherwise lifecycle management
// gets too complicated
atomic_int quit;
int verbose_exceptions;
int64_t idle_gc, max_memory, timeout;
struct State *pst; // used by v8 thread
VALUE procs; // array of js -> ruby callbacks
VALUE exception; // pending exception or Qnil
Buf req, res; // ruby->v8 request/response, mediated by |mtx| and |cv|
Buf snapshot;
// |rr_mtx| stands for "recursive ruby mutex"; it's used to exclude
// other ruby threads but allow reentrancy from the same ruby thread
// (think ruby->js->ruby->js calls)
pthread_mutex_t rr_mtx;
pthread_mutex_t mtx;
pthread_cond_t cv;
struct {
pthread_mutex_t mtx;
pthread_cond_t cv;
int cancel;
} wd; // watchdog
Barrier early_init, late_init;
} Context;
typedef struct Snapshot {
VALUE blob;
} Snapshot;
static void context_destroy(Context *c);
static void context_free(void *arg);
static void context_mark(void *arg);
static size_t context_size(const void *arg);
static const rb_data_type_t context_type = {
.wrap_struct_name = "mini_racer/context",
.function = {
.dfree = context_free,
.dmark = context_mark,
.dsize = context_size,
},
};
static void snapshot_free(void *arg);
static void snapshot_mark(void *arg);
static size_t snapshot_size(const void *arg);
static const rb_data_type_t snapshot_type = {
.wrap_struct_name = "mini_racer/snapshot",
.function = {
.dfree = snapshot_free,
.dmark = snapshot_mark,
.dsize = snapshot_size,
},
};
static VALUE platform_init_error;
static VALUE context_disposed_error;
static VALUE parse_error;
static VALUE memory_error;
static VALUE script_error;
static VALUE runtime_error;
static VALUE internal_error;
static VALUE snapshot_error;
static VALUE terminated_error;
static VALUE context_class;
static VALUE snapshot_class;
static VALUE date_time_class;
static VALUE js_function_class;
static pthread_mutex_t flags_mtx = PTHREAD_MUTEX_INITIALIZER;
static Buf flags; // protected by |flags_mtx|
// arg == &(struct rendezvous_nogvl){...}
static void *rendezvous_callback(void *arg);
// note: must be stack-allocated or VALUEs won't be visible to ruby's GC
typedef struct State
{
VALUE a, b;
uint8_t verbatim_keys:1;
} State;
// note: must be stack-allocated or VALUEs won't be visible to ruby's GC
typedef struct DesCtx
{
State *tos;
VALUE refs; // object refs array
uint8_t transcode_latin1:1;
char err[64];
State stack[512];
} DesCtx;
struct rendezvous_nogvl
{
Context *context;
Buf *req, *res;
};
struct rendezvous_des
{
DesCtx *d;
Buf *res;
};
static void DesCtx_init(DesCtx *c)
{
c->tos = c->stack;
c->refs = rb_ary_new();
*c->tos = (State){Qundef, Qundef, /*verbatim_keys*/0};
*c->err = '\0';
c->transcode_latin1 = 1; // convert to utf8
}
static void put(DesCtx *c, VALUE v)
{
VALUE *a, *b;
if (*c->err)
return;
a = &c->tos->a;
b = &c->tos->b;
switch (TYPE(*a)) {
case T_ARRAY:
rb_ary_push(*a, v);
break;
case T_HASH:
if (*b == Qundef) {
*b = v;
} else {
if (!c->tos->verbatim_keys)
*b = rb_funcall(*b, rb_intern("to_s"), 0);
rb_hash_aset(*a, *b, v);
*b = Qundef;
}
break;
case T_UNDEF:
*a = v;
break;
default:
snprintf(c->err, sizeof(c->err), "bad state");
return;
}
}
static void push(DesCtx *c, VALUE v)
{
if (*c->err)
return;
if (c->tos == endof(c->stack)) {
snprintf(c->err, sizeof(c->err), "stack overflow");
return;
}
*++c->tos = (State){v, Qundef, /*verbatim_keys*/0};
rb_ary_push(c->refs, v);
}
// see also des_named_props_end
static void pop(DesCtx *c)
{
if (*c->err)
return;
if (c->tos == c->stack) {
snprintf(c->err, sizeof(c->err), "stack underflow");
return;
}
put(c, (*c->tos--).a);
}
static void des_null(void *arg)
{
put(arg, Qnil);
}
static void des_undefined(void *arg)
{
put(arg, Qnil);
}
static void des_bool(void *arg, int v)
{
put(arg, v ? Qtrue : Qfalse);
}
static void des_int(void *arg, int64_t v)
{
put(arg, LONG2FIX(v));
}
static void des_num(void *arg, double v)
{
if (isfinite(v) && v == trunc(v) && v >= INT64_MIN && v <= INT64_MAX) {
put(arg, LONG2FIX(v));
} else {
put(arg, DBL2NUM(v));
}
}
static void des_date(void *arg, double v)
{
double sec, usec;
if (!isfinite(v))
rb_raise(rb_eRangeError, "invalid Date");
sec = v/1e3;
usec = 1e3 * fmod(v, 1e3);
put(arg, rb_time_new(sec, usec));
}
// note: v8 stores bigints in 1's complement, ruby in 2's complement,
// so we have to take additional steps to ensure correct conversion
static void des_bigint(void *arg, const void *p, size_t n, int sign)
{
VALUE v;
size_t i;
DesCtx *c;
unsigned long *a, t, limbs[65]; // +1 to suppress sign extension
c = arg;
if (*c->err)
return;
if (n > sizeof(limbs) - sizeof(*limbs)) {
snprintf(c->err, sizeof(c->err), "bigint too big");
return;
}
a = limbs;
t = 0;
for (i = 0; i < n; a++, i += sizeof(*a)) {
memcpy(a, (char *)p + i, sizeof(*a));
t = *a;
}
if (t >> 63)
*a++ = 0; // suppress sign extension
v = rb_big_unpack(limbs, a-limbs);
if (sign < 0) {
// rb_big_unpack returns T_FIXNUM for smallish bignums
switch (TYPE(v)) {
case T_BIGNUM:
v = rb_big_mul(v, LONG2FIX(-1));
break;
case T_FIXNUM:
v = LONG2FIX(-1 * FIX2LONG(v));
break;
default:
abort();
}
}
put(c, v);
}
static void des_string(void *arg, const char *s, size_t n)
{
put(arg, rb_utf8_str_new(s, n));
}
static VALUE str_encode_bang(VALUE v)
{
// TODO cache these? this function can get called often
return rb_funcall(v, rb_intern("encode!"), 1, rb_str_new_cstr("UTF-8"));
}
static void des_string8(void *arg, const uint8_t *s, size_t n)
{
rb_encoding *e;
DesCtx *c;
VALUE v;
c = arg;
if (*c->err)
return;
if (c->transcode_latin1) {
e = rb_enc_find("ISO-8859-1"); // TODO cache?
if (!e) {
snprintf(c->err, sizeof(c->err), "no ISO-8859-1 encoding");
return;
}
v = rb_enc_str_new((char *)s, n, e);
v = str_encode_bang(v); // cannot fail
} else {
v = rb_enc_str_new((char *)s, n, rb_ascii8bit_encoding());
}
put(c, v);
}
// des_string16: |s| is not word aligned
// des_string16: |n| is in bytes, not code points
static void des_string16(void *arg, const void *s, size_t n)
{
rb_encoding *e;
VALUE v, r;
DesCtx *c;
int exc;
c = arg;
if (*c->err)
return;
// TODO(bnoordhuis) replace this hack with something more principled
if (n == sizeof(js_function_marker) && !memcmp(js_function_marker, s, n))
return put(c, rb_funcall(js_function_class, rb_intern("new"), 0));
e = rb_enc_find("UTF-16LE"); // TODO cache?
if (!e) {
snprintf(c->err, sizeof(c->err), "no UTF16-LE encoding");
return;
}
v = rb_enc_str_new((char *)s, n, e);
// JS strings can contain unmatched or illegal surrogate pairs
// that Ruby won't decode; return the string as-is in that case
r = rb_protect(str_encode_bang, v, &exc);
if (exc) {
rb_set_errinfo(Qnil);
r = v;
}
put(c, r);
}
// ruby doesn't really have a concept of a byte array so store it as
// an 8-bit string instead; it's either that or a regular array of
// numbers, but the latter is markedly less efficient, storage-wise
static void des_arraybuffer(void *arg, const void *s, size_t n)
{
put(arg, rb_enc_str_new((char *)s, n, rb_ascii8bit_encoding()));
}
static void des_array_begin(void *arg)
{
push(arg, rb_ary_new());
}
static void des_array_end(void *arg)
{
pop(arg);
}
static void des_named_props_begin(void *arg)
{
push(arg, rb_hash_new());
}
// see also pop
static void des_named_props_end(void *arg)
{
DesCtx *c;
c = arg;
if (*c->err)
return;
if (c->tos == c->stack) {
snprintf(c->err, sizeof(c->err), "stack underflow");
return;
}
c->tos--; // dropped, no way to represent in ruby
}
static void des_object_begin(void *arg)
{
push(arg, rb_hash_new());
}
static void des_object_end(void *arg)
{
pop(arg);
}
static void des_map_begin(void *arg)
{
DesCtx *c;
c = arg;
push(c, rb_hash_new());
c->tos->verbatim_keys = 1; // don't stringify or intern keys
}
static void des_map_end(void *arg)
{
pop(arg);
}
static void des_object_ref(void *arg, uint32_t id)
{
DesCtx *c;
VALUE v;
c = arg;
v = rb_ary_entry(c->refs, id);
put(c, v);
}
static void des_error_begin(void *arg)
{
push(arg, rb_ary_new());
}
static void des_error_end(void *arg)
{
VALUE *a, h, message, stack, cause, newline;
DesCtx *c;
c = arg;
if (*c->err)
return;
if (c->tos == c->stack) {
snprintf(c->err, sizeof(c->err), "stack underflow");
return;
}
a = &c->tos->a;
h = rb_ary_pop(*a);
message = rb_hash_aref(h, rb_str_new_cstr("message"));
stack = rb_hash_aref(h, rb_str_new_cstr("stack"));
cause = rb_hash_aref(h, rb_str_new_cstr("cause"));
if (NIL_P(message))
message = rb_str_new_cstr("JS exception");
if (!NIL_P(stack)) {
newline = rb_str_new_cstr("\n");
message = rb_funcall(message, rb_intern("concat"), 2, newline, stack);
}
*a = rb_class_new_instance(1, &message, script_error);
if (!NIL_P(cause))
rb_iv_set(*a, "@cause", cause);
pop(c);
}
static int collect(VALUE k, VALUE v, VALUE a)
{
rb_ary_push(a, k);
rb_ary_push(a, v);
return ST_CONTINUE;
}
static void add_string(Ser *s, VALUE v)
{
rb_encoding *e;
const void *p;
size_t n;
Check_Type(v, T_STRING);
e = rb_enc_get(v);
p = RSTRING_PTR(v);
n = RSTRING_LEN(v);
if (e) {
if (!strcmp(e->name, "ISO-8859-1"))
return ser_string8(s, p, n);
if (!strcmp(e->name, "UTF-16LE"))
return ser_string16(s, p, n);
}
return ser_string(s, p, n);
}
static int serialize1(Ser *s, VALUE refs, VALUE v)
{
unsigned long limbs[64];
VALUE a, t, id;
size_t i, n;
int sign;
if (*s->err)
return -1;
switch (TYPE(v)) {
case T_ARRAY:
{
VALUE obj_id = rb_obj_id(v);
id = rb_hash_lookup(refs, obj_id);
if (NIL_P(id)) {
n = RARRAY_LENINT(v);
i = rb_hash_size_num(refs);
rb_hash_aset(refs, obj_id, LONG2FIX(i));
ser_array_begin(s, n);
for (i = 0; i < n; i++)
if (serialize1(s, refs, rb_ary_entry(v, i)))
return -1;
ser_array_end(s, n);
} else {
ser_object_ref(s, FIX2LONG(id));
}
}
break;
case T_HASH:
{
VALUE obj_id = rb_obj_id(v);
id = rb_hash_lookup(refs, obj_id);
if (NIL_P(id)) {
a = rb_ary_new();
i = rb_hash_size_num(refs);
n = rb_hash_size_num(v);
rb_hash_aset(refs, obj_id, LONG2FIX(i));
rb_hash_foreach(v, collect, a);
for (i = 0; i < 2*n; i += 2) {
t = rb_ary_entry(a, i);
switch (TYPE(t)) {
case T_FIXNUM:
case T_STRING:
case T_SYMBOL:
continue;
}
break;
}
if (i == 2*n) {
ser_object_begin(s);
for (i = 0; i < 2*n; i += 2) {
if (serialize1(s, refs, rb_ary_entry(a, i+0)))
return -1;
if (serialize1(s, refs, rb_ary_entry(a, i+1)))
return -1;
}
ser_object_end(s, n);
} else {
return bail(&s->err, "TODO serialize as Map");
}
} else {
ser_object_ref(s, FIX2LONG(id));
}
}
break;
case T_DATA:
if (date_time_class == CLASS_OF(v)) {
v = rb_funcall(v, rb_intern("to_time"), 0);
}
if (rb_cTime == CLASS_OF(v)) {
struct timeval tv = rb_time_timeval(v);
ser_date(s, tv.tv_sec*1e3 + tv.tv_usec/1e3);
} else {
static const char undefined_conversion[] = "Undefined Conversion";
ser_string(s, undefined_conversion, sizeof(undefined_conversion)-1);
}
break;
case T_NIL:
ser_null(s);
break;
case T_UNDEF:
ser_undefined(s);
break;
case T_TRUE:
ser_bool(s, 1);
break;
case T_FALSE:
ser_bool(s, 0);
break;
case T_BIGNUM:
// note: v8 stores bigints in 1's complement, ruby in 2's complement,
// so we have to take additional steps to ensure correct conversion
memset(limbs, 0, sizeof(limbs));
sign = rb_big_sign(v) ? 1 : -1;
if (sign < 0)
v = rb_big_mul(v, LONG2FIX(-1));
rb_big_pack(v, limbs, countof(limbs));
ser_bigint(s, limbs, countof(limbs), sign);
break;
case T_FIXNUM:
ser_int(s, FIX2LONG(v));
break;
case T_FLOAT:
ser_num(s, NUM2DBL(v));
break;
case T_SYMBOL:
v = rb_sym2str(v);
// fallthru
case T_STRING:
add_string(s, v);
break;
case T_OBJECT:
// this is somewhat wide, but we have active support which creates
// entirely new objects
if (rb_respond_to(v, rb_intern("to_time"))) {
v = rb_funcall(v, rb_intern("to_time"), 0);
}
if (rb_obj_is_kind_of(v, rb_cTime)) {
struct timeval tv = rb_time_timeval(v);
ser_date(s, tv.tv_sec*1e3 + tv.tv_usec/1e3);
} else {
snprintf(s->err, sizeof(s->err), "unsupported type %s", rb_class2name(CLASS_OF(v)));
return -1;
}
break;
default:
snprintf(s->err, sizeof(s->err), "unsupported type %x", TYPE(v));
return -1;
}
if (*s->err)
return -1;
return 0;
}
// don't mix with ser_array_begin/ser_object_begin because
// that will throw off the object reference count
static int serialize(Ser *s, VALUE v)
{
return serialize1(s, rb_hash_new(), v);
}
static struct timespec deadline_ms(int ms)
{
static const int64_t ns_per_sec = 1000*1000*1000;
struct timespec t;
#ifdef __APPLE__
clock_gettime(CLOCK_REALTIME, &t);
#else
clock_gettime(CLOCK_MONOTONIC, &t);
#endif
t.tv_sec += ms/1000;
t.tv_nsec += ms%1000 * ns_per_sec/1000;
while (t.tv_nsec >= ns_per_sec) {
t.tv_nsec -= ns_per_sec;
t.tv_sec++;
}
return t;
}
static int timespec_le(struct timespec a, struct timespec b)
{
if (a.tv_sec < b.tv_sec) return 1;
return a.tv_sec == b.tv_sec && a.tv_nsec <= b.tv_nsec;
}
static int deadline_exceeded(struct timespec deadline)
{
return timespec_le(deadline, deadline_ms(0));
}
static void *v8_watchdog(void *arg)
{
struct timespec deadline;
Context *c;
c = arg;
deadline = deadline_ms(c->timeout);
pthread_mutex_lock(&c->wd.mtx);
for (;;) {
if (c->wd.cancel)
break;
pthread_cond_timedwait(&c->wd.cv, &c->wd.mtx, &deadline);
if (c->wd.cancel)
break;
if (deadline_exceeded(deadline)) {
v8_terminate_execution(c->pst);
break;
}
}
pthread_mutex_unlock(&c->wd.mtx);
return NULL;
}
static void v8_timedwait(Context *c, const uint8_t *p, size_t n,
void (*func)(struct State *pst, const uint8_t *p, size_t n))
{
pthread_t thr;
int r;
r = -1;
if (c->timeout > 0 && (r = pthread_create(&thr, NULL, v8_watchdog, c))) {
fprintf(stderr, "mini_racer: watchdog: pthread_create: %s\n", strerror(r));
fflush(stderr);
}
func(c->pst, p, n);
if (r)
return;
pthread_mutex_lock(&c->wd.mtx);
c->wd.cancel = 1;
pthread_cond_signal(&c->wd.cv);
pthread_mutex_unlock(&c->wd.mtx);
pthread_join(thr, NULL);
c->wd.cancel = 0;
}
static void dispatch1(Context *c, const uint8_t *p, size_t n)
{
uint8_t b;
assert(n > 0);
switch (*p) {
case 'A': return v8_attach(c->pst, p+1, n-1);
case 'C': return v8_timedwait(c, p+1, n-1, v8_call);
case 'E': return v8_timedwait(c, p+1, n-1, v8_eval);
case 'H': return v8_heap_snapshot(c->pst);
case 'P': return v8_pump_message_loop(c->pst);
case 'S': return v8_heap_stats(c->pst);
case 'T': return v8_snapshot(c->pst, p+1, n-1);
case 'W': return v8_warmup(c->pst, p+1, n-1);
case 'L':
b = 0;
v8_reply(c, &b, 1); // doesn't matter what as long as it's not empty
return v8_low_memory_notification(c->pst);
}
fprintf(stderr, "mini_racer: bad request %02x\n", *p);
fflush(stderr);
}
static void dispatch(Context *c)
{
buf_reset(&c->res);
dispatch1(c, c->req.buf, c->req.len);
buf_reset(&c->req);
}
// called by v8_isolate_and_context
void v8_thread_main(Context *c, struct State *pst)
{
struct timespec deadline;
bool issued_idle_gc = true;
c->pst = pst;
barrier_wait(&c->late_init);
pthread_mutex_lock(&c->mtx);
while (!c->quit) {
if (!c->req.len) {
if (c->idle_gc > 0) {
deadline = deadline_ms(c->idle_gc);
pthread_cond_timedwait(&c->cv, &c->mtx, &deadline);
if (deadline_exceeded(deadline) && !issued_idle_gc) {
v8_low_memory_notification(c->pst);
issued_idle_gc = true;
}
} else {
pthread_cond_wait(&c->cv, &c->mtx);
}
}
if (!c->req.len)
continue; // spurious wakeup or quit signal from other thread
dispatch(c);
issued_idle_gc = false;
pthread_cond_signal(&c->cv);
}
}
// called by v8_thread_main and from mini_racer_v8.cc,
// in all cases with Context.mtx held
void v8_dispatch(Context *c)
{
dispatch1(c, c->req.buf, c->req.len);
buf_reset(&c->req);
}
// called from mini_racer_v8.cc with Context.mtx held
// only called when inside v8_call, v8_eval, or v8_pump_message_loop
void v8_roundtrip(Context *c, const uint8_t **p, size_t *n)
{
struct rendezvous_nogvl *args;
buf_reset(&c->req);
if (single_threaded) {
assert(*c->res.buf == 'c'); // js -> ruby callback
args = &(struct rendezvous_nogvl){c, &c->req, &c->res};
rb_thread_call_with_gvl(rendezvous_callback, args);
} else {
pthread_cond_signal(&c->cv);
while (!c->req.len)
pthread_cond_wait(&c->cv, &c->mtx);
}
buf_reset(&c->res);
*p = c->req.buf;
*n = c->req.len;
}
// called from mini_racer_v8.cc with Context.mtx held
void v8_reply(Context *c, const uint8_t *p, size_t n)
{
buf_put(&c->res, p, n);
}
static void v8_once_init(void)
{
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, v8_global_init);
}
static void *v8_thread_start(void *arg)
{
Context *c;
c = arg;
barrier_wait(&c->early_init);
v8_once_init();
v8_thread_init(c, c->snapshot.buf, c->snapshot.len, c->max_memory, c->verbose_exceptions);
while (c->quit < 2)
pthread_cond_wait(&c->cv, &c->mtx);
context_destroy(c);
return NULL;
}
static VALUE deserialize1(DesCtx *d, const uint8_t *p, size_t n)
{
char err[64];
if (des(&err, p, n, d))
rb_raise(runtime_error, "%s", err);
if (d->tos != d->stack) // should not happen
rb_raise(runtime_error, "parse stack not empty");
return d->tos->a;
}
static VALUE deserialize(VALUE arg)
{
struct rendezvous_des *a;
Buf *b;
a = (void *)arg;
b = a->res;
return deserialize1(a->d, b->buf, b->len);
}
// called with |rr_mtx| and GVL held; can raise exception
static VALUE rendezvous_callback_do(VALUE arg)
{
struct rendezvous_nogvl *a;
VALUE func, args;
Context *c;
DesCtx d;
Buf *b;
a = (void *)arg;
b = a->res;
c = a->context;
assert(b->len > 0);
assert(*b->buf == 'c');
DesCtx_init(&d);
args = deserialize1(&d, b->buf+1, b->len-1); // skip 'c' marker
func = rb_ary_pop(args); // callback id
func = rb_ary_entry(c->procs, FIX2LONG(func));
return rb_funcall2(func, rb_intern("call"), RARRAY_LENINT(args), RARRAY_PTR(args));
}
// called with |rr_mtx| and GVL held; |mtx| is unlocked
// callback data is in |a->res|, serialized result goes in |a->req|
static void *rendezvous_callback(void *arg)
{
struct rendezvous_nogvl *a;
const char *err;
Context *c;
int exc;
VALUE r;
Ser s;
a = arg;
c = a->context;
r = rb_protect(rendezvous_callback_do, (VALUE)a, &exc);
if (exc) {
c->exception = rb_errinfo();
rb_set_errinfo(Qnil);
goto fail;
}
ser_init1(&s, 'c'); // callback reply
if (serialize(&s, r)) { // should not happen
c->exception = rb_exc_new_cstr(internal_error, s.err);
ser_reset(&s);
goto fail;
}
out:
buf_move(&s.b, a->req);
return NULL;
fail:
ser_init0(&s); // ruby exception pending
w_byte(&s, 'e'); // send ruby error message to v8 thread
r = rb_funcall(c->exception, rb_intern("to_s"), 0);
err = StringValueCStr(r);
if (err)
w(&s, err, strlen(err));
goto out;
}
static inline void *rendezvous_nogvl(void *arg)
{
struct rendezvous_nogvl *a;
Context *c;
a = arg;
c = a->context;
pthread_mutex_lock(&c->rr_mtx);
if (c->depth > 0 && c->depth%50 == 0) { // TODO stop steep recursion
fprintf(stderr, "mini_racer: deep js->ruby->js recursion, depth=%d\n", c->depth);
fflush(stderr);
}
c->depth++;
next:
pthread_mutex_lock(&c->mtx);