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
use crate::{FromToNativeWasmType, RuntimeError, TypedFunction, WasmTypeList};
use wasmer_types::RawValue;

use crate::native_type::NativeWasmTypeInto;
use crate::store::{AsStoreMut, AsStoreRef};
use crate::sys::engine::NativeEngineExt;

macro_rules! impl_native_traits {
    (  $( $x:ident ),* ) => {
        #[allow(unused_parens, non_snake_case)]
        impl<$( $x , )* Rets> TypedFunction<( $( $x ),* ), Rets>
        where
            $( $x: FromToNativeWasmType, )*
            Rets: WasmTypeList,
        {
            /// Call the typed func and return results.
            #[allow(unused_mut)]
            #[allow(clippy::too_many_arguments)]
            pub fn call(&self, store: &mut impl AsStoreMut, $( $x: $x, )* ) -> Result<Rets, RuntimeError> {
                let anyfunc = unsafe {
                    *self.func.0
                        .handle
                        .get(store.as_store_ref().objects())
                        .anyfunc
                        .as_ptr()
                        .as_ref()
                };
                // Ensure all parameters come from the same context.
                if $(!FromToNativeWasmType::is_from_store(&$x, store) ||)* false {
                    return Err(RuntimeError::new(
                        "cross-`Store` values are not supported",
                    ));
                }
                // TODO: when `const fn` related features mature more, we can declare a single array
                // of the correct size here.
                let mut params_list = [ $( $x.to_native().into_raw(store) ),* ];
                let mut rets_list_array = Rets::empty_array();
                let rets_list: &mut [RawValue] = rets_list_array.as_mut();
                let using_rets_array;
                let args_rets: &mut [RawValue] = if params_list.len() > rets_list.len() {
                    using_rets_array = false;
                    params_list.as_mut()
                } else {
                    using_rets_array = true;
                    for (i, &arg) in params_list.iter().enumerate() {
                        rets_list[i] = arg;
                    }
                    rets_list.as_mut()
                };

                let mut r;
                loop {
                    let storeref = store.as_store_ref();
                    let config = storeref.engine().tunables().vmconfig();
                    r = unsafe {
                        wasmer_vm::wasmer_call_trampoline(
                            store.as_store_ref().signal_handler(),
                            config,
                            anyfunc.vmctx,
                            anyfunc.call_trampoline,
                            anyfunc.func_ptr,
                            args_rets.as_mut_ptr() as *mut u8,
                        )
                    };
                    let store_mut = store.as_store_mut();
                    if let Some(callback) = store_mut.inner.on_called.take() {
                        match callback(store_mut) {
                            Ok(wasmer_types::OnCalledAction::InvokeAgain) => { continue; }
                            Ok(wasmer_types::OnCalledAction::Finish) => { break; }
                            Ok(wasmer_types::OnCalledAction::Trap(trap)) => { return Err(RuntimeError::user(trap)) },
                            Err(trap) => { return Err(RuntimeError::user(trap)) },
                        }
                    }
                    break;
                }
                r?;

                let num_rets = rets_list.len();
                if !using_rets_array && num_rets > 0 {
                    let src_pointer = params_list.as_ptr();
                    let rets_list = &mut rets_list_array.as_mut()[0] as *mut RawValue;
                    unsafe {
                        // TODO: we can probably remove this copy by doing some clever `transmute`s.
                        // we know it's not overlapping because `using_rets_array` is false
                        std::ptr::copy_nonoverlapping(src_pointer,
                                                        rets_list,
                                                        num_rets);
                    }
                }
                Ok(unsafe { Rets::from_array(store, rets_list_array) })
                // TODO: When the Host ABI and Wasm ABI are the same, we could do this instead:
                // but we can't currently detect whether that's safe.
                //
                // let results = unsafe {
                //     wasmer_vm::catch_traps_with_result(self.vmctx, || {
                //         let f = std::mem::transmute::<_, unsafe extern "C" fn( *mut VMContext, $( $x, )*) -> Rets::CStruct>(self.address());
                //         // We always pass the vmctx
                //         f( self.vmctx, $( $x, )* )
                //     }).map_err(RuntimeError::from_trap)?
                // };
                // Ok(Rets::from_c_struct(results))
            }

            #[doc(hidden)]
            #[allow(missing_docs)]
            #[allow(unused_mut)]
            #[allow(clippy::too_many_arguments)]
            pub fn call_raw(&self, store: &mut impl AsStoreMut, mut params_list: Vec<RawValue> ) -> Result<Rets, RuntimeError> {
                let anyfunc = unsafe {
                    *self.func.0
                        .handle
                        .get(store.as_store_ref().objects())
                        .anyfunc
                        .as_ptr()
                        .as_ref()
                };
                // TODO: when `const fn` related features mature more, we can declare a single array
                // of the correct size here.
                let mut rets_list_array = Rets::empty_array();
                let rets_list: &mut [RawValue] = rets_list_array.as_mut();
                let using_rets_array;
                let args_rets: &mut [RawValue] = if params_list.len() > rets_list.len() {
                    using_rets_array = false;
                    params_list.as_mut()
                } else {
                    using_rets_array = true;
                    for (i, &arg) in params_list.iter().enumerate() {
                        rets_list[i] = arg;
                    }
                    rets_list.as_mut()
                };

                let mut r;
                loop {
                    let storeref = store.as_store_ref();
                    let config = storeref.engine().tunables().vmconfig();
                    r = unsafe {
                        wasmer_vm::wasmer_call_trampoline(
                            store.as_store_ref().signal_handler(),
                            config,
                            anyfunc.vmctx,
                            anyfunc.call_trampoline,
                            anyfunc.func_ptr,
                            args_rets.as_mut_ptr() as *mut u8,
                        )
                    };
                    let store_mut = store.as_store_mut();
                    if let Some(callback) = store_mut.inner.on_called.take() {
                        // TODO: OnCalledAction is needed for asyncify. It will be refactored with https://github.com/wasmerio/wasmer/issues/3451
                        match callback(store_mut) {
                            Ok(wasmer_types::OnCalledAction::InvokeAgain) => { continue; }
                            Ok(wasmer_types::OnCalledAction::Finish) => { break; }
                            Ok(wasmer_types::OnCalledAction::Trap(trap)) => { return Err(RuntimeError::user(trap)) },
                            Err(trap) => { return Err(RuntimeError::user(trap)) },
                        }
                    }
                    break;
                }
                r?;

                let num_rets = rets_list.len();
                if !using_rets_array && num_rets > 0 {
                    let src_pointer = params_list.as_ptr();
                    let rets_list = &mut rets_list_array.as_mut()[0] as *mut RawValue;
                    unsafe {
                        // TODO: we can probably remove this copy by doing some clever `transmute`s.
                        // we know it's not overlapping because `using_rets_array` is false
                        std::ptr::copy_nonoverlapping(src_pointer,
                                                        rets_list,
                                                        num_rets);
                    }
                }
                Ok(unsafe { Rets::from_array(store, rets_list_array) })
                // TODO: When the Host ABI and Wasm ABI are the same, we could do this instead:
                // but we can't currently detect whether that's safe.
                //
                // let results = unsafe {
                //     wasmer_vm::catch_traps_with_result(self.vmctx, || {
                //         let f = std::mem::transmute::<_, unsafe extern "C" fn( *mut VMContext, $( $x, )*) -> Rets::CStruct>(self.address());
                //         // We always pass the vmctx
                //         f( self.vmctx, $( $x, )* )
                //     }).map_err(RuntimeError::from_trap)?
                // };
                // Ok(Rets::from_c_struct(results))
            }
        }
    };
}

impl_native_traits!();
impl_native_traits!(A1);
impl_native_traits!(A1, A2);
impl_native_traits!(A1, A2, A3);
impl_native_traits!(A1, A2, A3, A4);
impl_native_traits!(A1, A2, A3, A4, A5);
impl_native_traits!(A1, A2, A3, A4, A5, A6);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16);
impl_native_traits!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17);
impl_native_traits!(
    A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18
);
impl_native_traits!(
    A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19
);
impl_native_traits!(
    A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20
);