-
Notifications
You must be signed in to change notification settings - Fork 826
/
function.rs
1261 lines (1121 loc) · 43.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;
pub use inner::{FromToNativeWasmType, HostFunction, WasmTypeList, WithEnv, WithoutEnv};
use std::cell::RefCell;
use std::cmp::max;
use std::fmt;
use wasmer_vm::{
raise_user_trap, resume_panic, wasmer_call_trampoline, Export, ExportFunction,
VMCallerCheckedAnyfunc, VMContext, VMDynamicFunctionContext, VMFunctionBody, VMFunctionKind,
VMTrampoline,
};
/// A function defined in the Wasm module
#[derive(Clone, PartialEq)]
pub struct WasmFunctionDefinition {
// 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
#[derive(Clone, PartialEq)]
pub struct Function {
pub(crate) store: Store,
pub(crate) definition: FunctionDefinition,
pub(crate) exported: ExportFunction,
}
impl Function {
/// Creates a new host `Function` (dynamic) with the provided signature.
///
/// # Example
///
/// ```
/// # 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)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new<F>(store: &Store, ty: &FunctionType, func: F) -> Self
where
F: Fn(&[Val]) -> Result<Vec<Val>, RuntimeError> + 'static,
{
let dynamic_ctx = VMDynamicFunctionContext::from_context(VMDynamicFunctionWithoutEnv {
func: Box::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 vmctx = Box::into_raw(Box::new(dynamic_ctx)) as *mut VMContext;
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction {
address,
kind: VMFunctionKind::Dynamic,
vmctx,
signature: ty.clone(),
},
}
}
/// Creates a new host `Function` (dynamic) with the provided signature and environment.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
///
/// 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)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new_with_env<F, Env>(store: &Store, ty: &FunctionType, env: Env, func: F) -> Self
where
F: Fn(&mut Env, &[Val]) -> Result<Vec<Val>, RuntimeError> + 'static,
Env: Sized + 'static,
{
let dynamic_ctx = VMDynamicFunctionContext::from_context(VMDynamicFunctionWithEnv {
env: RefCell::new(env),
func: Box::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 vmctx = Box::into_raw(Box::new(dynamic_ctx)) as *mut VMContext;
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction {
address,
kind: VMFunctionKind::Dynamic,
vmctx,
signature: ty.clone(),
},
}
}
/// 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,
{
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address() as *const VMFunctionBody;
let vmctx = std::ptr::null_mut() as *mut _ as *mut VMContext;
let signature = function.ty();
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: false }),
exported: ExportFunction {
address,
vmctx,
signature,
kind: VMFunctionKind::Static,
},
}
}
/// 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};
/// # let store = Store::default();
///
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// fn sum_and_multiply(env: &mut 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 + 'static,
{
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address();
// TODO: We need to refactor the Function context.
// Right now is structured as it's always a `VMContext`. However, only
// Wasm-defined functions have a `VMContext`.
// In the case of Host-defined functions `VMContext` is whatever environment
// the user want to attach to the function.
let box_env = Box::new(env);
let vmctx = Box::into_raw(box_env) as *mut _ as *mut VMContext;
let signature = function.ty();
Self {
store: store.clone(),
definition: FunctionDefinition::Host(HostFunctionDefinition { has_env: true }),
exported: ExportFunction {
address,
kind: VMFunctionKind::Static,
vmctx,
signature,
},
}
}
/// Returns the [`FunctionType`] of the `Function`.
pub fn ty(&self) -> &FunctionType {
&self.exported.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.vmctx,
func.trampoline,
self.exported.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.
pub fn param_arity(&self) -> usize {
self.ty().params().len()
}
/// Returns the number of results this function produces.
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.
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_export(store: &Store, wasmer_export: ExportFunction) -> Self {
let vmsignature = store.engine().register_signature(&wasmer_export.signature);
let trampoline = store
.engine()
.function_call_trampoline(vmsignature)
.expect("Can't get call trampoline for the function");
Self {
store: store.clone(),
definition: FunctionDefinition::Wasm(WasmFunctionDefinition { trampoline }),
exported: wasmer_export,
}
}
pub(crate) fn checked_anyfunc(&self) -> VMCallerCheckedAnyfunc {
let vmsignature = self
.store
.engine()
.register_signature(&self.exported.signature);
VMCallerCheckedAnyfunc {
func_ptr: self.exported.address,
type_index: vmsignature,
vmctx: self.exported.vmctx,
}
}
/// Transform this WebAssembly function into a function with the
/// native ABI. See `NativeFunc` to learn more.
pub fn native<'a, Args, Rets>(&self) -> Result<NativeFunc<'a, Args, Rets>, RuntimeError>
where
Args: WasmTypeList,
Rets: WasmTypeList,
{
// type check
{
let expected = self.exported.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.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.address,
self.exported.vmctx,
self.exported.kind,
self.definition.clone(),
))
}
}
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 {
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError>;
fn function_type(&self) -> &FunctionType;
}
pub(crate) struct VMDynamicFunctionWithoutEnv {
#[allow(clippy::type_complexity)]
func: Box<dyn Fn(&[Val]) -> Result<Vec<Val>, RuntimeError> + 'static>,
function_type: FunctionType,
}
impl VMDynamicFunction for VMDynamicFunctionWithoutEnv {
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError> {
(*self.func)(&args)
}
fn function_type(&self) -> &FunctionType {
&self.function_type
}
}
pub(crate) struct VMDynamicFunctionWithEnv<Env>
where
Env: Sized + 'static,
{
function_type: FunctionType,
#[allow(clippy::type_complexity)]
func: Box<dyn Fn(&mut Env, &[Val]) -> Result<Vec<Val>, RuntimeError> + 'static>,
env: RefCell<Env>,
}
impl<Env> VMDynamicFunction for VMDynamicFunctionWithEnv<Env>
where
Env: Sized + 'static,
{
fn call(&self, args: &[Val]) -> Result<Vec<Val>, RuntimeError> {
// TODO: the `&mut *self.env.as_ptr()` is likely invoking some "mild"
// undefined behavior due to how it's used in the static fn call
unsafe { (*self.func)(&mut *self.env.as_ptr(), &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 wasm_common::{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 splitted into two traits:
/// `FromNativeWasmType` and `ToNativeWasmType` but it creates a
/// non-negligeable 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.try_into().expect(concat!(
"out of range type conversion attempt (tried to convert `",
stringify!($native_type),
"` to `",
stringify!($type),
"`)",
))
}
#[inline]
fn to_native(self) -> Self::Native {
self.try_into().expect(concat!(
"out of range type conversion attempt (tried to convert `",
stringify!($type),
"` to `",
stringify!($native_type),
"`)",
))
}
}
)*
};
}
from_to_native_wasm_type!(
i8 => i32,
u8 => i32,
i16 => i32,
u16 => i32,
i32 => i32,
u32 => i32,
i64 => i64,
u64 => i64,
f32 => f32,
f64 => f64
);
#[cfg(test)]
mod test_from_to_native_wasm_type {
use super::*;
#[test]
fn test_to_native() {
assert_eq!(7i8.to_native(), 7i32);
}
#[test]
#[should_panic(
expected = "out of range type conversion attempt (tried to convert `u32` to `i32`)"
)]
fn test_to_native_panics() {
use std::{i32, u32};
assert_eq!(u32::MAX.to_native(), i32::MAX);
}
}
/// The `WasmTypeList` trait represents a tuple (list) of Wasm
/// typed values. It is used to get low-level representation of
/// such a tuple.
pub trait WasmTypeList
where
Self: Sized,
{
/// The C type (a struct) that can hold/represent all the
/// represented values.
type CStruct;
/// The array type that can hold all the represented values.
///
/// Note that all values are stored in their binary form.
type Array: AsMut<[i128]>;
/// Constructs `Self` based on an array of values.
fn from_array(array: Self::Array) -> Self;
/// Constructs `Self` based on a slice of values.
///
/// `from_slice` returns a `Result` because it is possible
/// that the slice doesn't have the same size than
/// `Self::Array`, in which circumstance an error of kind
/// `TryFromSliceError` will be returned.
fn from_slice(slice: &[i128]) -> Result<Self, TryFromSliceError>;
/// Builds and returns an array of type `Array` from a tuple
/// (list) of values.
fn into_array(self) -> Self::Array;
/// Allocates and return an empty array of type `Array` that
/// will hold a tuple (list) of values, usually to hold the
/// returned values of a WebAssembly function call.
fn empty_array() -> Self::Array;
/// Builds a tuple (list) of values from a C struct of type
/// `CStruct`.
fn from_c_struct(c_struct: Self::CStruct) -> Self;
/// Builds and returns a C struct of type `CStruct` from a
/// tuple (list) of values.
fn into_c_struct(self) -> Self::CStruct;
/// Get the Wasm types for the tuple (list) of currently
/// represented values.
fn wasm_types() -> &'static [Type];
}
/// The `IntoResult` trait turns a `WasmTypeList` into a
/// `Result<WasmTypeList, Self::Error>`.
///
/// It is mostly used to turn result values of a Wasm function
/// call into a `Result`.
pub trait IntoResult<T>
where
T: WasmTypeList,
{
/// The error type for this trait.
type Error: Error + Sync + Send + 'static;
/// Transforms `Self` into a `Result`.
fn into_result(self) -> Result<T, Self::Error>;
}
impl<T> IntoResult<T> for T
where
T: WasmTypeList,
{
// `T` is not a `Result`, it's already a value, so no error
// can be built.
type Error = Infallible;
fn into_result(self) -> Result<Self, Infallible> {
Ok(self)
}
}
impl<T, E> IntoResult<T> for Result<T, E>
where
T: WasmTypeList,
E: Error + Sync + Send + 'static,
{
type Error = E;
fn into_result(self) -> Self {
self
}
}
#[cfg(test)]
mod test_into_result {
use super::*;
use std::convert::Infallible;
#[test]
fn test_into_result_over_t() {
let x: i32 = 42;
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x.unwrap(), x);
}
#[test]
fn test_into_result_over_result() {
{
let x: Result<i32, Infallible> = Ok(42);
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x, x);
}
{
use std::{error, fmt};
#[derive(Debug, PartialEq)]
struct E;
impl fmt::Display for E {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "E")
}
}
impl error::Error for E {}
let x: Result<Infallible, E> = Err(E);
let result_of_x: Result<Infallible, E> = x.into_result();
assert_eq!(result_of_x.unwrap_err(), E);
}
}
}
/// The `HostFunction` trait represents the set of functions that
/// can be used as host function. To uphold this statement, it is
/// necessary for a function to be transformed into a pointer to
/// `VMFunctionBody`.
pub trait HostFunction<Args, Rets, Kind, T>
where
Args: WasmTypeList,
Rets: WasmTypeList,
Kind: HostFunctionKind,
T: Sized,
Self: Sized,
{
/// Get the pointer to the function body.
fn function_body_ptr(self) -> *const VMFunctionBody;
}
/// Empty trait to specify the kind of `HostFunction`: With or
/// without an environment.
///
/// This trait is never aimed to be used by a user. It is used by
/// the trait system to automatically generate the appropriate
/// host functions.
#[doc(hidden)]
pub trait HostFunctionKind {}
/// An empty struct to help Rust typing to determine
/// when a `HostFunction` does have an environment.
pub struct WithEnv;
impl HostFunctionKind for WithEnv {}
/// An empty struct to help Rust typing to determine
/// when a `HostFunction` does not have an environment.
pub struct WithoutEnv;
impl HostFunctionKind for WithoutEnv {}
/// Represents a low-level Wasm static host function. See
/// `super::Function::new` and `super::Function::new_env` to learn
/// more.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Function<Args = (), Rets = ()> {
address: *const VMFunctionBody,
_phantom: PhantomData<(Args, Rets)>,
}
unsafe impl<Args, Rets> Send for Function<Args, Rets> {}
impl<Args, Rets> Function<Args, Rets>
where
Args: WasmTypeList,
Rets: WasmTypeList,
{
/// Creates a new `Function`.
pub fn new<F, T, E>(function: F) -> Self
where
F: HostFunction<Args, Rets, T, E>,
T: HostFunctionKind,
E: Sized,
{
Self {
address: function.function_body_ptr(),
_phantom: PhantomData,
}
}
/// Get the function type of this `Function`.
pub fn ty(&self) -> FunctionType {
FunctionType::new(Args::wasm_types(), Rets::wasm_types())
}
/// Get the address of this `Function`.
pub fn address(&self) -> *const VMFunctionBody {
self.address
}
}
macro_rules! impl_host_function {
( [$c_struct_representation:ident]
$c_struct_name:ident,
$( $x:ident ),* ) => {
/// A structure with a C-compatible representation that can hold a set of Wasm values.
/// This type is used by `WasmTypeList::CStruct`.
#[repr($c_struct_representation)]
pub struct $c_struct_name< $( $x ),* > ( $( <$x as FromToNativeWasmType>::Native ),* )
where
$( $x: FromToNativeWasmType ),*;
// Implement `WasmTypeList` for a specific tuple.
#[allow(unused_parens, dead_code)]
impl< $( $x ),* >
WasmTypeList
for
( $( $x ),* )
where
$( $x: FromToNativeWasmType ),*
{
type CStruct = $c_struct_name< $( $x ),* >;
type Array = [i128; count_idents!( $( $x ),* )];
fn from_array(array: Self::Array) -> Self {
// Unpack items of the array.
#[allow(non_snake_case)]
let [ $( $x ),* ] = array;
// Build the tuple.
(
$(
FromToNativeWasmType::from_native(NativeWasmType::from_binary($x))
),*
)
}
fn from_slice(slice: &[i128]) -> Result<Self, TryFromSliceError> {
Ok(Self::from_array(slice.try_into()?))
}
fn into_array(self) -> Self::Array {
// Unpack items of the tuple.
#[allow(non_snake_case)]
let ( $( $x ),* ) = self;
// Build the array.
[
$(
FromToNativeWasmType::to_native($x).to_binary()
),*
]
}
fn empty_array() -> Self::Array {
// Build an array initialized with `0`.
[0; count_idents!( $( $x ),* )]
}
fn from_c_struct(c_struct: Self::CStruct) -> Self {
// Unpack items of the C structure.
#[allow(non_snake_case)]
let $c_struct_name( $( $x ),* ) = c_struct;
(
$(
FromToNativeWasmType::from_native($x)
),*
)
}
#[allow(unused_parens, non_snake_case)]
fn into_c_struct(self) -> Self::CStruct {
// Unpack items of the tuple.
let ( $( $x ),* ) = self;
// Build the C structure.
$c_struct_name(
$(
FromToNativeWasmType::to_native($x)
),*
)
}
fn wasm_types() -> &'static [Type] {
&[
$(
$x::Native::WASM_TYPE
),*
]
}
}
// Implement `HostFunction` for a function that has the same arity than the tuple.
// This specific function has no environment.
#[allow(unused_parens)]
impl< $( $x, )* Rets, RetsAsResult, Func >
HostFunction<( $( $x ),* ), Rets, WithoutEnv, ()>
for
Func
where
$( $x: FromToNativeWasmType, )*
Rets: WasmTypeList,
RetsAsResult: IntoResult<Rets>,
Func: Fn($( $x , )*) -> RetsAsResult + 'static + Send,
{
#[allow(non_snake_case)]
fn function_body_ptr(self) -> *const VMFunctionBody {
/// This is a function that wraps the real host
/// function. Its address will be used inside the
/// runtime.
extern fn func_wrapper<$( $x, )* Rets, RetsAsResult, Func>( _: usize, $( $x: $x::Native, )* ) -> Rets::CStruct
where
$( $x: FromToNativeWasmType, )*
Rets: WasmTypeList,
RetsAsResult: IntoResult<Rets>,
Func: Fn( $( $x ),* ) -> RetsAsResult + 'static
{
let func: &Func = unsafe { &*(&() as *const () as *const Func) };
let result = panic::catch_unwind(AssertUnwindSafe(|| {
func( $( FromToNativeWasmType::from_native($x) ),* ).into_result()
}));
match result {
Ok(Ok(result)) => return result.into_c_struct(),
Ok(Err(trap)) => unsafe { raise_user_trap(Box::new(trap)) },
Err(panic) => unsafe { resume_panic(panic) },
}
}
func_wrapper::< $( $x, )* Rets, RetsAsResult, Self > as *const VMFunctionBody
}