-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
bindings.rs
1555 lines (1424 loc) · 46.2 KB
/
bindings.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::error::is_instance_of_error;
use crate::error::JsError;
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::ops_builtin::WasmStreamingResource;
use crate::resolve_url_or_path;
use crate::source_map::apply_source_map as apply_source_map_;
use crate::JsRuntime;
use crate::PromiseId;
use crate::ResourceId;
use crate::ZeroCopyBuf;
use anyhow::Error;
use log::debug;
use once_cell::sync::Lazy;
use serde::Deserialize;
use serde::Serialize;
use serde_v8::to_v8;
use std::cell::RefCell;
use std::collections::HashMap;
use std::option::Option;
use std::os::raw::c_void;
use url::Url;
use v8::HandleScope;
use v8::Local;
use v8::MapFnTo;
use v8::SharedArrayBuffer;
use v8::ValueDeserializerHelper;
use v8::ValueSerializerHelper;
pub static EXTERNAL_REFERENCES: Lazy<v8::ExternalReferences> =
Lazy::new(|| {
v8::ExternalReferences::new(&[
v8::ExternalReference {
function: ref_op.map_fn_to(),
},
v8::ExternalReference {
function: unref_op.map_fn_to(),
},
v8::ExternalReference {
function: set_macrotask_callback.map_fn_to(),
},
v8::ExternalReference {
function: set_nexttick_callback.map_fn_to(),
},
v8::ExternalReference {
function: set_promise_reject_callback.map_fn_to(),
},
v8::ExternalReference {
function: set_uncaught_exception_callback.map_fn_to(),
},
v8::ExternalReference {
function: run_microtasks.map_fn_to(),
},
v8::ExternalReference {
function: has_tick_scheduled.map_fn_to(),
},
v8::ExternalReference {
function: set_has_tick_scheduled.map_fn_to(),
},
v8::ExternalReference {
function: eval_context.map_fn_to(),
},
v8::ExternalReference {
function: queue_microtask.map_fn_to(),
},
v8::ExternalReference {
function: create_host_object.map_fn_to(),
},
v8::ExternalReference {
function: encode.map_fn_to(),
},
v8::ExternalReference {
function: decode.map_fn_to(),
},
v8::ExternalReference {
function: serialize.map_fn_to(),
},
v8::ExternalReference {
function: deserialize.map_fn_to(),
},
v8::ExternalReference {
function: get_promise_details.map_fn_to(),
},
v8::ExternalReference {
function: get_proxy_details.map_fn_to(),
},
v8::ExternalReference {
function: is_proxy.map_fn_to(),
},
v8::ExternalReference {
function: memory_usage.map_fn_to(),
},
v8::ExternalReference {
function: call_console.map_fn_to(),
},
v8::ExternalReference {
function: set_wasm_streaming_callback.map_fn_to(),
},
v8::ExternalReference {
function: abort_wasm_streaming.map_fn_to(),
},
v8::ExternalReference {
function: destructure_error.map_fn_to(),
},
v8::ExternalReference {
function: terminate.map_fn_to(),
},
v8::ExternalReference {
function: apply_source_map.map_fn_to(),
},
])
});
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);
// Snapshot already registered `Deno.core.ops` but
// extensions may provide ops that aren't part of the snapshot.
//
// TODO(@littledivy): This is extra complexity for
// a really weird usecase. Remove this once all
// tsc ops are static at snapshot time.
if snapshot_loaded {
// Grab the Deno.core & Deno.core.ops objects
let core_obj = JsRuntime::grab_global::<v8::Object>(scope, "Deno.core")
.expect("Deno.core to exist");
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);
initialize_op_names(scope, core_obj, op_ctxs);
return scope.escape(context);
}
// global.Deno = { core: { } };
let core_val = JsRuntime::ensure_objs(scope, global, "Deno.core").unwrap();
// Bind functions to Deno.core.*
set_func(scope, core_val, "refOp_", ref_op);
set_func(scope, core_val, "unrefOp_", unref_op);
set_func(
scope,
core_val,
"setMacrotaskCallback",
set_macrotask_callback,
);
set_func(
scope,
core_val,
"setNextTickCallback",
set_nexttick_callback,
);
set_func(
scope,
core_val,
"setPromiseRejectCallback",
set_promise_reject_callback,
);
set_func(
scope,
core_val,
"setUncaughtExceptionCallback",
set_uncaught_exception_callback,
);
set_func(scope, core_val, "runMicrotasks", run_microtasks);
set_func(scope, core_val, "hasTickScheduled", has_tick_scheduled);
set_func(
scope,
core_val,
"setHasTickScheduled",
set_has_tick_scheduled,
);
set_func(scope, core_val, "evalContext", eval_context);
set_func(scope, core_val, "encode", encode);
set_func(scope, core_val, "decode", decode);
set_func(scope, core_val, "serialize", serialize);
set_func(scope, core_val, "deserialize", deserialize);
set_func(scope, core_val, "getPromiseDetails", get_promise_details);
set_func(scope, core_val, "getProxyDetails", get_proxy_details);
set_func(scope, core_val, "isProxy", is_proxy);
set_func(scope, core_val, "memoryUsage", memory_usage);
set_func(scope, core_val, "callConsole", call_console);
set_func(scope, core_val, "createHostObject", create_host_object);
set_func(
scope,
core_val,
"setWasmStreamingCallback",
set_wasm_streaming_callback,
);
set_func(scope, core_val, "abortWasmStreaming", abort_wasm_streaming);
set_func(scope, core_val, "destructureError", destructure_error);
set_func(scope, core_val, "terminate", terminate);
set_func(scope, core_val, "applySourceMap", apply_source_map);
// Direct bindings on `window`.
set_func(scope, global, "queueMicrotask", queue_microtask);
// Bind functions to Deno.core.ops.*
let ops_obj = JsRuntime::ensure_objs(scope, global, "Deno.core.ops").unwrap();
initialize_ops(scope, ops_obj, op_ctxs);
initialize_op_names(scope, core_val, op_ctxs);
scope.escape(context)
}
fn initialize_ops(
scope: &mut v8::HandleScope,
ops_obj: v8::Local<v8::Object>,
op_ctxs: &[OpCtx],
) {
for ctx in op_ctxs {
let ctx_ptr = ctx as *const OpCtx as *const c_void;
set_func_raw(scope, ops_obj, ctx.decl.name, ctx.decl.v8_fn_ptr, ctx_ptr);
}
}
fn initialize_op_names(
scope: &mut v8::HandleScope,
core_obj: v8::Local<v8::Object>,
op_ctxs: &[OpCtx],
) {
let names: Vec<&str> = op_ctxs.iter().map(|o| o.decl.name).collect();
let k = v8::String::new(scope, "op_names").unwrap().into();
let v = serde_v8::to_v8(scope, names).unwrap();
core_obj.set(scope, k, v);
}
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());
}
// Register a raw v8::FunctionCallback
// with some external data.
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,
) {
let key = v8::String::new(scope, name).unwrap();
let external = v8::External::new(scope, external_data as *mut c_void);
let val = v8::Function::builder_raw(callback)
.data(external.into())
.build(scope)
.unwrap();
val.set_name(key);
obj.set(scope, key.into(), val.into());
}
pub extern "C" fn host_import_module_dynamically_callback(
context: v8::Local<v8::Context>,
_host_defined_options: v8::Local<v8::Data>,
resource_name: v8::Local<v8::Value>,
specifier: v8::Local<v8::String>,
import_assertions: v8::Local<v8::FixedArray>,
) -> *mut v8::Promise {
let scope = &mut unsafe { v8::CallbackScope::new(context) };
// NOTE(bartlomieju): will crash for non-UTF-8 specifier
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();
}
// Map errors from module resolution (not JS errors from module execution) to
// ones rethrown from this scope, so they include the call stack of the
// dynamic import site. Error objects without any stack frames are assumed to
// be module resolution errors, other exception values are left as they are.
let map_err = |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);
};
let map_err = v8::FunctionTemplate::new(scope, map_err);
let map_err = map_err.get_function(scope).unwrap();
let promise = promise.catch(scope, map_err).unwrap();
&*promise as *const _ as *mut _
}
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());
}
pub extern "C" fn promise_reject_callback(message: v8::PromiseRejectMessage) {
use v8::PromiseRejectEvent::*;
let scope = &mut unsafe { v8::CallbackScope::new(&message) };
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
// Node compat: perform synchronous process.emit("unhandledRejection").
//
// Note the callback follows the (type, promise, reason) signature of Node's
// internal promiseRejectHandler from lib/internal/process/promises.js, not
// the (promise, reason) signature of the "unhandledRejection" event listener.
//
// Short-circuits Deno's regular unhandled rejection logic because that's
// a) asynchronous, and b) always terminates.
if let Some(js_promise_reject_cb) = state.js_promise_reject_cb.clone() {
let js_uncaught_exception_cb = state.js_uncaught_exception_cb.clone();
drop(state); // Drop borrow, callbacks can call back into runtime.
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 args = &[type_.into(), promise.into(), reason];
js_promise_reject_cb
.open(tc_scope)
.call(tc_scope, undefined, args);
if let Some(exception) = tc_scope.exception() {
if let Some(js_uncaught_exception_cb) = js_uncaught_exception_cb {
tc_scope.reset(); // Cancel pending exception.
js_uncaught_exception_cb.open(tc_scope).call(
tc_scope,
undefined,
&[exception],
);
}
}
if tc_scope.has_caught() {
// If we get here, an exception was thrown by the unhandledRejection
// handler and there is ether no uncaughtException handler or the
// handler threw an exception of its own.
//
// TODO(bnoordhuis) Node terminates the process or worker thread
// but we don't really have that option. The exception won't bubble
// up either because V8 cancels it when this function returns.
let exception = tc_scope
.stack_trace()
.or_else(|| tc_scope.exception())
.map(|value| value.to_rust_string_lossy(tc_scope))
.unwrap_or_else(|| "no exception".into());
eprintln!("Unhandled exception: {}", exception);
}
} else {
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 => {
// Should not warn. See #1272
}
}
}
}
fn ref_op<'s>(
scope: &mut v8::HandleScope<'s>,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
let promise_id = match v8::Local::<v8::Integer>::try_from(args.get(0))
.map(|l| l.value() as PromiseId)
.map_err(Error::from)
{
Ok(promise_id) => promise_id,
Err(err) => {
throw_type_error(scope, format!("invalid promise id: {}", err));
return;
}
};
state.unrefed_ops.remove(&promise_id);
}
fn unref_op<'s>(
scope: &mut v8::HandleScope<'s>,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
let promise_id = match v8::Local::<v8::Integer>::try_from(args.get(0))
.map(|l| l.value() as PromiseId)
.map_err(Error::from)
{
Ok(promise_id) => promise_id,
Err(err) => {
throw_type_error(scope, format!("invalid promise id: {}", err));
return;
}
};
state.unrefed_ops.insert(promise_id);
}
fn has_tick_scheduled(
scope: &mut v8::HandleScope,
_args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
let state_rc = JsRuntime::state(scope);
let state = state_rc.borrow();
rv.set(to_v8(scope, state.has_tick_scheduled).unwrap());
}
fn set_has_tick_scheduled(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
state.has_tick_scheduled = args.get(0).is_true();
}
fn run_microtasks(
scope: &mut v8::HandleScope,
_args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
scope.perform_microtask_checkpoint();
}
fn set_nexttick_callback(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
if let Ok(cb) = arg0_to_cb(scope, args) {
JsRuntime::state(scope)
.borrow_mut()
.js_nexttick_cbs
.push(cb);
}
}
fn set_macrotask_callback(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
if let Ok(cb) = arg0_to_cb(scope, args) {
JsRuntime::state(scope)
.borrow_mut()
.js_macrotask_cbs
.push(cb);
}
}
fn set_promise_reject_callback(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
if let Ok(new) = arg0_to_cb(scope, args) {
if let Some(old) = JsRuntime::state(scope)
.borrow_mut()
.js_promise_reject_cb
.replace(new)
{
let old = v8::Local::new(scope, old);
rv.set(old.into());
}
}
}
fn set_uncaught_exception_callback(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
if let Ok(new) = arg0_to_cb(scope, args) {
if let Some(old) = JsRuntime::state(scope)
.borrow_mut()
.js_uncaught_exception_cb
.replace(new)
{
let old = v8::Local::new(scope, old);
rv.set(old.into());
}
}
}
fn arg0_to_cb(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
) -> Result<v8::Global<v8::Function>, ()> {
v8::Local::<v8::Function>::try_from(args.get(0))
.map(|cb| v8::Global::new(scope, cb))
.map_err(|err| throw_type_error(scope, err.to_string()))
}
fn eval_context(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
let source = match v8::Local::<v8::String>::try_from(args.get(0)) {
Ok(s) => s,
Err(_) => {
throw_type_error(scope, "Missing first argument");
return;
}
};
let url = match v8::Local::<v8::String>::try_from(args.get(1)) {
Ok(s) => match resolve_url_or_path(&s.to_rust_string_lossy(scope)) {
Ok(s) => Some(s),
Err(err) => {
throw_type_error(scope, &format!("Invalid specifier: {}", err));
return;
}
},
Err(_) => None,
};
#[derive(Serialize)]
struct Output<'s>(Option<serde_v8::Value<'s>>, Option<ErrInfo<'s>>);
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ErrInfo<'s> {
thrown: serde_v8::Value<'s>,
is_native_error: bool,
is_compile_error: bool,
}
let tc_scope = &mut v8::TryCatch::new(scope);
let name = v8::String::new(
tc_scope,
url.as_ref().map_or(crate::DUMMY_SPECIFIER, Url::as_str),
)
.unwrap();
let origin = script_origin(tc_scope, name);
let maybe_script = v8::Script::compile(tc_scope, source, Some(&origin));
if maybe_script.is_none() {
assert!(tc_scope.has_caught());
let exception = tc_scope.exception().unwrap();
let output = Output(
None,
Some(ErrInfo {
thrown: exception.into(),
is_native_error: is_instance_of_error(tc_scope, exception),
is_compile_error: true,
}),
);
rv.set(to_v8(tc_scope, output).unwrap());
return;
}
let result = maybe_script.unwrap().run(tc_scope);
if result.is_none() {
assert!(tc_scope.has_caught());
let exception = tc_scope.exception().unwrap();
let output = Output(
None,
Some(ErrInfo {
thrown: exception.into(),
is_native_error: is_instance_of_error(tc_scope, exception),
is_compile_error: false,
}),
);
rv.set(to_v8(tc_scope, output).unwrap());
return;
}
let output = Output(Some(result.unwrap().into()), None);
rv.set(to_v8(tc_scope, output).unwrap());
}
/// This binding should be used if there's a custom console implementation
/// available. Using it will make sure that proper stack frames are displayed
/// in the inspector console.
///
/// Each method on console object should be bound to this function, eg:
/// ```ignore
/// function wrapConsole(consoleFromDeno, consoleFromV8) {
/// const callConsole = core.callConsole;
///
/// for (const key of Object.keys(consoleFromV8)) {
/// if (consoleFromDeno.hasOwnProperty(key)) {
/// consoleFromDeno[key] = callConsole.bind(
/// consoleFromDeno,
/// consoleFromV8[key],
/// consoleFromDeno[key],
/// );
/// }
/// }
/// }
/// ```
///
/// Inspired by:
/// https://github.com/nodejs/node/blob/1317252dfe8824fd9cfee125d2aaa94004db2f3b/src/inspector_js_api.cc#L194-L222
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);
}
fn set_wasm_streaming_callback(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let cb = match arg0_to_cb(scope, args) {
Ok(cb) => cb,
Err(()) => return,
};
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
// The callback to pass to the v8 API has to be a unit type, so it can't
// borrow or move any local variables. Therefore, we're storing the JS
// callback in a JsRuntimeState slot.
if let slot @ None = &mut state.js_wasm_streaming_cb {
slot.replace(cb);
} else {
return throw_type_error(
scope,
"Deno.core.setWasmStreamingCallback() already called",
);
}
scope.set_wasm_streaming_callback(|scope, arg, wasm_streaming| {
let (cb_handle, streaming_rid) = {
let state_rc = JsRuntime::state(scope);
let state = state_rc.borrow();
let cb_handle = state.js_wasm_streaming_cb.as_ref().unwrap().clone();
let streaming_rid = state
.op_state
.borrow_mut()
.resource_table
.add(WasmStreamingResource(RefCell::new(wasm_streaming)));
(cb_handle, streaming_rid)
};
let undefined = v8::undefined(scope);
let rid = serde_v8::to_v8(scope, streaming_rid).unwrap();
cb_handle
.open(scope)
.call(scope, undefined.into(), &[arg, rid]);
});
}
fn abort_wasm_streaming(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
_rv: v8::ReturnValue,
) {
let rid: ResourceId = match serde_v8::from_v8(scope, args.get(0)) {
Ok(rid) => rid,
Err(_) => return throw_type_error(scope, "Invalid argument"),
};
let exception = args.get(1);
let wasm_streaming = {
let state_rc = JsRuntime::state(scope);
let state = state_rc.borrow();
let wsr = state
.op_state
.borrow_mut()
.resource_table
.take::<WasmStreamingResource>(rid);
match wsr {
Ok(wasm_streaming) => wasm_streaming,
Err(err) => {
let message = v8::String::new(scope, &err.to_string()).unwrap();
let v8_error = v8::Exception::error(scope, message);
scope.throw_exception(v8_error);
return;
}
}
};
// At this point there are no clones of Rc<WasmStreamingResource> on the
// resource table, and no one should own a reference because we're never
// cloning them. So we can be sure `wasm_streaming` is the only reference.
if let Ok(wsr) = std::rc::Rc::try_unwrap(wasm_streaming) {
// NOTE: v8::WasmStreaming::abort can't be called while `state` is borrowed;
// see https://github.com/denoland/deno/issues/13917
wsr.0.into_inner().abort(Some(exception));
} else {
panic!("Couldn't consume WasmStreamingResource.");
}
}
fn encode(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
let text = match v8::Local::<v8::String>::try_from(args.get(0)) {
Ok(s) => s,
Err(_) => {
throw_type_error(scope, "Invalid argument");
return;
}
};
let text_str = text.to_rust_string_lossy(scope);
let bytes: Box<[u8]> = text_str.into_bytes().into_boxed_slice();
let len = bytes.len();
let backing_store =
v8::ArrayBuffer::new_backing_store_from_boxed_slice(bytes).make_shared();
let buffer = v8::ArrayBuffer::with_backing_store(scope, &backing_store);
let u8array = v8::Uint8Array::new(scope, buffer, 0, len).unwrap();
rv.set(u8array.into())
}
fn decode(
scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue,
) {
let zero_copy: ZeroCopyBuf = match serde_v8::from_v8(scope, args.get(0)) {
Ok(zbuf) => zbuf,
Err(_) => {
throw_type_error(scope, "Invalid argument");
return;
}
};
let buf = &zero_copy;
// Strip BOM
let buf =
if buf.len() >= 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf {
&buf[3..]
} else {
buf
};
// If `String::new_from_utf8()` returns `None`, this means that the
// length of the decoded string would be longer than what V8 can
// handle. In this case we return `RangeError`.
//
// For more details see:
// - https://encoding.spec.whatwg.org/#dom-textdecoder-decode
// - https://github.com/denoland/deno/issues/6649
// - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278
match v8::String::new_from_utf8(scope, buf, v8::NewStringType::Normal) {
Some(text) => rv.set(text.into()),
None => {
let msg = v8::String::new(scope, "string too long").unwrap();
let exception = v8::Exception::range_error(scope, msg);
scope.throw_exception(exception);
}
};
}
struct SerializeDeserialize<'a> {
host_objects: Option<v8::Local<'a, v8::Array>>,
}
impl<'a> v8::ValueSerializerImpl for SerializeDeserialize<'a> {
#[allow(unused_variables)]
fn throw_data_clone_error<'s>(
&mut self,
scope: &mut v8::HandleScope<'s>,
message: v8::Local<'s, v8::String>,
) {
let error = v8::Exception::type_error(scope, message);
scope.throw_exception(error);
}
fn get_shared_array_buffer_id<'s>(
&mut self,
scope: &mut HandleScope<'s>,
shared_array_buffer: Local<'s, SharedArrayBuffer>,
) -> Option<u32> {
let state_rc = JsRuntime::state(scope);
let state = state_rc.borrow_mut();
if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store {
let backing_store = shared_array_buffer.get_backing_store();
let id = shared_array_buffer_store.insert(backing_store);
Some(id)
} else {
None
}
}
fn get_wasm_module_transfer_id(
&mut self,
scope: &mut HandleScope<'_>,
module: Local<v8::WasmModuleObject>,
) -> Option<u32> {
let state_rc = JsRuntime::state(scope);
let state = state_rc.borrow_mut();
if let Some(compiled_wasm_module_store) = &state.compiled_wasm_module_store
{
let compiled_wasm_module = module.get_compiled_module();
let id = compiled_wasm_module_store.insert(compiled_wasm_module);
Some(id)
} else {
None
}
}
fn write_host_object<'s>(
&mut self,
scope: &mut v8::HandleScope<'s>,
object: v8::Local<'s, v8::Object>,