/
runtime.rs
3929 lines (3496 loc) · 121 KB
/
runtime.rs
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::bindings;
use crate::error::generic_error;
use crate::error::to_v8_type_error;
use crate::error::JsError;
use crate::extensions::OpDecl;
use crate::extensions::OpEventLoopFn;
use crate::inspector::JsRuntimeInspector;
use crate::module_specifier::ModuleSpecifier;
use crate::modules::ModuleError;
use crate::modules::ModuleId;
use crate::modules::ModuleLoadId;
use crate::modules::ModuleLoader;
use crate::modules::ModuleMap;
use crate::modules::NoopModuleLoader;
use crate::op_void_async;
use crate::op_void_sync;
use crate::ops::*;
use crate::source_map::SourceMapCache;
use crate::source_map::SourceMapGetter;
use crate::Extension;
use crate::OpMiddlewareFn;
use crate::OpResult;
use crate::OpState;
use crate::PromiseId;
use anyhow::Error;
use futures::channel::oneshot;
use futures::future::poll_fn;
use futures::future::Future;
use futures::future::FutureExt;
use futures::stream::FuturesUnordered;
use futures::stream::StreamExt;
use futures::task::AtomicWaker;
use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::option::Option;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Once;
use std::task::Context;
use std::task::Poll;
use v8::OwnedIsolate;
type PendingOpFuture = OpCall<(PromiseId, OpId, OpResult)>;
pub enum Snapshot {
Static(&'static [u8]),
JustCreated(v8::StartupData),
Boxed(Box<[u8]>),
}
pub type JsErrorCreateFn = dyn Fn(JsError) -> Error;
pub type GetErrorClassFn = &'static dyn for<'e> Fn(&'e Error) -> &'static str;
/// Objects that need to live as long as the isolate
#[derive(Default)]
struct IsolateAllocations {
near_heap_limit_callback_data:
Option<(Box<RefCell<dyn Any>>, v8::NearHeapLimitCallback)>,
}
/// A single execution context of JavaScript. Corresponds roughly to the "Web
/// Worker" concept in the DOM. A JsRuntime is a Future that can be used with
/// an event loop (Tokio, async_std).
////
/// The JsRuntime future completes when there is an error or when all
/// pending ops have completed.
///
/// Pending ops are created in JavaScript by calling Deno.core.opAsync(), and in Rust
/// by implementing an async function that takes a serde::Deserialize "control argument"
/// and an optional zero copy buffer, each async Op is tied to a Promise in JavaScript.
pub struct JsRuntime {
state: Rc<RefCell<JsRuntimeState>>,
module_map: Option<Rc<RefCell<ModuleMap>>>,
// This is an Option<OwnedIsolate> instead of just OwnedIsolate to workaround
// a safety issue with SnapshotCreator. See JsRuntime::drop.
v8_isolate: Option<v8::OwnedIsolate>,
built_from_snapshot: bool,
allocations: IsolateAllocations,
extensions: Vec<Extension>,
event_loop_middlewares: Vec<Box<OpEventLoopFn>>,
}
pub(crate) struct DynImportModEvaluate {
load_id: ModuleLoadId,
module_id: ModuleId,
promise: v8::Global<v8::Promise>,
module: v8::Global<v8::Module>,
}
pub(crate) struct ModEvaluate {
pub(crate) promise: Option<v8::Global<v8::Promise>>,
pub(crate) has_evaluated: bool,
pub(crate) handled_promise_rejections: Vec<v8::Global<v8::Promise>>,
sender: oneshot::Sender<Result<(), Error>>,
}
pub struct CrossIsolateStore<T>(Arc<Mutex<CrossIsolateStoreInner<T>>>);
struct CrossIsolateStoreInner<T> {
map: HashMap<u32, T>,
last_id: u32,
}
impl<T> CrossIsolateStore<T> {
pub(crate) fn insert(&self, value: T) -> u32 {
let mut store = self.0.lock().unwrap();
let last_id = store.last_id;
store.map.insert(last_id, value);
store.last_id += 1;
last_id
}
pub(crate) fn take(&self, id: u32) -> Option<T> {
let mut store = self.0.lock().unwrap();
store.map.remove(&id)
}
}
impl<T> Default for CrossIsolateStore<T> {
fn default() -> Self {
CrossIsolateStore(Arc::new(Mutex::new(CrossIsolateStoreInner {
map: Default::default(),
last_id: 0,
})))
}
}
impl<T> Clone for CrossIsolateStore<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
pub type SharedArrayBufferStore =
CrossIsolateStore<v8::SharedRef<v8::BackingStore>>;
pub type CompiledWasmModuleStore = CrossIsolateStore<v8::CompiledWasmModule>;
/// Internal state for JsRuntime which is stored in one of v8::Isolate's
/// embedder slots.
pub struct JsRuntimeState {
global_realm: Option<JsRealm>,
pub(crate) js_recv_cb: Option<v8::Global<v8::Function>>,
pub(crate) js_macrotask_cbs: Vec<v8::Global<v8::Function>>,
pub(crate) js_nexttick_cbs: Vec<v8::Global<v8::Function>>,
pub(crate) js_promise_reject_cb: Option<v8::Global<v8::Function>>,
pub(crate) js_format_exception_cb: Option<v8::Global<v8::Function>>,
pub(crate) js_build_custom_error_cb: Option<v8::Global<v8::Function>>,
pub(crate) has_tick_scheduled: bool,
pub(crate) js_wasm_streaming_cb: Option<v8::Global<v8::Function>>,
pub(crate) pending_promise_exceptions:
HashMap<v8::Global<v8::Promise>, v8::Global<v8::Value>>,
pub(crate) pending_dyn_mod_evaluate: Vec<DynImportModEvaluate>,
pub(crate) pending_mod_evaluate: Option<ModEvaluate>,
/// A counter used to delay our dynamic import deadlock detection by one spin
/// of the event loop.
dyn_module_evaluate_idle_counter: u32,
pub(crate) source_map_getter: Option<Box<dyn SourceMapGetter>>,
pub(crate) source_map_cache: SourceMapCache,
pub(crate) pending_ops: FuturesUnordered<PendingOpFuture>,
pub(crate) unrefed_ops: HashSet<i32>,
pub(crate) have_unpolled_ops: bool,
pub(crate) op_state: Rc<RefCell<OpState>>,
#[allow(dead_code)]
// We don't explicitly re-read this prop but need the slice to live alongside the isolate
pub(crate) op_ctxs: Box<[OpCtx]>,
pub(crate) shared_array_buffer_store: Option<SharedArrayBufferStore>,
pub(crate) compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
/// The error that was passed to an `op_dispatch_exception` call.
/// It will be retrieved by `exception_to_err_result` and used as an error
/// instead of any other exceptions.
// TODO(nayeemrmn): This is polled in `exception_to_err_result()` which is
// flimsy. Try to poll it similarly to `pending_promise_exceptions`.
pub(crate) dispatched_exceptions: VecDeque<v8::Global<v8::Value>>,
pub(crate) inspector: Option<Rc<RefCell<JsRuntimeInspector>>>,
waker: AtomicWaker,
}
fn v8_init(
v8_platform: Option<v8::SharedRef<v8::Platform>>,
predictable: bool,
) {
// Include 10MB ICU data file.
#[repr(C, align(16))]
struct IcuData([u8; 10454784]);
static ICU_DATA: IcuData = IcuData(*include_bytes!("icudtl.dat"));
v8::icu::set_common_data_71(&ICU_DATA.0).unwrap();
let flags = concat!(
" --experimental-wasm-threads",
" --wasm-test-streaming",
" --harmony-import-assertions",
" --no-validate-asm",
" --turbo_fast_api_calls",
// This flag prevents "unresolved external reference" panic during
// build, which started happening in V8 10.6
" --noexperimental-async-stack-tagging-api",
" --harmony-change-array-by-copy",
);
if predictable {
v8::V8::set_flags_from_string(&format!(
"{}{}",
flags, " --predictable --random-seed=42"
));
} else {
v8::V8::set_flags_from_string(flags);
}
let v8_platform = v8_platform
.unwrap_or_else(|| v8::new_default_platform(0, false).make_shared());
v8::V8::initialize_platform(v8_platform);
v8::V8::initialize();
}
pub const V8_WRAPPER_TYPE_INDEX: i32 = 0;
pub const V8_WRAPPER_OBJECT_INDEX: i32 = 1;
#[derive(Default)]
pub struct RuntimeOptions {
/// Source map reference for errors.
pub source_map_getter: Option<Box<dyn SourceMapGetter>>,
/// Allows to map error type to a string "class" used to represent
/// error in JavaScript.
pub get_error_class_fn: Option<GetErrorClassFn>,
/// Implementation of `ModuleLoader` which will be
/// called when V8 requests to load ES modules.
///
/// If not provided runtime will error if code being
/// executed tries to load modules.
pub module_loader: Option<Rc<dyn ModuleLoader>>,
/// JsRuntime extensions, not to be confused with ES modules
/// these are sets of ops and other JS code to be initialized.
pub extensions: Vec<Extension>,
/// V8 snapshot that should be loaded on startup.
///
/// Currently can't be used with `will_snapshot`.
pub startup_snapshot: Option<Snapshot>,
/// Prepare runtime to take snapshot of loaded code.
/// The snapshot is determinstic and uses predictable random numbers.
///
/// Currently can't be used with `startup_snapshot`.
pub will_snapshot: bool,
/// Isolate creation parameters.
pub create_params: Option<v8::CreateParams>,
/// V8 platform instance to use. Used when Deno initializes V8
/// (which it only does once), otherwise it's silenty dropped.
pub v8_platform: Option<v8::SharedRef<v8::Platform>>,
/// The store to use for transferring SharedArrayBuffers between isolates.
/// If multiple isolates should have the possibility of sharing
/// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If
/// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be
/// serialized.
pub shared_array_buffer_store: Option<SharedArrayBufferStore>,
/// The store to use for transferring `WebAssembly.Module` objects between
/// isolates.
/// If multiple isolates should have the possibility of sharing
/// `WebAssembly.Module` objects, they should use the same
/// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified,
/// `WebAssembly.Module` objects cannot be serialized.
pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
pub inspector: bool,
}
impl Drop for JsRuntime {
fn drop(&mut self) {
if let Some(v8_isolate) = self.v8_isolate.as_mut() {
Self::drop_state_and_module_map(v8_isolate);
}
}
}
impl JsRuntime {
const STATE_DATA_OFFSET: u32 = 0;
const MODULE_MAP_DATA_OFFSET: u32 = 1;
/// Only constructor, configuration is done through `options`.
pub fn new(mut options: RuntimeOptions) -> Self {
let v8_platform = options.v8_platform.take();
static DENO_INIT: Once = Once::new();
DENO_INIT.call_once(move || v8_init(v8_platform, options.will_snapshot));
let has_startup_snapshot = options.startup_snapshot.is_some();
// Add builtins extension
options
.extensions
.insert(0, crate::ops_builtin::init_builtins());
let ops = Self::collect_ops(&mut options.extensions);
let mut op_state = OpState::new(ops.len());
if let Some(get_error_class_fn) = options.get_error_class_fn {
op_state.get_error_class_fn = get_error_class_fn;
}
let op_state = Rc::new(RefCell::new(op_state));
let align = std::mem::align_of::<usize>();
let layout = std::alloc::Layout::from_size_align(
std::mem::size_of::<*mut v8::OwnedIsolate>(),
align,
)
.unwrap();
assert!(layout.size() > 0);
let isolate_ptr: *mut v8::OwnedIsolate =
// SAFETY: we just asserted that layout has non-0 size.
unsafe { std::alloc::alloc(layout) as *mut _ };
let state_rc = Rc::new(RefCell::new(JsRuntimeState {
pending_promise_exceptions: HashMap::new(),
pending_dyn_mod_evaluate: vec![],
pending_mod_evaluate: None,
dyn_module_evaluate_idle_counter: 0,
js_recv_cb: None,
js_macrotask_cbs: vec![],
js_nexttick_cbs: vec![],
js_promise_reject_cb: None,
js_format_exception_cb: None,
js_build_custom_error_cb: None,
has_tick_scheduled: false,
js_wasm_streaming_cb: None,
source_map_getter: options.source_map_getter,
source_map_cache: Default::default(),
pending_ops: FuturesUnordered::new(),
unrefed_ops: HashSet::new(),
shared_array_buffer_store: options.shared_array_buffer_store,
compiled_wasm_module_store: options.compiled_wasm_module_store,
op_state: op_state.clone(),
waker: AtomicWaker::new(),
have_unpolled_ops: false,
dispatched_exceptions: Default::default(),
// Some fields are initialized later after isolate is created
inspector: None,
op_ctxs: vec![].into_boxed_slice(),
global_realm: None,
}));
let weak = Rc::downgrade(&state_rc);
let op_ctxs = ops
.into_iter()
.enumerate()
.map(|(id, decl)| OpCtx {
id,
state: op_state.clone(),
runtime_state: weak.clone(),
decl,
})
.collect::<Vec<_>>()
.into_boxed_slice();
let refs = bindings::external_references(&op_ctxs, !options.will_snapshot);
// V8 takes ownership of external_references.
let refs: &'static v8::ExternalReferences = Box::leak(Box::new(refs));
let global_context;
let mut isolate = if options.will_snapshot {
// TODO(ry) Support loading snapshots before snapshotting.
assert!(options.startup_snapshot.is_none());
let snapshot_creator = v8::Isolate::snapshot_creator(Some(refs));
let mut isolate = JsRuntime::setup_isolate(snapshot_creator);
{
// SAFETY: this is first use of `isolate_ptr` so we are sure we're
// not overwriting an existing pointer.
isolate = unsafe {
isolate_ptr.write(isolate);
isolate_ptr.read()
};
let scope = &mut v8::HandleScope::new(&mut isolate);
let context = bindings::initialize_context(scope, &op_ctxs, false);
global_context = v8::Global::new(scope, context);
scope.set_default_context(context);
}
isolate
} else {
let mut params = options
.create_params
.take()
.unwrap_or_else(|| {
v8::CreateParams::default().embedder_wrapper_type_info_offsets(
V8_WRAPPER_TYPE_INDEX,
V8_WRAPPER_OBJECT_INDEX,
)
})
.external_references(&**refs);
let snapshot_loaded = if let Some(snapshot) = options.startup_snapshot {
params = match snapshot {
Snapshot::Static(data) => params.snapshot_blob(data),
Snapshot::JustCreated(data) => params.snapshot_blob(data),
Snapshot::Boxed(data) => params.snapshot_blob(data),
};
true
} else {
false
};
let isolate = v8::Isolate::new(params);
let mut isolate = JsRuntime::setup_isolate(isolate);
{
// SAFETY: this is first use of `isolate_ptr` so we are sure we're
// not overwriting an existing pointer.
isolate = unsafe {
isolate_ptr.write(isolate);
isolate_ptr.read()
};
let scope = &mut v8::HandleScope::new(&mut isolate);
let context =
bindings::initialize_context(scope, &op_ctxs, snapshot_loaded);
global_context = v8::Global::new(scope, context);
}
isolate
};
op_state.borrow_mut().put(isolate_ptr);
let inspector = if options.inspector {
Some(JsRuntimeInspector::new(
&mut isolate,
global_context.clone(),
))
} else {
None
};
let loader = options
.module_loader
.unwrap_or_else(|| Rc::new(NoopModuleLoader));
{
let mut state = state_rc.borrow_mut();
state.global_realm = Some(JsRealm(global_context));
state.op_ctxs = op_ctxs;
state.inspector = inspector;
}
isolate.set_data(
Self::STATE_DATA_OFFSET,
Rc::into_raw(state_rc.clone()) as *mut c_void,
);
let module_map_rc = Rc::new(RefCell::new(ModuleMap::new(loader, op_state)));
isolate.set_data(
Self::MODULE_MAP_DATA_OFFSET,
Rc::into_raw(module_map_rc.clone()) as *mut c_void,
);
let mut js_runtime = Self {
v8_isolate: Some(isolate),
built_from_snapshot: has_startup_snapshot,
allocations: IsolateAllocations::default(),
event_loop_middlewares: Vec::with_capacity(options.extensions.len()),
extensions: options.extensions,
state: state_rc,
module_map: Some(module_map_rc),
};
// Init resources and ops before extensions to make sure they are
// available during the initialization process.
js_runtime.init_extension_ops().unwrap();
// TODO(@AaronO): diff extensions inited in snapshot and those provided
// for now we assume that snapshot and extensions always match
if !has_startup_snapshot {
let realm = js_runtime.global_realm();
js_runtime.init_extension_js(&realm).unwrap();
}
// Init callbacks (opresolve)
js_runtime.init_cbs();
js_runtime
}
fn drop_state_and_module_map(v8_isolate: &mut OwnedIsolate) {
let state_ptr = v8_isolate.get_data(Self::STATE_DATA_OFFSET);
let state_rc =
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
// the runtime.
unsafe { Rc::from_raw(state_ptr as *const RefCell<JsRuntimeState>) };
drop(state_rc);
let module_map_ptr = v8_isolate.get_data(Self::MODULE_MAP_DATA_OFFSET);
let module_map_rc =
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
// the runtime.
unsafe { Rc::from_raw(module_map_ptr as *const RefCell<ModuleMap>) };
drop(module_map_rc);
}
#[inline]
fn get_module_map(&mut self) -> &Rc<RefCell<ModuleMap>> {
self.module_map.as_ref().unwrap()
}
#[inline]
pub fn global_context(&mut self) -> v8::Global<v8::Context> {
self.global_realm().0
}
#[inline]
pub fn v8_isolate(&mut self) -> &mut v8::OwnedIsolate {
self.v8_isolate.as_mut().unwrap()
}
#[inline]
pub fn inspector(&mut self) -> Rc<RefCell<JsRuntimeInspector>> {
self.state.borrow().inspector()
}
#[inline]
pub fn global_realm(&mut self) -> JsRealm {
let state = self.state.borrow();
state.global_realm.clone().unwrap()
}
/// Creates a new realm (V8 context) in this JS execution context,
/// pre-initialized with all of the extensions that were passed in
/// [`RuntimeOptions::extensions`] when the [`JsRuntime`] was constructed.
///
/// If the [`JsRuntime`] was not built from a snapshot (see
/// [`RuntimeOptions::startup_snapshot`]), the JS code for the extensions will
/// be run in the call to this method. In contrast, if there is a snapshot,
/// that will be used instead, and the extensions' initialization will come
/// "for free".
pub fn create_realm(&mut self) -> Result<JsRealm, Error> {
let realm = {
// SAFETY: Having the scope tied to self's lifetime makes it impossible to
// reference self.ops while the scope is alive. Here we turn it into an
// unbound lifetime, which is sound because 1. it only lives until the end
// of this block, and 2. the HandleScope only has access to the isolate,
// and nothing else we're accessing from self does.
let scope = &mut v8::HandleScope::new(unsafe {
&mut *(self.v8_isolate() as *mut v8::OwnedIsolate)
});
let context = bindings::initialize_context(
scope,
&self.state.borrow().op_ctxs,
self.built_from_snapshot,
);
JsRealm::new(v8::Global::new(scope, context))
};
if !self.built_from_snapshot {
self.init_extension_js(&realm)?;
}
Ok(realm)
}
#[inline]
pub fn handle_scope(&mut self) -> v8::HandleScope {
self.global_realm().handle_scope(self.v8_isolate())
}
fn setup_isolate(mut isolate: v8::OwnedIsolate) -> v8::OwnedIsolate {
isolate.set_capture_stack_trace_for_uncaught_exceptions(true, 10);
isolate.set_promise_reject_callback(bindings::promise_reject_callback);
isolate.set_host_initialize_import_meta_object_callback(
bindings::host_initialize_import_meta_object_callback,
);
isolate.set_host_import_module_dynamically_callback(
bindings::host_import_module_dynamically_callback,
);
isolate.set_wasm_async_resolve_promise_callback(
bindings::wasm_async_resolve_promise_callback,
);
isolate
}
pub(crate) fn state(isolate: &v8::Isolate) -> Rc<RefCell<JsRuntimeState>> {
let state_ptr = isolate.get_data(Self::STATE_DATA_OFFSET);
let state_rc =
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
// the runtime.
unsafe { Rc::from_raw(state_ptr as *const RefCell<JsRuntimeState>) };
let state = state_rc.clone();
Rc::into_raw(state_rc);
state
}
pub(crate) fn module_map(isolate: &v8::Isolate) -> Rc<RefCell<ModuleMap>> {
let module_map_ptr = isolate.get_data(Self::MODULE_MAP_DATA_OFFSET);
let module_map_rc =
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
// the runtime.
unsafe { Rc::from_raw(module_map_ptr as *const RefCell<ModuleMap>) };
let module_map = module_map_rc.clone();
Rc::into_raw(module_map_rc);
module_map
}
/// Initializes JS of provided Extensions in the given realm
fn init_extension_js(&mut self, realm: &JsRealm) -> Result<(), Error> {
// Take extensions to avoid double-borrow
let mut extensions: Vec<Extension> = std::mem::take(&mut self.extensions);
for m in extensions.iter_mut() {
let js_files = m.init_js();
for (filename, source) in js_files {
// TODO(@AaronO): use JsRuntime::execute_static() here to move src off heap
realm.execute_script(self.v8_isolate(), filename, source)?;
}
}
// Restore extensions
self.extensions = extensions;
Ok(())
}
/// Collects ops from extensions & applies middleware
fn collect_ops(extensions: &mut [Extension]) -> Vec<OpDecl> {
// Middleware
let middleware: Vec<Box<OpMiddlewareFn>> = extensions
.iter_mut()
.filter_map(|e| e.init_middleware())
.collect();
// macroware wraps an opfn in all the middleware
let macroware = move |d| middleware.iter().fold(d, |d, m| m(d));
// Flatten ops, apply middlware & override disabled ops
extensions
.iter_mut()
.filter_map(|e| e.init_ops())
.flatten()
.map(|d| OpDecl {
name: d.name,
..macroware(d)
})
.map(|op| match op.enabled {
true => op,
false => OpDecl {
v8_fn_ptr: match op.is_async {
true => op_void_async::v8_fn_ptr(),
false => op_void_sync::v8_fn_ptr(),
},
..op
},
})
.collect()
}
/// Initializes ops of provided Extensions
fn init_extension_ops(&mut self) -> Result<(), Error> {
let op_state = self.op_state();
// Take extensions to avoid double-borrow
let mut extensions: Vec<Extension> = std::mem::take(&mut self.extensions);
// Setup state
for e in extensions.iter_mut() {
// ops are already registered during in bindings::initialize_context();
e.init_state(&mut op_state.borrow_mut())?;
// Setup event-loop middleware
if let Some(middleware) = e.init_event_loop_middleware() {
self.event_loop_middlewares.push(middleware);
}
}
// Restore extensions
self.extensions = extensions;
Ok(())
}
/// Grab a Global handle to a v8 value returned by the expression
pub(crate) fn grab<'s, T>(
scope: &mut v8::HandleScope<'s>,
root: v8::Local<'s, v8::Value>,
path: &str,
) -> Option<v8::Local<'s, T>>
where
v8::Local<'s, T>: TryFrom<v8::Local<'s, v8::Value>, Error = v8::DataError>,
{
path
.split('.')
.fold(Some(root), |p, k| {
let p = v8::Local::<v8::Object>::try_from(p?).ok()?;
let k = v8::String::new(scope, k)?;
p.get(scope, k.into())
})?
.try_into()
.ok()
}
pub fn grab_global<'s, T>(
scope: &mut v8::HandleScope<'s>,
path: &str,
) -> Option<v8::Local<'s, T>>
where
v8::Local<'s, T>: TryFrom<v8::Local<'s, v8::Value>, Error = v8::DataError>,
{
let context = scope.get_current_context();
let global = context.global(scope);
Self::grab(scope, global.into(), path)
}
pub(crate) fn ensure_objs<'s>(
scope: &mut v8::HandleScope<'s>,
root: v8::Local<'s, v8::Object>,
path: &str,
) -> Option<v8::Local<'s, v8::Object>> {
path.split('.').fold(Some(root), |p, k| {
let k = v8::String::new(scope, k)?.into();
match p?.get(scope, k) {
Some(v) if !v.is_null_or_undefined() => v.try_into().ok(),
_ => {
let o = v8::Object::new(scope);
p?.set(scope, k, o.into());
Some(o)
}
}
})
}
/// Grabs a reference to core.js' opresolve & syncOpsCache()
fn init_cbs(&mut self) {
let scope = &mut self.handle_scope();
let recv_cb =
Self::grab_global::<v8::Function>(scope, "Deno.core.opresolve").unwrap();
let recv_cb = v8::Global::new(scope, recv_cb);
let build_custom_error_cb =
Self::grab_global::<v8::Function>(scope, "Deno.core.buildCustomError")
.expect("Deno.core.buildCustomError is undefined in the realm");
let build_custom_error_cb = v8::Global::new(scope, build_custom_error_cb);
// Put global handles in state
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
state.js_recv_cb.replace(recv_cb);
state
.js_build_custom_error_cb
.replace(build_custom_error_cb);
}
/// Returns the runtime's op state, which can be used to maintain ops
/// and access resources between op calls.
pub fn op_state(&mut self) -> Rc<RefCell<OpState>> {
let state = self.state.borrow();
state.op_state.clone()
}
/// Executes traditional JavaScript code (traditional = not ES modules).
///
/// The execution takes place on the current global context, so it is possible
/// to maintain local JS state and invoke this method multiple times.
///
/// `name` can be a filepath or any other string, eg.
///
/// - "/some/file/path.js"
/// - "<anon>"
/// - "[native code]"
///
/// The same `name` value can be used for multiple executions.
///
/// `Error` can usually be downcast to `JsError`.
pub fn execute_script(
&mut self,
name: &str,
source_code: &str,
) -> Result<v8::Global<v8::Value>, Error> {
self
.global_realm()
.execute_script(self.v8_isolate(), name, source_code)
}
/// Takes a snapshot. The isolate should have been created with will_snapshot
/// set to true.
///
/// `Error` can usually be downcast to `JsError`.
pub fn snapshot(mut self) -> v8::StartupData {
// Nuke Deno.core.ops.* to avoid ExternalReference snapshotting issues
// TODO(@AaronO): make ops stable across snapshots
{
let scope = &mut self.handle_scope();
let o = Self::grab_global::<v8::Object>(scope, "Deno.core.ops").unwrap();
let names = o.get_own_property_names(scope, Default::default()).unwrap();
for i in 0..names.length() {
let key = names.get_index(scope, i).unwrap();
o.delete(scope, key);
}
}
self.state.borrow_mut().global_realm.take();
self.state.borrow_mut().inspector.take();
// Drop existing ModuleMap to drop v8::Global handles
{
self.module_map.take();
let v8_isolate = self.v8_isolate();
Self::drop_state_and_module_map(v8_isolate);
}
// Drop other v8::Global handles before snapshotting
{
let mut state = self.state.borrow_mut();
std::mem::take(&mut state.js_recv_cb);
std::mem::take(&mut state.js_promise_reject_cb);
std::mem::take(&mut state.js_format_exception_cb);
std::mem::take(&mut state.js_wasm_streaming_cb);
std::mem::take(&mut state.js_build_custom_error_cb);
state.js_macrotask_cbs.clear();
state.js_nexttick_cbs.clear();
}
let snapshot_creator = self.v8_isolate.take().unwrap();
snapshot_creator
.create_blob(v8::FunctionCodeHandling::Keep)
.unwrap()
}
/// Returns the namespace object of a module.
///
/// This is only available after module evaluation has completed.
/// This function panics if module has not been instantiated.
pub fn get_module_namespace(
&mut self,
module_id: ModuleId,
) -> Result<v8::Global<v8::Object>, Error> {
let module_map_rc = Self::module_map(self.v8_isolate());
let module_handle = module_map_rc
.borrow()
.get_handle(module_id)
.expect("ModuleInfo not found");
let scope = &mut self.handle_scope();
let module = module_handle.open(scope);
if module.get_status() == v8::ModuleStatus::Errored {
let exception = module.get_exception();
return exception_to_err_result(scope, exception, false);
}
assert!(matches!(
module.get_status(),
v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated
));
let module_namespace: v8::Local<v8::Object> =
v8::Local::try_from(module.get_module_namespace())
.map_err(|err: v8::DataError| generic_error(err.to_string()))?;
Ok(v8::Global::new(scope, module_namespace))
}
/// Registers a callback on the isolate when the memory limits are approached.
/// Use this to prevent V8 from crashing the process when reaching the limit.
///
/// Calls the closure with the current heap limit and the initial heap limit.
/// The return value of the closure is set as the new limit.
pub fn add_near_heap_limit_callback<C>(&mut self, cb: C)
where
C: FnMut(usize, usize) -> usize + 'static,
{
let boxed_cb = Box::new(RefCell::new(cb));
let data = boxed_cb.as_ptr() as *mut c_void;
let prev = self
.allocations
.near_heap_limit_callback_data
.replace((boxed_cb, near_heap_limit_callback::<C>));
if let Some((_, prev_cb)) = prev {
self
.v8_isolate()
.remove_near_heap_limit_callback(prev_cb, 0);
}
self
.v8_isolate()
.add_near_heap_limit_callback(near_heap_limit_callback::<C>, data);
}
pub fn remove_near_heap_limit_callback(&mut self, heap_limit: usize) {
if let Some((_, cb)) = self.allocations.near_heap_limit_callback_data.take()
{
self
.v8_isolate()
.remove_near_heap_limit_callback(cb, heap_limit);
}
}
fn pump_v8_message_loop(&mut self) -> Result<(), Error> {
let scope = &mut self.handle_scope();
while v8::Platform::pump_message_loop(
&v8::V8::get_current_platform(),
scope,
false, // don't block if there are no tasks
) {
// do nothing
}
let tc_scope = &mut v8::TryCatch::new(scope);
tc_scope.perform_microtask_checkpoint();
match tc_scope.exception() {
None => Ok(()),
Some(exception) => exception_to_err_result(tc_scope, exception, false),
}
}
pub fn maybe_init_inspector(&mut self) {
if self.state.borrow().inspector.is_some() {
return;
}
let mut state = self.state.borrow_mut();
state.inspector = Some(JsRuntimeInspector::new(
self.v8_isolate.as_mut().unwrap(),
state.global_realm.clone().unwrap().0,
));
}
pub fn poll_value(
&mut self,
global: &v8::Global<v8::Value>,
cx: &mut Context,
) -> Poll<Result<v8::Global<v8::Value>, Error>> {
let state = self.poll_event_loop(cx, false);
let mut scope = self.handle_scope();
let local = v8::Local::<v8::Value>::new(&mut scope, global);
if let Ok(promise) = v8::Local::<v8::Promise>::try_from(local) {
match promise.state() {
v8::PromiseState::Pending => match state {
Poll::Ready(Ok(_)) => {
let msg = "Promise resolution is still pending but the event loop has already resolved.";
Poll::Ready(Err(generic_error(msg)))
}
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
},
v8::PromiseState::Fulfilled => {
let value = promise.result(&mut scope);
let value_handle = v8::Global::new(&mut scope, value);
Poll::Ready(Ok(value_handle))
}
v8::PromiseState::Rejected => {
let exception = promise.result(&mut scope);
Poll::Ready(exception_to_err_result(&mut scope, exception, false))
}
}
} else {
let value_handle = v8::Global::new(&mut scope, local);
Poll::Ready(Ok(value_handle))
}
}
/// Waits for the given value to resolve while polling the event loop.
///
/// This future resolves when either the value is resolved or the event loop runs to
/// completion.
pub async fn resolve_value(
&mut self,
global: v8::Global<v8::Value>,
) -> Result<v8::Global<v8::Value>, Error> {
poll_fn(|cx| self.poll_value(&global, cx)).await
}
/// Runs event loop to completion
///
/// This future resolves when:
/// - there are no more pending dynamic imports
/// - there are no more pending ops
/// - there are no more active inspector sessions (only if `wait_for_inspector` is set to true)
pub async fn run_event_loop(
&mut self,
wait_for_inspector: bool,
) -> Result<(), Error> {
poll_fn(|cx| self.poll_event_loop(cx, wait_for_inspector)).await
}
/// Runs a single tick of event loop
///
/// If `wait_for_inspector` is set to true event loop
/// will return `Poll::Pending` if there are active inspector sessions.
pub fn poll_event_loop(
&mut self,
cx: &mut Context,
wait_for_inspector: bool,
) -> Poll<Result<(), Error>> {
let has_inspector: bool;
{
let state = self.state.borrow();
has_inspector = state.inspector.is_some();
state.waker.register(cx.waker());
}