-
Notifications
You must be signed in to change notification settings - Fork 66
/
jsruntime.rs
2437 lines (2183 loc) · 79.4 KB
/
jsruntime.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-2023 the Deno authors. All rights reserved. MIT license.
use super::bindings;
use super::jsrealm::JsRealmInner;
use super::snapshot_util;
use crate::error::exception_to_err_result;
use crate::error::generic_error;
use crate::error::to_v8_type_error;
use crate::error::GetErrorClassFn;
use crate::error::JsError;
use crate::extensions::EventLoopMiddlewareFn;
use crate::extensions::GlobalObjectMiddlewareFn;
use crate::extensions::GlobalTemplateMiddlewareFn;
use crate::extensions::OpDecl;
use crate::include_js_files;
use crate::inspector::JsRuntimeInspector;
use crate::module_specifier::ModuleSpecifier;
use crate::modules::AssertedModuleType;
use crate::modules::ExtModuleLoader;
use crate::modules::ExtModuleLoaderCb;
use crate::modules::ModuleCode;
use crate::modules::ModuleError;
use crate::modules::ModuleId;
use crate::modules::ModuleLoadId;
use crate::modules::ModuleLoader;
use crate::modules::ModuleMap;
use crate::ops::*;
use crate::runtime::ContextState;
use crate::runtime::JsRealm;
use crate::source_map::SourceMapCache;
use crate::source_map::SourceMapGetter;
use crate::Extension;
use crate::ExtensionFileSource;
use crate::NoopModuleLoader;
use crate::OpMiddlewareFn;
use crate::OpResult;
use crate::OpState;
use crate::V8_WRAPPER_OBJECT_INDEX;
use crate::V8_WRAPPER_TYPE_INDEX;
use anyhow::Context as AnyhowContext;
use anyhow::Error;
use futures::channel::oneshot;
use futures::future::poll_fn;
use futures::stream::StreamExt;
use once_cell::sync::Lazy;
use smallvec::SmallVec;
use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::ops::DerefMut;
use std::option::Option;
use std::rc::Rc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Once;
use std::task::Context;
use std::task::Poll;
const STATE_DATA_OFFSET: u32 = 0;
pub enum Snapshot {
Static(&'static [u8]),
JustCreated(v8::StartupData),
Boxed(Box<[u8]>),
}
/// Objects that need to live as long as the isolate
#[derive(Default)]
pub(crate) struct IsolateAllocations {
pub(crate) near_heap_limit_callback_data:
Option<(Box<RefCell<dyn Any>>, v8::NearHeapLimitCallback)>,
}
/// ManuallyDrop<Rc<...>> is clone, but it returns a ManuallyDrop<Rc<...>> which is a massive
/// memory-leak footgun.
pub(crate) struct ManuallyDropRc<T>(ManuallyDrop<Rc<T>>);
impl<T> ManuallyDropRc<T> {
pub fn clone(&self) -> Rc<T> {
self.0.deref().clone()
}
}
impl<T> Deref for ManuallyDropRc<T> {
type Target = Rc<T>;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl<T> DerefMut for ManuallyDropRc<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
/// This struct contains the [`JsRuntimeState`] and [`v8::OwnedIsolate`] that are required
/// to do an orderly shutdown of V8. We keep these in a separate struct to allow us to control
/// the destruction more closely, as snapshots require the isolate to be destroyed by the
/// snapshot process, not the destructor.
///
/// The way rusty_v8 works w/snapshots is that the [`v8::OwnedIsolate`] gets consumed by a
/// [`v8::snapshot::SnapshotCreator`] that is stored in its annex. It's a bit awkward, because this
/// means we cannot let it drop (because we don't have it after a snapshot). On top of that, we have
/// to consume it in the snapshot creator because otherwise it panics.
///
/// This inner struct allows us to let the outer JsRuntime drop normally without a Drop impl, while we
/// control dropping more closely here using ManuallyDrop.
pub(crate) struct InnerIsolateState {
will_snapshot: bool,
pub(crate) state: ManuallyDropRc<RefCell<JsRuntimeState>>,
v8_isolate: ManuallyDrop<v8::OwnedIsolate>,
}
impl InnerIsolateState {
/// Clean out the opstate and take the inspector to prevent the inspector from getting destroyed
/// after we've torn down the contexts. If the inspector is not correctly torn down, random crashes
/// happen in tests (and possibly for users using the inspector).
pub fn prepare_for_cleanup(&mut self) {
let mut state = self.state.borrow_mut();
let inspector = state.inspector.take();
state.op_state.borrow_mut().clear();
if let Some(inspector) = inspector {
assert_eq!(
Rc::strong_count(&inspector),
1,
"The inspector must be dropped before the runtime"
);
}
}
pub fn cleanup(&mut self) {
self.prepare_for_cleanup();
let state_ptr = self.v8_isolate.get_data(STATE_DATA_OFFSET);
// 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>) };
self.state.borrow_mut().destroy_all_realms();
debug_assert_eq!(Rc::strong_count(&self.state), 1);
}
pub fn prepare_for_snapshot(mut self) -> v8::OwnedIsolate {
self.cleanup();
// SAFETY: We're copying out of self and then immediately forgetting self
let (state, isolate) = unsafe {
(
ManuallyDrop::take(&mut self.state.0),
ManuallyDrop::take(&mut self.v8_isolate),
)
};
std::mem::forget(self);
drop(state);
isolate
}
}
impl Drop for InnerIsolateState {
fn drop(&mut self) {
self.cleanup();
// SAFETY: We gotta drop these
unsafe {
ManuallyDrop::drop(&mut self.state.0);
if self.will_snapshot {
// Create the snapshot and just drop it.
eprintln!("WARNING: v8::OwnedIsolate for snapshot was leaked");
} else {
ManuallyDrop::drop(&mut self.v8_isolate);
}
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum InitMode {
/// We have no snapshot -- this is a pristine context.
New,
/// We are using a snapshot, thus certain initialization steps are skipped.
FromSnapshot,
}
impl InitMode {
fn from_options(options: &RuntimeOptions) -> Self {
match options.startup_snapshot {
None => Self::New,
Some(_) => Self::FromSnapshot,
}
}
}
pub(crate) static BUILTIN_SOURCES: Lazy<Vec<ExtensionFileSource>> =
Lazy::new(|| {
include_js_files!(
core
"00_primordials.js",
"01_core.js",
"02_error.js",
)
});
/// A single execution context of JavaScript. Corresponds roughly to the "Web
/// Worker" concept in the DOM.
////
/// The JsRuntime future completes when there is an error or when all
/// pending ops have completed.
///
/// Use [`JsRuntimeForSnapshot`] to be able to create a snapshot.
pub struct JsRuntime {
pub(crate) inner: InnerIsolateState,
pub(crate) allocations: IsolateAllocations,
extensions: Vec<Extension>,
event_loop_middlewares: Vec<Box<EventLoopMiddlewareFn>>,
global_template_middlewares: Vec<Box<GlobalTemplateMiddlewareFn>>,
global_object_middlewares: Vec<Box<GlobalObjectMiddlewareFn>>,
init_mode: InitMode,
// Marks if this is considered the top-level runtime. Used only by inspector.
is_main_runtime: bool,
}
/// The runtime type used for snapshot creation.
pub struct JsRuntimeForSnapshot(JsRuntime);
impl Deref for JsRuntimeForSnapshot {
type Target = JsRuntime;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for JsRuntimeForSnapshot {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
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 {
main_realm: Option<JsRealm>,
known_realms: Vec<JsRealmInner>,
pub(crate) has_tick_scheduled: bool,
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<Rc<Box<dyn SourceMapGetter>>>,
pub(crate) source_map_cache: Rc<RefCell<SourceMapCache>>,
pub(crate) op_state: Rc<RefCell<OpState>>,
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_rejections`.
pub(crate) dispatched_exception: Option<v8::Global<v8::Value>>,
pub(crate) inspector: Option<Rc<RefCell<JsRuntimeInspector>>>,
}
impl JsRuntimeState {
pub(crate) fn destroy_all_realms(&mut self) {
self.main_realm.take();
for realm in self.known_realms.drain(..) {
realm.destroy()
}
}
pub(crate) fn remove_realm(
&mut self,
realm_context: &Rc<v8::Global<v8::Context>>,
) {
self
.known_realms
.retain(|realm| !realm.is_same(realm_context));
}
}
fn v8_init(
v8_platform: Option<v8::SharedRef<v8::Platform>>,
predictable: bool,
expose_natives: bool,
) {
// Include 10MB ICU data file.
#[repr(C, align(16))]
struct IcuData([u8; 10541264]);
static ICU_DATA: IcuData = IcuData(*include_bytes!("icudtl.dat"));
v8::icu::set_common_data_72(&ICU_DATA.0).unwrap();
let base_flags = concat!(
" --wasm-test-streaming",
" --harmony-import-assertions",
" --no-validate-asm",
" --turbo_fast_api_calls",
" --harmony-change-array-by-copy",
);
let predictable_flags = "--predictable --random-seed=42";
let expose_natives_flags = "--expose_gc --allow_natives_syntax";
#[allow(clippy::useless_format)]
let flags = match (predictable, expose_natives) {
(false, false) => format!("{base_flags}"),
(true, false) => format!("{base_flags} {predictable_flags}"),
(false, true) => format!("{base_flags} {expose_natives_flags}"),
(true, true) => {
format!("{base_flags} {predictable_flags} {expose_natives_flags}")
}
};
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();
}
#[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.
/// Only ops registered by extensions will be initialized. If you need
/// to execute JS code from extensions, pass source files in `js` or `esm`
/// option on `ExtensionBuilder`.
///
/// If you are creating a runtime from a snapshot take care not to include
/// JavaScript sources in the extensions.
pub extensions: Vec<Extension>,
/// If provided, the module map will be cleared and left only with the specifiers
/// in this list, with the new names provided. If not provided, the module map is
/// left intact.
pub preserve_snapshotted_modules: Option<&'static [&'static str]>,
/// V8 snapshot that should be loaded on startup.
pub startup_snapshot: Option<Snapshot>,
/// 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 silently 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>,
/// Start inspector instance to allow debuggers to connect.
pub inspector: bool,
/// Describe if this is the main runtime instance, used by debuggers in some
/// situation - like disconnecting when program finishes running.
pub is_main: bool,
#[cfg(any(test, feature = "unsafe_runtime_options"))]
/// Should this isolate expose the v8 natives (eg: %OptimizeFunctionOnNextCall) and
/// GC control functions (`gc()`)? WARNING: This should not be used for production code as
/// this may expose the runtime to security vulnerabilities.
pub unsafe_expose_natives_and_gc: bool,
}
impl RuntimeOptions {
#[cfg(any(test, feature = "unsafe_runtime_options"))]
fn unsafe_expose_natives_and_gc(&self) -> bool {
self.unsafe_expose_natives_and_gc
}
#[cfg(not(any(test, feature = "unsafe_runtime_options")))]
fn unsafe_expose_natives_and_gc(&self) -> bool {
false
}
}
#[derive(Default)]
pub struct RuntimeSnapshotOptions {
/// An optional callback that will be called for each module that is loaded
/// during snapshotting. This callback can be used to transpile source on the
/// fly, during snapshotting, eg. to transpile TypeScript to JavaScript.
pub snapshot_module_load_cb: Option<ExtModuleLoaderCb>,
}
#[derive(Default)]
pub struct CreateRealmOptions {
/// Implementation of `ModuleLoader` which will be
/// called when V8 requests to load ES modules in the realm.
///
/// If not provided, there will be an error if code being
/// executed tries to load modules from the realm.
pub module_loader: Option<Rc<dyn ModuleLoader>>,
}
impl JsRuntime {
/// Only constructor, configuration is done through `options`.
pub fn new(mut options: RuntimeOptions) -> JsRuntime {
JsRuntime::init_v8(
options.v8_platform.take(),
cfg!(test),
options.unsafe_expose_natives_and_gc(),
);
JsRuntime::new_inner(options, false, None)
}
pub(crate) fn state_from(
isolate: &v8::Isolate,
) -> Rc<RefCell<JsRuntimeState>> {
let state_ptr = isolate.get_data(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();
std::mem::forget(state_rc);
state
}
/// Returns the `OpState` associated with the passed `Isolate`.
pub fn op_state_from(isolate: &v8::Isolate) -> Rc<RefCell<OpState>> {
let state = Self::state_from(isolate);
let state = state.borrow();
state.op_state.clone()
}
pub(crate) fn event_loop_pending_state_from_scope(
scope: &mut v8::HandleScope,
) -> EventLoopPendingState {
let state = JsRuntime::state_from(scope);
let module_map = JsRealm::module_map_from(scope);
let state = EventLoopPendingState::new(
scope,
&mut state.borrow_mut(),
&module_map.borrow(),
);
state
}
fn init_v8(
v8_platform: Option<v8::SharedRef<v8::Platform>>,
predictable: bool,
expose_natives: bool,
) {
static DENO_INIT: Once = Once::new();
static DENO_PREDICTABLE: AtomicBool = AtomicBool::new(false);
static DENO_PREDICTABLE_SET: AtomicBool = AtomicBool::new(false);
if DENO_PREDICTABLE_SET.load(Ordering::SeqCst) {
let current = DENO_PREDICTABLE.load(Ordering::SeqCst);
assert_eq!(current, predictable, "V8 may only be initialized once in either snapshotting or non-snapshotting mode. Either snapshotting or non-snapshotting mode may be used in a single process, not both.");
DENO_PREDICTABLE_SET.store(true, Ordering::SeqCst);
DENO_PREDICTABLE.store(predictable, Ordering::SeqCst);
}
DENO_INIT
.call_once(move || v8_init(v8_platform, predictable, expose_natives));
}
fn new_inner(
mut options: RuntimeOptions,
will_snapshot: bool,
maybe_load_callback: Option<ExtModuleLoaderCb>,
) -> JsRuntime {
let init_mode = InitMode::from_options(&options);
let (op_state, ops) = Self::create_opstate(&mut options);
let op_state = Rc::new(RefCell::new(op_state));
// Collect event-loop middleware, global template middleware, global object
// middleware, and additional ExternalReferences from extensions.
let mut event_loop_middlewares =
Vec::with_capacity(options.extensions.len());
let mut global_template_middlewares =
Vec::with_capacity(options.extensions.len());
let mut global_object_middlewares =
Vec::with_capacity(options.extensions.len());
let mut additional_references =
Vec::with_capacity(options.extensions.len());
for extension in &mut options.extensions {
if let Some(middleware) = extension.init_event_loop_middleware() {
event_loop_middlewares.push(middleware);
}
if let Some(middleware) = extension.init_global_template_middleware() {
global_template_middlewares.push(middleware);
}
if let Some(middleware) = extension.init_global_object_middleware() {
global_object_middlewares.push(middleware);
}
if let Some(ext_refs) = extension.init_external_references() {
additional_references.extend_from_slice(&ext_refs);
}
}
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_dyn_mod_evaluate: vec![],
pending_mod_evaluate: None,
dyn_module_evaluate_idle_counter: 0,
has_tick_scheduled: false,
source_map_getter: options.source_map_getter.map(Rc::new),
source_map_cache: Default::default(),
shared_array_buffer_store: options.shared_array_buffer_store,
compiled_wasm_module_store: options.compiled_wasm_module_store,
op_state: op_state.clone(),
dispatched_exception: None,
// Some fields are initialized later after isolate is created
inspector: None,
main_realm: None,
known_realms: Vec::with_capacity(1),
}));
let weak = Rc::downgrade(&state_rc);
let context_state = Rc::new(RefCell::new(ContextState::default()));
let op_ctxs = ops
.into_iter()
.enumerate()
.map(|(id, decl)| {
OpCtx::new(
id as u16,
context_state.clone(),
Rc::new(decl),
op_state.clone(),
weak.clone(),
)
})
.collect::<Vec<_>>()
.into_boxed_slice();
context_state.borrow_mut().op_ctxs = op_ctxs;
context_state.borrow_mut().isolate = Some(isolate_ptr);
let refs = bindings::external_references(
&context_state.borrow().op_ctxs,
&additional_references,
);
// V8 takes ownership of external_references.
let refs: &'static v8::ExternalReferences = Box::leak(Box::new(refs));
let mut isolate = if will_snapshot {
snapshot_util::create_snapshot_creator(
refs,
options.startup_snapshot.take(),
)
} else {
let mut params = options
.create_params
.take()
.unwrap_or_default()
.embedder_wrapper_type_info_offsets(
V8_WRAPPER_TYPE_INDEX,
V8_WRAPPER_OBJECT_INDEX,
)
.external_references(&**refs);
if let Some(snapshot) = options.startup_snapshot.take() {
params = match snapshot {
Snapshot::Static(data) => params.snapshot_blob(data),
Snapshot::JustCreated(data) => params.snapshot_blob(data),
Snapshot::Boxed(data) => params.snapshot_blob(data),
};
}
v8::Isolate::new(params)
};
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,
);
let (main_context, snapshotted_data) = {
let scope = &mut v8::HandleScope::new(&mut isolate);
let context = create_context(
scope,
&global_template_middlewares,
&global_object_middlewares,
);
// Get module map data from the snapshot
let snapshotted_data = if init_mode == InitMode::FromSnapshot {
Some(snapshot_util::get_snapshotted_data(scope, context))
} else {
None
};
(v8::Global::new(scope, context), snapshotted_data)
};
// 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 mut context_scope: v8::HandleScope =
v8::HandleScope::with_context(&mut isolate, main_context.clone());
let scope = &mut context_scope;
let context = v8::Local::new(scope, main_context.clone());
bindings::initialize_context(
scope,
context,
&context_state.borrow().op_ctxs,
init_mode,
);
context.set_slot(scope, context_state.clone());
op_state.borrow_mut().put(isolate_ptr);
let inspector = if options.inspector {
Some(JsRuntimeInspector::new(scope, context, options.is_main))
} else {
None
};
let loader = options
.module_loader
.unwrap_or_else(|| Rc::new(NoopModuleLoader));
let module_map_rc = Rc::new(RefCell::new(ModuleMap::new(loader)));
if let Some(snapshotted_data) = snapshotted_data {
let mut module_map = module_map_rc.borrow_mut();
module_map.update_with_snapshotted_data(scope, snapshotted_data);
}
context.set_slot(scope, module_map_rc.clone());
{
let main_realm = JsRealmInner::new(
context_state,
main_context,
module_map_rc,
state_rc.clone(),
true,
);
let mut state = state_rc.borrow_mut();
state.main_realm = Some(JsRealm::new(main_realm.clone()));
state.inspector = inspector;
state.known_realms.push(main_realm);
}
scope.set_data(
STATE_DATA_OFFSET,
Rc::into_raw(state_rc.clone()) as *mut c_void,
);
drop(context_scope);
let mut js_runtime = JsRuntime {
inner: InnerIsolateState {
will_snapshot,
state: ManuallyDropRc(ManuallyDrop::new(state_rc)),
v8_isolate: ManuallyDrop::new(isolate),
},
init_mode,
allocations: IsolateAllocations::default(),
event_loop_middlewares,
global_template_middlewares,
global_object_middlewares,
extensions: options.extensions,
is_main_runtime: options.is_main,
};
let realm = js_runtime.main_realm();
// TODO(mmastrac): We should thread errors back out of the runtime
js_runtime
.init_extension_js(&realm, maybe_load_callback)
.unwrap();
// If the user has requested that we rename modules
if let Some(preserve_snapshotted_modules) =
options.preserve_snapshotted_modules
{
js_runtime
.module_map()
.borrow_mut()
.clear_module_map(preserve_snapshotted_modules);
}
js_runtime
}
#[inline]
pub(crate) fn module_map(&mut self) -> Rc<RefCell<ModuleMap>> {
self.main_realm().0.module_map()
}
#[inline]
pub fn main_context(&self) -> v8::Global<v8::Context> {
self
.inner
.state
.borrow()
.known_realms
.get(0)
.unwrap()
.context()
.clone()
}
#[inline]
pub fn v8_isolate(&mut self) -> &mut v8::OwnedIsolate {
&mut self.inner.v8_isolate
}
#[inline]
pub fn inspector(&mut self) -> Rc<RefCell<JsRuntimeInspector>> {
self.inner.state.borrow().inspector()
}
#[inline]
pub fn main_realm(&mut self) -> JsRealm {
let state = self.inner.state.borrow();
state.main_realm.clone().unwrap()
}
/// Returns the extensions that this runtime is using (including internal ones).
pub fn extensions(&self) -> &Vec<Extension> {
&self.extensions
}
/// 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.
pub fn create_realm(
&mut self,
options: CreateRealmOptions,
) -> Result<JsRealm, Error> {
let realm = {
let context_state = Rc::new(RefCell::new(ContextState::default()));
let op_ctxs: Box<[OpCtx]> = self
.main_realm()
.0
.state()
.borrow()
.op_ctxs
.iter()
.map(|op_ctx| {
OpCtx::new(
op_ctx.id,
context_state.clone(),
op_ctx.decl.clone(),
op_ctx.state.clone(),
op_ctx.runtime_state.clone(),
)
})
.collect();
context_state.borrow_mut().op_ctxs = op_ctxs;
context_state.borrow_mut().isolate = Some(self.v8_isolate() as _);
let raw_ptr = self.v8_isolate() as *mut v8::OwnedIsolate;
// SAFETY: Having the scope tied to self's lifetime makes it impossible to
// reference JsRuntimeState::op_ctxs 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 isolate = unsafe { raw_ptr.as_mut() }.unwrap();
let scope = &mut v8::HandleScope::new(isolate);
let context = create_context(
scope,
&self.global_template_middlewares,
&self.global_object_middlewares,
);
let scope = &mut v8::ContextScope::new(scope, context);
let context = bindings::initialize_context(
scope,
context,
&context_state.borrow().op_ctxs,
self.init_mode,
);
context.set_slot(scope, context_state.clone());
let loader = options
.module_loader
.unwrap_or_else(|| Rc::new(NoopModuleLoader));
let module_map_rc = Rc::new(RefCell::new(ModuleMap::new(loader)));
// TODO(andreubotella): Should the module map be initialized with snapshotted data?
context.set_slot(scope, module_map_rc.clone());
let realm = JsRealmInner::new(
context_state,
v8::Global::new(scope, context),
module_map_rc,
self.inner.state.clone(),
false,
);
let mut state = self.inner.state.borrow_mut();
state.known_realms.push(realm.clone());
JsRealm::new(realm)
};
self.init_extension_js(&realm, None)?;
Ok(realm)
}
#[inline]
pub fn handle_scope(&mut self) -> v8::HandleScope {
self.main_realm().handle_scope(self.v8_isolate())
}
/// Initializes JS of provided Extensions in the given realm.
fn init_extension_js(
&mut self,
realm: &JsRealm,
maybe_load_callback: Option<ExtModuleLoaderCb>,
) -> Result<(), Error> {
// Initialization of JS happens in phases:
// 1. Iterate through all extensions:
// a. Execute all extension "script" JS files
// b. Load all extension "module" JS files (but do not execute them yet)
// 2. Iterate through all extensions:
// a. If an extension has a `esm_entry_point`, execute it.
// Take extensions temporarily so we can avoid have a mutable reference to self
let extensions = std::mem::take(&mut self.extensions);
// TODO(nayeemrmn): Module maps should be per-realm.
let loader = self.module_map().borrow().loader.clone();
let ext_loader = Rc::new(ExtModuleLoader::new(
&extensions,
maybe_load_callback.map(Rc::new),
));
self.module_map().borrow_mut().loader = ext_loader;
let mut esm_entrypoints = vec![];
futures::executor::block_on(async {
if self.init_mode == InitMode::New {
for file_source in &*BUILTIN_SOURCES {
realm.execute_script(
self.v8_isolate(),
file_source.specifier,
file_source.load()?,
)?;
}
}
self.init_cbs(realm);
for extension in &extensions {
let maybe_esm_entry_point = extension.get_esm_entry_point();
for file_source in extension.get_esm_sources() {
self
.load_side_module(
&ModuleSpecifier::parse(file_source.specifier)?,
None,
)
.await?;
}
if let Some(entry_point) = maybe_esm_entry_point {
esm_entrypoints.push(entry_point);
}
for file_source in extension.get_js_sources() {
realm.execute_script(
self.v8_isolate(),
file_source.specifier,
file_source.load()?,
)?;
}
}
for specifier in esm_entrypoints {
let mod_id = {
self
.module_map()
.borrow()
.get_id(specifier, AssertedModuleType::JavaScriptOrWasm)
.unwrap_or_else(|| {
panic!("{} not present in the module map", specifier)
})
};
let receiver = self.mod_evaluate(mod_id);
self.run_event_loop(false).await?;
receiver
.await?
.with_context(|| format!("Couldn't execute '{specifier}'"))?;
}
#[cfg(debug_assertions)]
{
let module_map_rc = self.module_map();
let mut scope = realm.handle_scope(self.v8_isolate());
let module_map = module_map_rc.borrow();
module_map.assert_all_modules_evaluated(&mut scope);
}
Ok::<_, anyhow::Error>(())
})?;
self.extensions = extensions;
self.module_map().borrow_mut().loader = loader;
Ok(())
}
/// Collects ops from extensions & applies middleware
fn collect_ops(exts: &mut [Extension]) -> Vec<OpDecl> {
for (ext, previous_exts) in