forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
2363 lines (2177 loc) · 70 KB
/
lib.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 core::ptr::NonNull;
use deno_core::anyhow::anyhow;
use deno_core::error::generic_error;
use deno_core::error::range_error;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::futures::channel::mpsc;
use deno_core::futures::Future;
use deno_core::include_js_files;
use deno_core::op;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::serde_v8;
use deno_core::v8;
use deno_core::v8::fast_api;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::Resource;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use dlopen::raw::Library;
use libffi::middle::Arg;
use libffi::middle::Cif;
use libffi::raw::*;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ffi::CStr;
use std::mem::size_of;
use std::os::raw::c_char;
use std::os::raw::c_short;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::rc::Rc;
use std::sync::mpsc::sync_channel;
#[cfg(not(target_os = "windows"))]
mod jit_trampoline;
#[cfg(not(target_os = "windows"))]
mod tcc;
#[cfg(not(target_pointer_width = "64"))]
compile_error!("platform not supported");
// Assert assumptions made in `prelude.h`
const _: () = {
assert!(size_of::<c_char>() == 1);
assert!(size_of::<c_short>() == 2);
assert!(size_of::<*const ()>() == 8);
};
thread_local! {
static LOCAL_ISOLATE_POINTER: RefCell<*const v8::Isolate> = RefCell::new(ptr::null());
}
const MAX_SAFE_INTEGER: isize = 9007199254740991;
const MIN_SAFE_INTEGER: isize = -9007199254740991;
pub struct Unstable(pub bool);
fn check_unstable(state: &OpState, api_name: &str) {
let unstable = state.borrow::<Unstable>();
if !unstable.0 {
eprintln!(
"Unstable API '{}'. The --unstable flag must be provided.",
api_name
);
std::process::exit(70);
}
}
pub fn check_unstable2(state: &Rc<RefCell<OpState>>, api_name: &str) {
let state = state.borrow();
check_unstable(&state, api_name)
}
pub trait FfiPermissions {
fn check(&mut self, path: Option<&Path>) -> Result<(), AnyError>;
}
#[derive(Clone)]
struct Symbol {
cif: libffi::middle::Cif,
ptr: libffi::middle::CodePtr,
parameter_types: Vec<NativeType>,
result_type: NativeType,
// This is dead code only on Windows
#[allow(dead_code)]
can_callback: bool,
}
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for Symbol {}
unsafe impl Sync for Symbol {}
#[derive(Clone)]
struct PtrSymbol {
cif: libffi::middle::Cif,
ptr: libffi::middle::CodePtr,
}
impl PtrSymbol {
fn new(fn_ptr: usize, def: &ForeignFunction) -> Self {
let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _);
let cif = libffi::middle::Cif::new(
def
.parameters
.clone()
.into_iter()
.map(libffi::middle::Type::from),
def.result.into(),
);
Self { cif, ptr }
}
}
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for PtrSymbol {}
unsafe impl Sync for PtrSymbol {}
struct DynamicLibraryResource {
lib: Library,
symbols: HashMap<String, Box<Symbol>>,
}
impl Resource for DynamicLibraryResource {
fn name(&self) -> Cow<str> {
"dynamicLibrary".into()
}
fn close(self: Rc<Self>) {
drop(self)
}
}
impl DynamicLibraryResource {
fn get_static(&self, symbol: String) -> Result<*const c_void, AnyError> {
// By default, Err returned by this function does not tell
// which symbol wasn't exported. So we'll modify the error
// message to include the name of symbol.
//
// SAFETY: The obtained T symbol is the size of a pointer.
match unsafe { self.lib.symbol::<*const c_void>(&symbol) } {
Ok(value) => Ok(Ok(value)),
Err(err) => Err(generic_error(format!(
"Failed to register symbol {}: {}",
symbol, err
))),
}?
}
}
type PendingFfiAsyncWork = Box<dyn FnOnce()>;
struct FfiState {
async_work_sender: mpsc::UnboundedSender<PendingFfiAsyncWork>,
async_work_receiver: mpsc::UnboundedReceiver<PendingFfiAsyncWork>,
active_refed_functions: usize,
}
pub fn init<P: FfiPermissions + 'static>(unstable: bool) -> Extension {
Extension::builder()
.js(include_js_files!(
prefix "deno:ext/ffi",
"00_ffi.js",
))
.ops(vec![
op_ffi_load::decl::<P>(),
op_ffi_get_static::decl(),
op_ffi_call_nonblocking::decl(),
op_ffi_call_ptr::decl::<P>(),
op_ffi_call_ptr_nonblocking::decl::<P>(),
op_ffi_ptr_of::decl::<P>(),
op_ffi_get_buf::decl::<P>(),
op_ffi_buf_copy_into::decl::<P>(),
op_ffi_cstr_read::decl::<P>(),
op_ffi_read_u8::decl::<P>(),
op_ffi_read_i8::decl::<P>(),
op_ffi_read_u16::decl::<P>(),
op_ffi_read_i16::decl::<P>(),
op_ffi_read_u32::decl::<P>(),
op_ffi_read_i32::decl::<P>(),
op_ffi_read_u64::decl::<P>(),
op_ffi_read_i64::decl::<P>(),
op_ffi_read_f32::decl::<P>(),
op_ffi_read_f64::decl::<P>(),
op_ffi_unsafe_callback_create::decl::<P>(),
op_ffi_unsafe_callback_ref::decl(),
])
.event_loop_middleware(|op_state_rc, _cx| {
// FFI callbacks coming in from other threads will call in and get queued.
let mut maybe_scheduling = false;
let mut work_items: Vec<PendingFfiAsyncWork> = vec![];
{
let mut op_state = op_state_rc.borrow_mut();
let ffi_state = op_state.borrow_mut::<FfiState>();
while let Ok(Some(async_work_fut)) =
ffi_state.async_work_receiver.try_next()
{
// Move received items to a temporary vector so that we can drop the `op_state` borrow before we do the work.
work_items.push(async_work_fut);
maybe_scheduling = true;
}
if ffi_state.active_refed_functions > 0 {
maybe_scheduling = true;
}
drop(op_state);
}
while let Some(async_work_fut) = work_items.pop() {
async_work_fut();
}
maybe_scheduling
})
.state(move |state| {
// Stolen from deno_webgpu, is there a better option?
state.put(Unstable(unstable));
let (async_work_sender, async_work_receiver) =
mpsc::unbounded::<PendingFfiAsyncWork>();
state.put(FfiState {
active_refed_functions: 0,
async_work_receiver,
async_work_sender,
});
Ok(())
})
.build()
}
/// Defines the accepted types that can be used as
/// parameters and return values in FFI.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
enum NativeType {
Void,
U8,
I8,
U16,
I16,
U32,
I32,
U64,
I64,
USize,
ISize,
F32,
F64,
Pointer,
Function,
}
impl From<NativeType> for libffi::middle::Type {
fn from(native_type: NativeType) -> Self {
match native_type {
NativeType::Void => libffi::middle::Type::void(),
NativeType::U8 => libffi::middle::Type::u8(),
NativeType::I8 => libffi::middle::Type::i8(),
NativeType::U16 => libffi::middle::Type::u16(),
NativeType::I16 => libffi::middle::Type::i16(),
NativeType::U32 => libffi::middle::Type::u32(),
NativeType::I32 => libffi::middle::Type::i32(),
NativeType::U64 => libffi::middle::Type::u64(),
NativeType::I64 => libffi::middle::Type::i64(),
NativeType::USize => libffi::middle::Type::usize(),
NativeType::ISize => libffi::middle::Type::isize(),
NativeType::F32 => libffi::middle::Type::f32(),
NativeType::F64 => libffi::middle::Type::f64(),
NativeType::Pointer => libffi::middle::Type::pointer(),
NativeType::Function => libffi::middle::Type::pointer(),
}
}
}
/// Intermediate format for easy translation from NativeType + V8 value
/// to libffi argument types.
#[repr(C)]
union NativeValue {
void_value: (),
u8_value: u8,
i8_value: i8,
u16_value: u16,
i16_value: i16,
u32_value: u32,
i32_value: i32,
u64_value: u64,
i64_value: i64,
usize_value: usize,
isize_value: isize,
f32_value: f32,
f64_value: f64,
pointer: *const u8,
}
impl NativeValue {
unsafe fn as_arg(&self, native_type: NativeType) -> Arg {
match native_type {
NativeType::Void => unreachable!(),
NativeType::U8 => Arg::new(&self.u8_value),
NativeType::I8 => Arg::new(&self.i8_value),
NativeType::U16 => Arg::new(&self.u16_value),
NativeType::I16 => Arg::new(&self.i16_value),
NativeType::U32 => Arg::new(&self.u32_value),
NativeType::I32 => Arg::new(&self.i32_value),
NativeType::U64 => Arg::new(&self.u64_value),
NativeType::I64 => Arg::new(&self.i64_value),
NativeType::USize => Arg::new(&self.usize_value),
NativeType::ISize => Arg::new(&self.isize_value),
NativeType::F32 => Arg::new(&self.f32_value),
NativeType::F64 => Arg::new(&self.f64_value),
NativeType::Pointer | NativeType::Function => Arg::new(&self.pointer),
}
}
// SAFETY: native_type must correspond to the type of value represented by the union field
unsafe fn to_value(&self, native_type: NativeType) -> Value {
match native_type {
NativeType::Void => Value::Null,
NativeType::U8 => Value::from(self.u8_value),
NativeType::I8 => Value::from(self.i8_value),
NativeType::U16 => Value::from(self.u16_value),
NativeType::I16 => Value::from(self.i16_value),
NativeType::U32 => Value::from(self.u32_value),
NativeType::I32 => Value::from(self.i32_value),
NativeType::U64 => {
let value = self.u64_value;
if value > MAX_SAFE_INTEGER as u64 {
json!(U32x2::from(self.u64_value))
} else {
Value::from(value)
}
}
NativeType::I64 => {
let value = self.i64_value;
if value > MAX_SAFE_INTEGER as i64 || value < MIN_SAFE_INTEGER as i64 {
json!(U32x2::from(self.i64_value as u64))
} else {
Value::from(value)
}
}
NativeType::USize => {
let value = self.usize_value;
if value > MAX_SAFE_INTEGER as usize {
json!(U32x2::from(self.usize_value as u64))
} else {
Value::from(value)
}
}
NativeType::ISize => {
let value = self.isize_value;
if value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER {
json!(U32x2::from(self.isize_value as u64))
} else {
Value::from(value)
}
}
NativeType::F32 => Value::from(self.f32_value),
NativeType::F64 => Value::from(self.f64_value),
NativeType::Pointer | NativeType::Function => {
let value = self.pointer as usize;
if value > MAX_SAFE_INTEGER as usize {
json!(U32x2::from(value as u64))
} else {
Value::from(value)
}
}
}
}
// SAFETY: native_type must correspond to the type of value represented by the union field
#[inline]
unsafe fn to_v8<'scope>(
&self,
scope: &mut v8::HandleScope<'scope>,
native_type: NativeType,
) -> serde_v8::Value<'scope> {
match native_type {
NativeType::Void => {
let local_value: v8::Local<v8::Value> = v8::undefined(scope).into();
local_value.into()
}
NativeType::U8 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new_from_unsigned(scope, self.u8_value as u32).into();
local_value.into()
}
NativeType::I8 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new(scope, self.i8_value as i32).into();
local_value.into()
}
NativeType::U16 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new_from_unsigned(scope, self.u16_value as u32).into();
local_value.into()
}
NativeType::I16 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new(scope, self.i16_value as i32).into();
local_value.into()
}
NativeType::U32 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new_from_unsigned(scope, self.u32_value).into();
local_value.into()
}
NativeType::I32 => {
let local_value: v8::Local<v8::Value> =
v8::Integer::new(scope, self.i32_value).into();
local_value.into()
}
NativeType::U64 => {
let value = self.u64_value;
let local_value: v8::Local<v8::Value> =
if value > MAX_SAFE_INTEGER as u64 {
v8::BigInt::new_from_u64(scope, value).into()
} else {
v8::Number::new(scope, value as f64).into()
};
local_value.into()
}
NativeType::I64 => {
let value = self.i64_value;
let local_value: v8::Local<v8::Value> =
if value > MAX_SAFE_INTEGER as i64 || value < MIN_SAFE_INTEGER as i64
{
v8::BigInt::new_from_i64(scope, self.i64_value).into()
} else {
v8::Number::new(scope, value as f64).into()
};
local_value.into()
}
NativeType::USize => {
let value = self.usize_value;
let local_value: v8::Local<v8::Value> =
if value > MAX_SAFE_INTEGER as usize {
v8::BigInt::new_from_u64(scope, value as u64).into()
} else {
v8::Number::new(scope, value as f64).into()
};
local_value.into()
}
NativeType::ISize => {
let value = self.isize_value;
let local_value: v8::Local<v8::Value> =
if value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER {
v8::BigInt::new_from_i64(scope, self.isize_value as i64).into()
} else {
v8::Number::new(scope, value as f64).into()
};
local_value.into()
}
NativeType::F32 => {
let local_value: v8::Local<v8::Value> =
v8::Number::new(scope, self.f32_value as f64).into();
local_value.into()
}
NativeType::F64 => {
let local_value: v8::Local<v8::Value> =
v8::Number::new(scope, self.f64_value).into();
local_value.into()
}
NativeType::Pointer | NativeType::Function => {
let value = self.pointer as u64;
let local_value: v8::Local<v8::Value> =
if value > MAX_SAFE_INTEGER as u64 {
v8::BigInt::new_from_u64(scope, value).into()
} else {
v8::Number::new(scope, value as f64).into()
};
local_value.into()
}
}
}
}
unsafe impl Send for NativeValue {}
#[derive(Serialize, Debug, Clone, Copy)]
struct U32x2(u32, u32);
impl From<u64> for U32x2 {
fn from(value: u64) -> Self {
Self((value >> 32) as u32, value as u32)
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ForeignFunction {
name: Option<String>,
parameters: Vec<NativeType>,
result: NativeType,
#[serde(rename = "nonblocking")]
non_blocking: Option<bool>,
#[serde(rename = "callback")]
#[serde(default = "default_callback")]
callback: bool,
}
fn default_callback() -> bool {
false
}
// ForeignStatic's name and type fields are read and used by
// serde_v8 to determine which variant a ForeignSymbol is.
// They are not used beyond that and are thus marked with underscores.
#[derive(Deserialize, Debug)]
struct ForeignStatic {
#[serde(rename(deserialize = "name"))]
_name: Option<String>,
#[serde(rename(deserialize = "type"))]
_type: String,
}
#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum ForeignSymbol {
ForeignFunction(ForeignFunction),
ForeignStatic(ForeignStatic),
}
#[derive(Deserialize, Debug)]
struct FfiLoadArgs {
path: String,
symbols: HashMap<String, ForeignSymbol>,
}
// `path` is only used on Windows.
#[allow(unused_variables)]
pub(crate) fn format_error(e: dlopen::Error, path: String) -> String {
match e {
#[cfg(target_os = "windows")]
// This calls FormatMessageW with library path
// as replacement for the insert sequences.
// Unlike libstd which passes the FORMAT_MESSAGE_IGNORE_INSERTS
// flag without any arguments.
//
// https://github.com/denoland/deno/issues/11632
dlopen::Error::OpeningLibraryError(e) => {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::winbase::FormatMessageW;
use winapi::um::winbase::FORMAT_MESSAGE_ARGUMENT_ARRAY;
use winapi::um::winbase::FORMAT_MESSAGE_FROM_SYSTEM;
use winapi::um::winnt::LANG_SYSTEM_DEFAULT;
use winapi::um::winnt::MAKELANGID;
use winapi::um::winnt::SUBLANG_SYS_DEFAULT;
let err_num = match e.raw_os_error() {
Some(err_num) => err_num,
// This should never hit unless dlopen changes its error type.
None => return e.to_string(),
};
// Language ID (0x0800)
let lang_id =
MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) as DWORD;
let mut buf = vec![0; 500];
let path = OsStr::new(&path)
.encode_wide()
.chain(Some(0).into_iter())
.collect::<Vec<_>>();
let arguments = [path.as_ptr()];
loop {
// SAFETY:
// winapi call to format the error message
let length = unsafe {
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
std::ptr::null_mut(),
err_num as DWORD,
lang_id as DWORD,
buf.as_mut_ptr(),
buf.len() as DWORD,
arguments.as_ptr() as _,
)
};
if length == 0 {
// SAFETY:
// winapi call to get the last error message
let err_num = unsafe { GetLastError() };
if err_num == ERROR_INSUFFICIENT_BUFFER {
buf.resize(buf.len() * 2, 0);
continue;
}
// Something went wrong, just return the original error.
return e.to_string();
}
let msg = String::from_utf16_lossy(&buf[..length as usize]);
return msg;
}
}
_ => e.to_string(),
}
}
#[op(v8)]
fn op_ffi_load<FP, 'scope>(
scope: &mut v8::HandleScope<'scope>,
state: &mut deno_core::OpState,
args: FfiLoadArgs,
) -> Result<(ResourceId, serde_v8::Value<'scope>), AnyError>
where
FP: FfiPermissions + 'static,
{
let path = args.path;
check_unstable(state, "Deno.dlopen");
let permissions = state.borrow_mut::<FP>();
permissions.check(Some(&PathBuf::from(&path)))?;
let lib = Library::open(&path).map_err(|e| {
dlopen::Error::OpeningLibraryError(std::io::Error::new(
std::io::ErrorKind::Other,
format_error(e, path),
))
})?;
let mut resource = DynamicLibraryResource {
lib,
symbols: HashMap::new(),
};
let obj = v8::Object::new(scope);
for (symbol_key, foreign_symbol) in args.symbols {
match foreign_symbol {
ForeignSymbol::ForeignStatic(_) => {
// No-op: Statics will be handled separately and are not part of the Rust-side resource.
}
ForeignSymbol::ForeignFunction(foreign_fn) => {
let symbol = match &foreign_fn.name {
Some(symbol) => symbol,
None => &symbol_key,
};
// By default, Err returned by this function does not tell
// which symbol wasn't exported. So we'll modify the error
// message to include the name of symbol.
let fn_ptr =
// SAFETY: The obtained T symbol is the size of a pointer.
match unsafe { resource.lib.symbol::<*const c_void>(symbol) } {
Ok(value) => Ok(value),
Err(err) => Err(generic_error(format!(
"Failed to register symbol {}: {}",
symbol, err
))),
}?;
let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _);
let cif = libffi::middle::Cif::new(
foreign_fn
.parameters
.clone()
.into_iter()
.map(libffi::middle::Type::from),
foreign_fn.result.into(),
);
let func_key = v8::String::new(scope, &symbol_key).unwrap();
let sym = Box::new(Symbol {
cif,
ptr,
parameter_types: foreign_fn.parameters,
result_type: foreign_fn.result,
can_callback: foreign_fn.callback,
});
resource.symbols.insert(symbol_key, sym.clone());
match foreign_fn.non_blocking {
// Generate functions for synchronous calls.
Some(false) | None => {
let function = make_sync_fn(scope, sym);
obj.set(scope, func_key.into(), function.into());
}
// This optimization is not yet supported for non-blocking calls.
_ => {}
};
}
}
}
let rid = state.resource_table.add(resource);
Ok((
rid,
serde_v8::Value {
v8_value: obj.into(),
},
))
}
pub struct FfiFastCallTemplate {
args: Box<[fast_api::Type]>,
ret: fast_api::CType,
symbol_ptr: *const c_void,
}
impl fast_api::FastFunction for FfiFastCallTemplate {
fn function(&self) -> *const c_void {
self.symbol_ptr
}
fn args(&self) -> &'static [fast_api::Type] {
Box::leak(self.args.clone())
}
fn return_type(&self) -> fast_api::CType {
self.ret
}
}
impl From<&NativeType> for fast_api::Type {
fn from(native_type: &NativeType) -> Self {
match native_type {
NativeType::U8 | NativeType::U16 | NativeType::U32 => {
fast_api::Type::Uint32
}
NativeType::I8 | NativeType::I16 | NativeType::I32 => {
fast_api::Type::Int32
}
NativeType::F32 => fast_api::Type::Float32,
NativeType::F64 => fast_api::Type::Float64,
NativeType::Void => fast_api::Type::Void,
NativeType::I64 => fast_api::Type::Int64,
NativeType::U64 => fast_api::Type::Uint64,
NativeType::ISize => fast_api::Type::Int64,
NativeType::USize | NativeType::Function | NativeType::Pointer => {
fast_api::Type::Uint64
}
}
}
}
#[cfg(not(target_os = "windows"))]
fn is_fast_api_rv(rv: NativeType) -> bool {
!matches!(
rv,
NativeType::Function
| NativeType::Pointer
| NativeType::I64
| NativeType::ISize
| NativeType::U64
| NativeType::USize
)
}
// Create a JavaScript function for synchronous FFI call to
// the given symbol.
fn make_sync_fn<'s>(
scope: &mut v8::HandleScope<'s>,
sym: Box<Symbol>,
) -> v8::Local<'s, v8::Function> {
#[cfg(not(target_os = "windows"))]
let mut fast_ffi_templ: Option<FfiFastCallTemplate> = None;
#[cfg(target_os = "windows")]
let fast_ffi_templ: Option<FfiFastCallTemplate> = None;
#[cfg(not(target_os = "windows"))]
let mut fast_allocations: Option<*mut ()> = None;
#[cfg(not(target_os = "windows"))]
if !sym.can_callback && is_fast_api_rv(sym.result_type) {
let ret = fast_api::Type::from(&sym.result_type);
let mut args = sym
.parameter_types
.iter()
.map(|t| t.into())
.collect::<Vec<_>>();
// recv
args.insert(0, fast_api::Type::V8Value);
let symbol_trampoline =
jit_trampoline::gen_trampoline(sym.clone()).expect("gen_trampoline");
fast_ffi_templ = Some(FfiFastCallTemplate {
args: args.into_boxed_slice(),
ret: (&ret).into(),
symbol_ptr: symbol_trampoline.addr,
});
fast_allocations = Some(Box::into_raw(symbol_trampoline) as *mut ());
}
let sym = Box::leak(sym);
let builder = v8::FunctionTemplate::builder(
|scope: &mut v8::HandleScope,
args: v8::FunctionCallbackArguments,
mut rv: v8::ReturnValue| {
let external: v8::Local<v8::External> =
args.data().unwrap().try_into().unwrap();
// SAFETY: The pointer will not be deallocated until the function is
// garbage collected.
let symbol = unsafe { &*(external.value() as *const Symbol) };
match ffi_call_sync(scope, args, symbol) {
Ok(result) => {
// SAFETY: Same return type declared to libffi; trust user to have it right beyond that.
let result = unsafe { result.to_v8(scope, symbol.result_type) };
rv.set(result.v8_value);
}
Err(err) => {
deno_core::_ops::throw_type_error(scope, err.to_string());
}
};
},
)
.data(v8::External::new(scope, sym as *mut Symbol as *mut _).into());
let func = if let Some(fast_ffi_templ) = fast_ffi_templ {
builder.build_fast(scope, &fast_ffi_templ, None)
} else {
builder.build(scope)
};
let func = func.get_function(scope).unwrap();
let weak = v8::Weak::with_finalizer(
scope,
func,
Box::new(move |_| {
// SAFETY: This is never called twice. pointer obtained
// from Box::into_raw, hence, satisfies memory layout requirements.
unsafe {
Box::from_raw(sym);
#[cfg(not(target_os = "windows"))]
if let Some(fast_allocations) = fast_allocations {
Box::from_raw(fast_allocations as *mut jit_trampoline::Allocation);
}
}
}),
);
weak.to_local(scope).unwrap()
}
#[inline]
fn ffi_parse_u8_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let u8_value = v8::Local::<v8::Uint32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI u8 type, expected unsigned integer"))?
.value() as u8;
Ok(NativeValue { u8_value })
}
#[inline]
fn ffi_parse_i8_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let i8_value = v8::Local::<v8::Int32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI i8 type, expected integer"))?
.value() as i8;
Ok(NativeValue { i8_value })
}
#[inline]
fn ffi_parse_u16_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let u16_value = v8::Local::<v8::Uint32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI u16 type, expected unsigned integer"))?
.value() as u16;
Ok(NativeValue { u16_value })
}
#[inline]
fn ffi_parse_i16_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let i16_value = v8::Local::<v8::Int32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI i16 type, expected integer"))?
.value() as i16;
Ok(NativeValue { i16_value })
}
#[inline]
fn ffi_parse_u32_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let u32_value = v8::Local::<v8::Uint32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI u32 type, expected unsigned integer"))?
.value() as u32;
Ok(NativeValue { u32_value })
}
#[inline]
fn ffi_parse_i32_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let i32_value = v8::Local::<v8::Int32>::try_from(arg)
.map_err(|_| type_error("Invalid FFI i32 type, expected integer"))?
.value() as i32;
Ok(NativeValue { i32_value })
}
#[inline]
fn ffi_parse_u64_arg(
scope: &mut v8::HandleScope,
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
// Order of checking:
// 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case.
// 2. Number: Common, supported by Fast API, so let that be the optimal case.
let u64_value: u64 = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg)
{
value.u64_value().0
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) {
value.integer_value(scope).unwrap() as u64
} else {
return Err(type_error(
"Invalid FFI u64 type, expected unsigned integer",
));
};
Ok(NativeValue { u64_value })
}
#[inline]
fn ffi_parse_i64_arg(
scope: &mut v8::HandleScope,
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
// Order of checking:
// 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case.
// 2. Number: Common, supported by Fast API, so let that be the optimal case.
let i64_value: i64 = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg)
{
value.i64_value().0
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) {
value.integer_value(scope).unwrap() as i64
} else {
return Err(type_error("Invalid FFI i64 type, expected integer"));
};
Ok(NativeValue { i64_value })
}
#[inline]
fn ffi_parse_usize_arg(
scope: &mut v8::HandleScope,
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
// Order of checking:
// 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case.
// 2. Number: Common, supported by Fast API, so let that be the optimal case.
let usize_value: usize =
if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) {
value.u64_value().0 as usize
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) {
value.integer_value(scope).unwrap() as usize
} else {
return Err(type_error("Invalid FFI usize type, expected integer"));
};
Ok(NativeValue { usize_value })
}
#[inline]
fn ffi_parse_isize_arg(
scope: &mut v8::HandleScope,
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
// Order of checking:
// 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case.
// 2. Number: Common, supported by Fast API, so let that be the optimal case.
let isize_value: isize =
if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) {
value.i64_value().0 as isize
} else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) {
value.integer_value(scope).unwrap() as isize
} else {
return Err(type_error("Invalid FFI isize type, expected integer"));
};
Ok(NativeValue { isize_value })
}
#[inline]
fn ffi_parse_f32_arg(
arg: v8::Local<v8::Value>,
) -> Result<NativeValue, AnyError> {
let f32_value = v8::Local::<v8::Number>::try_from(arg)
.map_err(|_| type_error("Invalid FFI f32 type, expected number"))?
.value() as f32;
Ok(NativeValue { f32_value })
}