-
Notifications
You must be signed in to change notification settings - Fork 845
/
Copy pathfunction.rs
1716 lines (1551 loc) · 59.3 KB
/
function.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
use crate::exports::{ExportError, Exportable};
use crate::externals::Extern;
use crate::store::Store;
use crate::types::Val;
use crate::FunctionType;
use crate::NativeFunc;
use crate::RuntimeError;
use crate::WasmerEnv;
pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv};
#[cfg(feature = "deprecated")]
pub use inner::{UnsafeMutableEnv, WithUnsafeMutableEnv};
use std::cmp::max;
use std::fmt;
use std::sync::Arc;
use wasmer_engine::{Export, ExportFunction, ExportFunctionMetadata};
use wasmer_vm::{
raise_user_trap, resume_panic, wasmer_call_trampoline, VMCallerCheckedAnyfunc,
VMDynamicFunctionContext, VMExportFunction, VMFunctionBody, VMFunctionEnvironment,
VMFunctionKind, VMTrampoline,
};
/// A function defined in the Wasm module
#[derive(Clone, PartialEq)]
pub struct WasmFunctionDefinition {
// Address of the trampoline to do the call.
pub(crate) trampoline: VMTrampoline,
}
/// A function defined in the Host
#[derive(Clone, PartialEq)]
pub struct HostFunctionDefinition {
/// If the host function has a custom environment attached
pub(crate) has_env: bool,
}
/// The inner helper
#[derive(Clone, PartialEq)]
pub enum FunctionDefinition {
/// A function defined in the Wasm side
Wasm(WasmFunctionDefinition),
/// A function defined in the Host side
Host(HostFunctionDefinition),
}
/// A WebAssembly `function` instance.
///
/// A function instance is the runtime representation of a function.
/// It effectively is a closure of the original function (defined in either
/// the host or the WebAssembly module) over the runtime `Instance` of its
/// originating `Module`.
///
/// The module instance is used to resolve references to other definitions
/// during execution of the function.
///
/// Spec: <https://webassembly.github.io/spec/core/exec/runtime.html#function-instances>
///
/// # Panics
/// - Closures (functions with captured environments) are not currently supported
/// with native functions. Attempting to create a native `Function` with one will
/// result in a panic.
/// [Closures as host functions tracking issue](https://github.com/wasmerio/wasmer/issues/1840)
#[derive(Clone, PartialEq)]
pub struct Function {
pub(crate) store: Store,
pub(crate) definition: FunctionDefinition,
pub(crate) exported: ExportFunction,
}
fn build_export_function_metadata<Env>(
env: Env,
import_init_function_ptr: for<'a> fn(
&'a mut Env,
&'a crate::Instance,
) -> Result<(), crate::HostEnvInitError>,
) -> (*mut std::ffi::c_void, ExportFunctionMetadata)
where
Env: Clone + Sized + 'static + Send + Sync,
{
let import_init_function_ptr = Some(unsafe {
std::mem::transmute::<fn(_, _) -> Result<(), _>, fn(_, _) -> Result<(), _>>(
import_init_function_ptr,
)
});
let host_env_clone_fn: fn(*mut std::ffi::c_void) -> *mut std::ffi::c_void = |ptr| {
let env_ref: &Env = unsafe {
ptr.cast::<Env>()
.as_ref()
.expect("`ptr` to the environment is null when cloning it")
};
Box::into_raw(Box::new(env_ref.clone())) as _
};
let host_env_drop_fn: fn(*mut std::ffi::c_void) = |ptr| {
unsafe { Box::from_raw(ptr.cast::<Env>()) };
};
let env = Box::into_raw(Box::new(env)) as _;
// # Safety
// - All these functions work on all threads
// - The host env is `Send`.
let metadata = unsafe {
ExportFunctionMetadata::new(
env,
import_init_function_ptr,
host_env_clone_fn,
host_env_drop_fn,
)
};
(env, metadata)
}
impl Function {
/// Creates a new host `Function` (dynamic) with the provided signature.
///
/// If you know the signature of the host function at compile time,
/// consider using [`Function::new_native`] for less runtime overhead.
///
/// # Examples
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// #
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
///
/// let f = Function::new(&store, &signature, |args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
/// ```
///
/// With constant signature:
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// #
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
///
/// let f = Function::new(&store, I32_I32_TO_I32, |args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new<FT, F>(store: &Store, ty: FT, func: F) -> Self
where
FT: Into<FunctionType>,
F: Fn(&[Val]) -> Result<Vec<Val>, RuntimeError> + 'static + Send + Sync,
{
let ty: FunctionType = ty.into();
let dynamic_ctx: VMDynamicFunctionContext<DynamicFunctionWithoutEnv> =
VMDynamicFunctionContext::from_context(DynamicFunctionWithoutEnv {
func: Arc::new(func),
function_type: ty.clone(),
});
// We don't yet have the address with the Wasm ABI signature.
// The engine linker will replace the address with one pointing to a
// generated dynamic trampoline.
let address = std::ptr::null() as *const VMFunctionBody;
let host_env = Box::into_raw(Box::new(dynamic_ctx)) as *mut _;
let vmctx = VMFunctionEnvironment { host_env };
let host_env_clone_fn: fn(*mut std::ffi::c_void) -> *mut std::ffi::c_void = |ptr| {
let duped_env: VMDynamicFunctionContext<DynamicFunctionWithoutEnv> = unsafe {
let ptr: *mut VMDynamicFunctionContext<DynamicFunctionWithoutEnv> = ptr as _;
let item: &VMDynamicFunctionContext<DynamicFunctionWithoutEnv> = &*ptr;
item.clone()
};
Box::into_raw(Box::new(duped_env)) as _
};
let host_env_drop_fn: fn(*mut std::ffi::c_void) = |ptr: *mut std::ffi::c_void| {
unsafe {
Box::from_raw(ptr as *mut VMDynamicFunctionContext<DynamicFunctionWithoutEnv>)
};
};
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction {
metadata: Some(Arc::new(
// # Safety
// - All these functions work on all threads
// - The host env is `Send`.
unsafe {
ExportFunctionMetadata::new(
host_env,
None,
host_env_clone_fn,
host_env_drop_fn,
)
},
)),
vm_function: VMExportFunction {
address,
kind: VMFunctionKind::Dynamic,
vmctx,
signature: ty,
call_trampoline: None,
instance_ref: None,
},
},
}
}
/// Creates a new host `Function` (dynamic) with the provided signature and environment.
///
/// If you know the signature of the host function at compile time,
/// consider using [`Function::new_native_with_env`] for less runtime
/// overhead.
///
/// # Examples
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value, WasmerEnv};
/// # let store = Store::default();
/// #
/// #[derive(WasmerEnv, Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
///
/// let f = Function::new_with_env(&store, &signature, env, |env, args| {
/// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
/// Ok(vec![Value::I32(result)])
/// });
/// ```
///
/// With constant signature:
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value, WasmerEnv};
/// # let store = Store::default();
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
///
/// #[derive(WasmerEnv, Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// let f = Function::new_with_env(&store, I32_I32_TO_I32, env, |env, args| {
/// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
/// Ok(vec![Value::I32(result)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new_with_env<FT, F, Env>(store: &Store, ty: FT, env: Env, func: F) -> Self
where
FT: Into<FunctionType>,
F: Fn(&Env, &[Val]) -> Result<Vec<Val>, RuntimeError> + 'static + Send + Sync,
Env: Sized + WasmerEnv + 'static,
{
let ty: FunctionType = ty.into();
let dynamic_ctx: VMDynamicFunctionContext<DynamicFunctionWithEnv<Env>> =
VMDynamicFunctionContext::from_context(DynamicFunctionWithEnv {
env: Box::new(env),
func: Arc::new(func),
function_type: ty.clone(),
});
let import_init_function_ptr: for<'a> fn(&'a mut _, &'a _) -> Result<(), _> =
|env: &mut VMDynamicFunctionContext<DynamicFunctionWithEnv<Env>>,
instance: &crate::Instance| {
Env::init_with_instance(&mut *env.ctx.env, instance)
};
let (host_env, metadata) = build_export_function_metadata::<
VMDynamicFunctionContext<DynamicFunctionWithEnv<Env>>,
>(dynamic_ctx, import_init_function_ptr);
// We don't yet have the address with the Wasm ABI signature.
// The engine linker will replace the address with one pointing to a
// generated dynamic trampoline.
let address = std::ptr::null() as *const VMFunctionBody;
let vmctx = VMFunctionEnvironment { host_env };
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction {
metadata: Some(Arc::new(metadata)),
vm_function: VMExportFunction {
address,
kind: VMFunctionKind::Dynamic,
vmctx,
signature: ty,
call_trampoline: None,
instance_ref: None,
},
},
}
}
/// Creates a new host `Function` from a native function.
///
/// The function signature is automatically retrieved using the
/// Rust typing system.
///
/// # Example
///
/// ```
/// # use wasmer::{Store, Function};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// ```
pub fn new_native<F, Args, Rets, Env>(store: &Store, func: F) -> Self
where
F: HostFunction<Args, Rets, WithoutEnv, Env>,
Args: WasmTypeList,
Rets: WasmTypeList,
Env: Sized + 'static,
{
if std::mem::size_of::<F>() != 0 {
Self::closures_unsupported_panic();
}
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address() as *const VMFunctionBody;
let vmctx = VMFunctionEnvironment {
host_env: std::ptr::null_mut() as *mut _,
};
let signature = function.ty();
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction {
// TODO: figure out what's going on in this function: it takes an `Env`
// param but also marks itself as not having an env
metadata: None,
vm_function: VMExportFunction {
address,
vmctx,
signature,
kind: VMFunctionKind::Static,
call_trampoline: None,
instance_ref: None,
},
},
}
}
/// Creates a new host `Function` from a native function and a provided environment.
///
/// The function signature is automatically retrieved using the
/// Rust typing system.
///
/// # Example
///
/// ```
/// # use wasmer::{Store, Function, WasmerEnv};
/// # let store = Store::default();
/// #
/// #[derive(WasmerEnv, Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// fn sum_and_multiply(env: &Env, a: i32, b: i32) -> i32 {
/// (a + b) * env.multiplier
/// }
///
/// let f = Function::new_native_with_env(&store, env, sum_and_multiply);
/// ```
pub fn new_native_with_env<F, Args, Rets, Env>(store: &Store, env: Env, func: F) -> Self
where
F: HostFunction<Args, Rets, WithEnv, Env>,
Args: WasmTypeList,
Rets: WasmTypeList,
Env: Sized + WasmerEnv + 'static,
{
if std::mem::size_of::<F>() != 0 {
Self::closures_unsupported_panic();
}
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address();
let (host_env, metadata) =
build_export_function_metadata::<Env>(env, Env::init_with_instance);
let vmctx = VMFunctionEnvironment { host_env };
let signature = function.ty();
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction {
metadata: Some(Arc::new(metadata)),
vm_function: VMExportFunction {
address,
kind: VMFunctionKind::Static,
vmctx,
signature,
call_trampoline: None,
instance_ref: None,
},
},
}
}
/// Function used by the deprecated API to call a function with a `&mut` Env.
///
/// This is not a stable API and may be broken at any time.
///
/// # Safety
/// - This function is only safe to use from the deprecated API.
#[doc(hidden)]
#[cfg(feature = "deprecated")]
pub unsafe fn new_native_with_unsafe_mutable_env<F, Args, Rets, Env>(
store: &Store,
env: Env,
func: F,
) -> Self
where
F: HostFunction<Args, Rets, WithUnsafeMutableEnv, Env>,
Args: WasmTypeList,
Rets: WasmTypeList,
Env: UnsafeMutableEnv + WasmerEnv + 'static,
{
if std::mem::size_of::<F>() != 0 {
Self::closures_unsupported_panic();
}
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address();
let (host_env, metadata) =
build_export_function_metadata::<Env>(env, Env::init_with_instance);
let vmctx = VMFunctionEnvironment { host_env };
let signature = function.ty();
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction {
metadata: Some(Arc::new(metadata)),
vm_function: VMExportFunction {
address,
kind: VMFunctionKind::Static,
vmctx,
signature,
call_trampoline: None,
instance_ref: None,
},
},
}
}
/// Returns the [`FunctionType`] of the `Function`.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]);
/// assert_eq!(f.ty().results(), vec![Type::I32]);
/// ```
pub fn ty(&self) -> &FunctionType {
&self.exported.vm_function.signature
}
/// Returns the [`Store`] where the `Function` belongs.
pub fn store(&self) -> &Store {
&self.store
}
fn call_wasm(
&self,
func: &WasmFunctionDefinition,
params: &[Val],
results: &mut [Val],
) -> Result<(), RuntimeError> {
let format_types_for_error_message = |items: &[Val]| {
items
.iter()
.map(|param| param.ty().to_string())
.collect::<Vec<String>>()
.join(", ")
};
let signature = self.ty();
if signature.params().len() != params.len() {
return Err(RuntimeError::new(format!(
"Parameters of type [{}] did not match signature {}",
format_types_for_error_message(params),
&signature
)));
}
if signature.results().len() != results.len() {
return Err(RuntimeError::new(format!(
"Results of type [{}] did not match signature {}",
format_types_for_error_message(results),
&signature,
)));
}
let mut values_vec = vec![0; max(params.len(), results.len())];
// Store the argument values into `values_vec`.
let param_tys = signature.params().iter();
for ((arg, slot), ty) in params.iter().zip(&mut values_vec).zip(param_tys) {
if arg.ty() != *ty {
let param_types = format_types_for_error_message(params);
return Err(RuntimeError::new(format!(
"Parameters of type [{}] did not match signature {}",
param_types, &signature,
)));
}
unsafe {
arg.write_value_to(slot);
}
}
// Call the trampoline.
if let Err(error) = unsafe {
wasmer_call_trampoline(
self.exported.vm_function.vmctx,
func.trampoline,
self.exported.vm_function.address,
values_vec.as_mut_ptr() as *mut u8,
)
} {
return Err(RuntimeError::from_trap(error));
}
// Load the return values out of `values_vec`.
for (index, &value_type) in signature.results().iter().enumerate() {
unsafe {
let ptr = values_vec.as_ptr().add(index);
results[index] = Val::read_value_from(ptr, value_type);
}
}
Ok(())
}
/// Returns the number of parameters that this function takes.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.param_arity(), 2);
/// ```
pub fn param_arity(&self) -> usize {
self.ty().params().len()
}
/// Returns the number of results this function produces.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.result_arity(), 1);
/// ```
pub fn result_arity(&self) -> usize {
self.ty().results().len()
}
/// Call the `Function` function.
///
/// Depending on where the Function is defined, it will call it.
/// 1. If the function is defined inside a WebAssembly, it will call the trampoline
/// for the function signature.
/// 2. If the function is defined in the host (in a native way), it will
/// call the trampoline.
///
/// # Examples
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
/// ```
pub fn call(&self, params: &[Val]) -> Result<Box<[Val]>, RuntimeError> {
let mut results = vec![Val::null(); self.result_arity()];
match &self.definition {
FunctionDefinition::Wasm(wasm) => {
self.call_wasm(&wasm, params, &mut results)?;
}
_ => unimplemented!("The function definition isn't supported for the moment"),
}
Ok(results.into_boxed_slice())
}
pub(crate) fn from_vm_export(store: &Store, wasmer_export: ExportFunction) -> Self {
if let Some(trampoline) = wasmer_export.vm_function.call_trampoline {
Self {
store: store.clone(),
definition: FunctionDefinition::Wasm(WasmFunctionDefinition { trampoline }),
exported: wasmer_export,
}
} else {
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition {
has_env: !wasmer_export.vm_function.vmctx.is_null(),
}),
exported: wasmer_export,
}
}
}
pub(crate) fn checked_anyfunc(&self) -> VMCallerCheckedAnyfunc {
let vmsignature = self
.store
.engine()
.register_signature(&self.exported.vm_function.signature);
VMCallerCheckedAnyfunc {
func_ptr: self.exported.vm_function.address,
type_index: vmsignature,
vmctx: self.exported.vm_function.vmctx,
}
}
/// Transform this WebAssembly function into a function with the
/// native ABI. See [`NativeFunc`] to learn more.
///
/// # Examples
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
/// let sum_native = sum.native::<(i32, i32), i32>().unwrap();
///
/// assert_eq!(sum_native.call(1, 2).unwrap(), 3);
/// ```
///
/// # Errors
///
/// If the `Args` generic parameter does not match the exported function
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i64, i64), i32>().unwrap();
/// ```
///
/// If the `Rets` generic parameter does not match the exported function
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i32, i32), i64>().unwrap();
/// ```
pub fn native<Args, Rets>(&self) -> Result<NativeFunc<Args, Rets>, RuntimeError>
where
Args: WasmTypeList,
Rets: WasmTypeList,
{
// type check
{
let expected = self.exported.vm_function.signature.params();
let given = Args::wasm_types();
if expected != given {
return Err(RuntimeError::new(format!(
"given types (`{:?}`) for the function arguments don't match the actual types (`{:?}`)",
given,
expected,
)));
}
}
{
let expected = self.exported.vm_function.signature.results();
let given = Rets::wasm_types();
if expected != given {
// todo: error result types don't match
return Err(RuntimeError::new(format!(
"given types (`{:?}`) for the function results don't match the actual types (`{:?}`)",
given,
expected,
)));
}
}
Ok(NativeFunc::new(
self.store.clone(),
self.exported.clone(),
self.definition.clone(),
))
}
#[track_caller]
fn closures_unsupported_panic() -> ! {
unimplemented!("Closures (functions with captured environments) are currently unsupported with native functions. See: https://github.com/wasmerio/wasmer/issues/1840")
}
}
impl<'a> Exportable<'a> for Function {
fn to_export(&self) -> Export {
self.exported.clone().into()
}
fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> {
match _extern {
Extern::Function(func) => Ok(func),
_ => Err(ExportError::IncompatibleType),
}
}
}
impl fmt::Debug for Function {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_struct("Function")
.field("ty", &self.ty())
.finish()
}
}
/// This trait is one that all dynamic functions must fulfill.
pub(crate) trait VMDynamicFunction: Send + Sync {
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError>;
fn function_type(&self) -> &FunctionType;
}
#[derive(Clone)]
pub(crate) struct DynamicFunctionWithoutEnv {
#[allow(clippy::type_complexity)]
func: Arc<dyn Fn(&[Val]) -> Result<Vec<Val>, RuntimeError> + 'static + Send + Sync>,
function_type: FunctionType,
}
impl VMDynamicFunction for DynamicFunctionWithoutEnv {
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError> {
(*self.func)(&args)
}
fn function_type(&self) -> &FunctionType {
&self.function_type
}
}
pub(crate) struct DynamicFunctionWithEnv<Env>
where
Env: Sized + 'static + Send + Sync,
{
function_type: FunctionType,
#[allow(clippy::type_complexity)]
func: Arc<dyn Fn(&Env, &[Val]) -> Result<Vec<Val>, RuntimeError> + 'static + Send + Sync>,
env: Box<Env>,
}
impl<Env: Sized + Clone + 'static + Send + Sync> Clone for DynamicFunctionWithEnv<Env> {
fn clone(&self) -> Self {
Self {
env: self.env.clone(),
function_type: self.function_type.clone(),
func: self.func.clone(),
}
}
}
impl<Env> VMDynamicFunction for DynamicFunctionWithEnv<Env>
where
Env: Sized + 'static + Send + Sync,
{
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError> {
(*self.func)(&*self.env, &args)
}
fn function_type(&self) -> &FunctionType {
&self.function_type
}
}
trait VMDynamicFunctionCall<T: VMDynamicFunction> {
fn from_context(ctx: T) -> Self;
fn address_ptr() -> *const VMFunctionBody;
unsafe fn func_wrapper(&self, values_vec: *mut i128);
}
impl<T: VMDynamicFunction> VMDynamicFunctionCall<T> for VMDynamicFunctionContext<T> {
fn from_context(ctx: T) -> Self {
Self {
address: Self::address_ptr(),
ctx,
}
}
fn address_ptr() -> *const VMFunctionBody {
Self::func_wrapper as *const () as *const VMFunctionBody
}
// This function wraps our func, to make it compatible with the
// reverse trampoline signature
unsafe fn func_wrapper(
// Note: we use the trick that the first param to this function is the `VMDynamicFunctionContext`
// itself, so rather than doing `dynamic_ctx: &VMDynamicFunctionContext<T>`, we simplify it a bit
&self,
values_vec: *mut i128,
) {
use std::panic::{self, AssertUnwindSafe};
let result = panic::catch_unwind(AssertUnwindSafe(|| {
let func_ty = self.ctx.function_type();
let mut args = Vec::with_capacity(func_ty.params().len());
for (i, ty) in func_ty.params().iter().enumerate() {
args.push(Val::read_value_from(values_vec.add(i), *ty));
}
let returns = self.ctx.call(&args)?;
// We need to dynamically check that the returns
// match the expected types, as well as expected length.
let return_types = returns.iter().map(|ret| ret.ty()).collect::<Vec<_>>();
if return_types != func_ty.results() {
return Err(RuntimeError::new(format!(
"Dynamic function returned wrong signature. Expected {:?} but got {:?}",
func_ty.results(),
return_types
)));
}
for (i, ret) in returns.iter().enumerate() {
ret.write_value_to(values_vec.add(i));
}
Ok(())
}));
match result {
Ok(Ok(())) => {}
Ok(Err(trap)) => raise_user_trap(Box::new(trap)),
Err(panic) => resume_panic(panic),
}
}
}
/// This private inner module contains the low-level implementation
/// for `Function` and its siblings.
mod inner {
use std::array::TryFromSliceError;
use std::convert::{Infallible, TryInto};
use std::error::Error;
use std::marker::PhantomData;
use std::panic::{self, AssertUnwindSafe};
use wasmer_types::{FunctionType, NativeWasmType, Type};
use wasmer_vm::{raise_user_trap, resume_panic, VMFunctionBody};
/// A trait to convert a Rust value to a `WasmNativeType` value,
/// or to convert `WasmNativeType` value to a Rust value.
///
/// This trait should ideally be split into two traits:
/// `FromNativeWasmType` and `ToNativeWasmType` but it creates a
/// non-negligible complexity in the `WasmTypeList`
/// implementation.
pub unsafe trait FromToNativeWasmType: Copy
where
Self: Sized,
{
/// Native Wasm type.
type Native: NativeWasmType;
/// Convert a value of kind `Self::Native` to `Self`.
///
/// # Panics
///
/// This method panics if `native` cannot fit in the `Self`
/// type`.
fn from_native(native: Self::Native) -> Self;
/// Convert self to `Self::Native`.
///
/// # Panics
///
/// This method panics if `self` cannot fit in the
/// `Self::Native` type.
fn to_native(self) -> Self::Native;
}
macro_rules! from_to_native_wasm_type {
( $( $type:ty => $native_type:ty ),* ) => {
$(
#[allow(clippy::use_self)]
unsafe impl FromToNativeWasmType for $type {
type Native = $native_type;
#[inline]
fn from_native(native: Self::Native) -> Self {
native as Self
}
#[inline]
fn to_native(self) -> Self::Native {
self as Self::Native
}
}
)*
};
}
macro_rules! from_to_native_wasm_type_same_size {
( $( $type:ty => $native_type:ty ),* ) => {
$(
#[allow(clippy::use_self)]
unsafe impl FromToNativeWasmType for $type {
type Native = $native_type;
#[inline]
fn from_native(native: Self::Native) -> Self {
Self::from_ne_bytes(Self::Native::to_ne_bytes(native))
}
#[inline]
fn to_native(self) -> Self::Native {
Self::Native::from_ne_bytes(Self::to_ne_bytes(self))