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
use crate::error::is_instance_of_error;
use crate::modules::get_asserted_module_type_from_assertions;
use crate::modules::parse_import_assertions;
use crate::modules::validate_import_assertions;
use crate::modules::ImportAssertionsKind;
use crate::modules::ModuleMap;
use crate::ops::OpCtx;
use crate::JsRealm;
use crate::JsRuntime;
use log::debug;
use std::option::Option;
use std::os::raw::c_void;
use v8::fast_api::FastFunction;
use v8::MapFnTo;
pub fn external_references(
ops: &[OpCtx],
snapshot_loaded: bool,
) -> v8::ExternalReferences {
let mut references = vec![
v8::ExternalReference {
function: call_console.map_fn_to(),
},
v8::ExternalReference {
function: import_meta_resolve.map_fn_to(),
},
v8::ExternalReference {
function: catch_dynamic_import_promise_error.map_fn_to(),
},
v8::ExternalReference {
function: empty_fn.map_fn_to(),
},
];
for ctx in ops {
let ctx_ptr = ctx as *const OpCtx as _;
references.push(v8::ExternalReference { pointer: ctx_ptr });
references.push(v8::ExternalReference {
function: ctx.decl.v8_fn_ptr,
});
if snapshot_loaded {
if let Some(fast_fn) = &ctx.decl.fast_fn {
references.push(v8::ExternalReference {
pointer: fast_fn.function() as _,
});
}
}
}
let refs = v8::ExternalReferences::new(&references);
std::mem::forget(references);
refs
}
pub fn script_origin<'a>(
s: &mut v8::HandleScope<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let source_map_url = v8::String::new(s, "").unwrap();
v8::ScriptOrigin::new(
s,
resource_name.into(),
0,
0,
false,
123,
source_map_url.into(),
true,
false,
false,
)
}
pub fn module_origin<'a>(
s: &mut v8::HandleScope<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let source_map_url = v8::String::new(s, "").unwrap();
v8::ScriptOrigin::new(
s,
resource_name.into(),
0,
0,
false,
123,
source_map_url.into(),
true,
false,
true,
)
}
pub fn initialize_context<'s>(
scope: &mut v8::HandleScope<'s, ()>,
op_ctxs: &[OpCtx],
snapshot_loaded: bool,
) -> v8::Local<'s, v8::Context> {
let scope = &mut v8::EscapableHandleScope::new(scope);
let context = v8::Context::new(scope);
let global = context.global(scope);
let scope = &mut v8::ContextScope::new(scope, context);
if snapshot_loaded {
let ops_obj = JsRuntime::grab_global::<v8::Object>(scope, "Deno.core.ops")
.expect("Deno.core.ops to exist");
initialize_ops(scope, ops_obj, op_ctxs, snapshot_loaded);
return scope.escape(context);
}
let core_val = JsRuntime::ensure_objs(scope, global, "Deno.core").unwrap();
set_func(scope, core_val, "callConsole", call_console);
let ops_obj = JsRuntime::ensure_objs(scope, global, "Deno.core.ops").unwrap();
initialize_ops(scope, ops_obj, op_ctxs, snapshot_loaded);
scope.escape(context)
}
fn initialize_ops(
scope: &mut v8::HandleScope,
ops_obj: v8::Local<v8::Object>,
op_ctxs: &[OpCtx],
snapshot_loaded: bool,
) {
for ctx in op_ctxs {
let ctx_ptr = ctx as *const OpCtx as *const c_void;
if ctx.decl.fast_fn.is_some() && snapshot_loaded {
set_func_raw(
scope,
ops_obj,
ctx.decl.name,
ctx.decl.v8_fn_ptr,
ctx_ptr,
&ctx.decl.fast_fn,
snapshot_loaded,
);
} else {
set_func_raw(
scope,
ops_obj,
ctx.decl.name,
ctx.decl.v8_fn_ptr,
ctx_ptr,
&None,
snapshot_loaded,
);
}
}
}
pub fn set_func(
scope: &mut v8::HandleScope<'_>,
obj: v8::Local<v8::Object>,
name: &'static str,
callback: impl v8::MapFnTo<v8::FunctionCallback>,
) {
let key = v8::String::new(scope, name).unwrap();
let val = v8::Function::new(scope, callback).unwrap();
val.set_name(key);
obj.set(scope, key.into(), val.into());
}
pub fn set_func_raw(
scope: &mut v8::HandleScope<'_>,
obj: v8::Local<v8::Object>,
name: &'static str,
callback: v8::FunctionCallback,
external_data: *const c_void,
fast_function: &Option<Box<dyn FastFunction>>,
snapshot_loaded: bool,
) {
let key = v8::String::new(scope, name).unwrap();
let external = v8::External::new(scope, external_data as *mut c_void);
let builder =
v8::FunctionTemplate::builder_raw(callback).data(external.into());
let templ = if let Some(fast_function) = fast_function {
if !snapshot_loaded {
builder.build(scope)
} else {
builder.build_fast(scope, &**fast_function, None)
}
} else {
builder.build(scope)
};
let val = templ.get_function(scope).unwrap();
val.set_name(key);
obj.set(scope, key.into(), val.into());
}
pub extern "C" fn wasm_async_resolve_promise_callback(
_isolate: *mut v8::Isolate,
context: v8::Local<v8::Context>,
resolver: v8::Local<v8::PromiseResolver>,
compilation_result: v8::Local<v8::Value>,
success: v8::WasmAsyncSuccess,
) {
let scope = &mut unsafe { v8::CallbackScope::new(context) };
if success == v8::WasmAsyncSuccess::Success {
resolver.resolve(scope, compilation_result).unwrap();
} else {
resolver.reject(scope, compilation_result).unwrap();
}
}
pub fn host_import_module_dynamically_callback<'s>(
scope: &mut v8::HandleScope<'s>,
_host_defined_options: v8::Local<'s, v8::Data>,
resource_name: v8::Local<'s, v8::Value>,
specifier: v8::Local<'s, v8::String>,
import_assertions: v8::Local<'s, v8::FixedArray>,
) -> Option<v8::Local<'s, v8::Promise>> {
let specifier_str = specifier
.to_string(scope)
.unwrap()
.to_rust_string_lossy(scope);
let referrer_name_str = resource_name
.to_string(scope)
.unwrap()
.to_rust_string_lossy(scope);
let resolver = v8::PromiseResolver::new(scope).unwrap();
let promise = resolver.get_promise(scope);
let assertions = parse_import_assertions(
scope,
import_assertions,
ImportAssertionsKind::DynamicImport,
);
{
let tc_scope = &mut v8::TryCatch::new(scope);
validate_import_assertions(tc_scope, &assertions);
if tc_scope.has_caught() {
let e = tc_scope.exception().unwrap();
resolver.reject(tc_scope, e);
}
}
let asserted_module_type =
get_asserted_module_type_from_assertions(&assertions);
let resolver_handle = v8::Global::new(scope, resolver);
{
let state_rc = JsRuntime::state(scope);
let module_map_rc = JsRuntime::module_map(scope);
debug!(
"dyn_import specifier {} referrer {} ",
specifier_str, referrer_name_str
);
ModuleMap::load_dynamic_import(
module_map_rc,
&specifier_str,
&referrer_name_str,
asserted_module_type,
resolver_handle,
);
state_rc.borrow_mut().notify_new_dynamic_import();
}
let builder = v8::FunctionBuilder::new(catch_dynamic_import_promise_error);
let map_err =
v8::FunctionBuilder::<v8::Function>::build(builder, scope).unwrap();
let promise = promise.catch(scope, map_err).unwrap();
Some(promise)
}
pub extern "C" fn host_initialize_import_meta_object_callback(
context: v8::Local<v8::Context>,
module: v8::Local<v8::Module>,
meta: v8::Local<v8::Object>,
) {
let scope = &mut unsafe { v8::CallbackScope::new(context) };
let module_map_rc = JsRuntime::module_map(scope);
let module_map = module_map_rc.borrow();
let module_global = v8::Global::new(scope, module);
let info = module_map
.get_info(&module_global)
.expect("Module not found");
let url_key = v8::String::new(scope, "url").unwrap();
let url_val = v8::String::new(scope, &info.name).unwrap();
meta.create_data_property(scope, url_key.into(), url_val.into());
let main_key = v8::String::new(scope, "main").unwrap();
let main_val = v8::Boolean::new(scope, info.main);
meta.create_data_property(scope, main_key.into(), main_val.into());
let builder =
v8::FunctionBuilder::new(import_meta_resolve).data(url_val.into());
let val = v8::FunctionBuilder::<v8::Function>::build(builder, scope).unwrap();
let resolve_key = v8::String::new(scope, "resolve").unwrap();
meta.set(scope, resolve_key.into(), val.into());
}
fn import_meta_resolve(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
if args.length() > 1 {
return throw_type_error(scope, "Invalid arguments");
}
let maybe_arg_str = args.get(0).to_string(scope);
if maybe_arg_str.is_none() {
return throw_type_error(scope, "Invalid arguments");
}
let specifier = maybe_arg_str.unwrap();
let referrer = {
let url_prop = args.data().unwrap();
url_prop.to_rust_string_lossy(scope)
};
let module_map_rc = JsRuntime::module_map(scope);
let loader = {
let module_map = module_map_rc.borrow();
module_map.loader.clone()
};
match loader.resolve(&specifier.to_rust_string_lossy(scope), &referrer, false)
{
Ok(resolved) => {
let resolved_val = serde_v8::to_v8(scope, resolved.as_str()).unwrap();
rv.set(resolved_val);
}
Err(err) => {
throw_type_error(scope, &err.to_string());
}
};
}
fn empty_fn(
_scope: &mut v8::HandleScope,
_args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
}
pub fn create_empty_fn<'s>(
scope: &mut v8::HandleScope<'s>,
) -> Option<v8::Local<'s, v8::Function>> {
let empty_fn = v8::FunctionTemplate::new(scope, empty_fn);
empty_fn.get_function(scope)
}
fn catch_dynamic_import_promise_error(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let arg = args.get(0);
if is_instance_of_error(scope, arg) {
let e: crate::error::NativeJsError = serde_v8::from_v8(scope, arg).unwrap();
let name = e.name.unwrap_or_else(|| "Error".to_string());
let message = v8::Exception::create_message(scope, arg);
if message.get_stack_trace(scope).unwrap().get_frame_count() == 0 {
let arg: v8::Local<v8::Object> = arg.try_into().unwrap();
let message_key = v8::String::new(scope, "message").unwrap();
let message = arg.get(scope, message_key.into()).unwrap();
let exception = match name.as_str() {
"RangeError" => {
v8::Exception::range_error(scope, message.try_into().unwrap())
}
"TypeError" => {
v8::Exception::type_error(scope, message.try_into().unwrap())
}
"SyntaxError" => {
v8::Exception::syntax_error(scope, message.try_into().unwrap())
}
"ReferenceError" => {
v8::Exception::reference_error(scope, message.try_into().unwrap())
}
_ => v8::Exception::error(scope, message.try_into().unwrap()),
};
let code_key = v8::String::new(scope, "code").unwrap();
let code_value = v8::String::new(scope, "ERR_MODULE_NOT_FOUND").unwrap();
let exception_obj = exception.to_object(scope).unwrap();
exception_obj.set(scope, code_key.into(), code_value.into());
scope.throw_exception(exception);
return;
}
}
scope.throw_exception(arg);
}
pub extern "C" fn promise_reject_callback(message: v8::PromiseRejectMessage) {
use v8::PromiseRejectEvent::*;
let scope = &mut unsafe { v8::CallbackScope::new(&message) };
let realm_state_rc = JsRealm::state_from_scope(scope);
if let Some(js_promise_reject_cb) =
realm_state_rc.borrow().js_promise_reject_cb.clone()
{
let tc_scope = &mut v8::TryCatch::new(scope);
let undefined: v8::Local<v8::Value> = v8::undefined(tc_scope).into();
let type_ = v8::Integer::new(tc_scope, message.get_event() as i32);
let promise = message.get_promise();
let reason = match message.get_event() {
PromiseRejectWithNoHandler
| PromiseRejectAfterResolved
| PromiseResolveAfterResolved => message.get_value().unwrap_or(undefined),
PromiseHandlerAddedAfterReject => undefined,
};
let promise_global = v8::Global::new(tc_scope, promise);
let args = &[type_.into(), promise.into(), reason];
let maybe_has_unhandled_rejection_handler = js_promise_reject_cb
.open(tc_scope)
.call(tc_scope, undefined, args);
let has_unhandled_rejection_handler =
if let Some(value) = maybe_has_unhandled_rejection_handler {
value.is_true()
} else {
false
};
if has_unhandled_rejection_handler {
let state_rc = JsRuntime::state(tc_scope);
let mut state = state_rc.borrow_mut();
if let Some(pending_mod_evaluate) = state.pending_mod_evaluate.as_mut() {
if !pending_mod_evaluate.has_evaluated {
pending_mod_evaluate
.handled_promise_rejections
.push(promise_global);
}
}
}
} else {
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
let promise = message.get_promise();
let promise_global = v8::Global::new(scope, promise);
match message.get_event() {
PromiseRejectWithNoHandler => {
let error = message.get_value().unwrap();
let error_global = v8::Global::new(scope, error);
state
.pending_promise_exceptions
.insert(promise_global, error_global);
}
PromiseHandlerAddedAfterReject => {
state.pending_promise_exceptions.remove(&promise_global);
}
PromiseRejectAfterResolved => {}
PromiseResolveAfterResolved => {
}
}
};
}
fn call_console(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
if args.length() < 2
|| !args.get(0).is_function()
|| !args.get(1).is_function()
{
return throw_type_error(scope, "Invalid arguments");
}
let mut call_args = vec![];
for i in 2..args.length() {
call_args.push(args.get(i));
}
let receiver = args.this();
let inspector_console_method =
v8::Local::<v8::Function>::try_from(args.get(0)).unwrap();
let deno_console_method =
v8::Local::<v8::Function>::try_from(args.get(1)).unwrap();
inspector_console_method.call(scope, receiver.into(), &call_args);
deno_console_method.call(scope, receiver.into(), &call_args);
}
pub fn module_resolve_callback<'s>(
context: v8::Local<'s, v8::Context>,
specifier: v8::Local<'s, v8::String>,
import_assertions: v8::Local<'s, v8::FixedArray>,
referrer: v8::Local<'s, v8::Module>,
) -> Option<v8::Local<'s, v8::Module>> {
let scope = &mut unsafe { v8::CallbackScope::new(context) };
let module_map_rc = JsRuntime::module_map(scope);
let module_map = module_map_rc.borrow();
let referrer_global = v8::Global::new(scope, referrer);
let referrer_info = module_map
.get_info(&referrer_global)
.expect("ModuleInfo not found");
let referrer_name = referrer_info.name.to_string();
let specifier_str = specifier.to_rust_string_lossy(scope);
let assertions = parse_import_assertions(
scope,
import_assertions,
ImportAssertionsKind::StaticImport,
);
let maybe_module = module_map.resolve_callback(
scope,
&specifier_str,
&referrer_name,
assertions,
);
if let Some(module) = maybe_module {
return Some(module);
}
let msg = format!(
r#"Cannot resolve module "{}" from "{}""#,
specifier_str, referrer_name
);
throw_type_error(scope, msg);
None
}
pub fn throw_type_error(scope: &mut v8::HandleScope, message: impl AsRef<str>) {
let message = v8::String::new(scope, message.as_ref()).unwrap();
let exception = v8::Exception::type_error(scope, message);
scope.throw_exception(exception);
}