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
use super::super::store::wasm_store_t;
use super::super::trap::wasm_trap_t;
use super::super::types::{wasm_functype_t, wasm_valkind_enum};
use super::super::value::{wasm_val_inner, wasm_val_t, wasm_val_vec_t};
use std::convert::TryInto;
use std::ffi::c_void;
use std::sync::Arc;
use wasmer::{Function, Instance, RuntimeError, Val};
#[derive(Debug)]
#[allow(non_camel_case_types)]
pub struct wasm_func_t {
pub(crate) inner: Function,
pub(crate) instance: Option<Arc<Instance>>,
}
#[allow(non_camel_case_types)]
pub type wasm_func_callback_t = unsafe extern "C" fn(
args: *const wasm_val_vec_t,
results: *mut wasm_val_vec_t,
) -> *mut wasm_trap_t;
#[allow(non_camel_case_types)]
pub type wasm_func_callback_with_env_t = unsafe extern "C" fn(
env: *mut c_void,
args: *const wasm_val_vec_t,
results: *mut wasm_val_vec_t,
) -> *mut wasm_trap_t;
#[allow(non_camel_case_types)]
pub type wasm_env_finalizer_t = unsafe extern "C" fn(*mut c_void);
#[no_mangle]
pub unsafe extern "C" fn wasm_func_new(
store: Option<&wasm_store_t>,
function_type: Option<&wasm_functype_t>,
callback: Option<wasm_func_callback_t>,
) -> Option<Box<wasm_func_t>> {
let store = store?;
let function_type = function_type?;
let callback = callback?;
let func_sig = &function_type.inner().function_type;
let num_rets = func_sig.results().len();
let inner_callback = move |args: &[Val]| -> Result<Vec<Val>, RuntimeError> {
let processed_args: wasm_val_vec_t = args
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<wasm_val_t>, _>>()
.expect("Argument conversion failed")
.into();
let mut results: wasm_val_vec_t = vec![
wasm_val_t {
kind: wasm_valkind_enum::WASM_I64 as _,
of: wasm_val_inner { int64_t: 0 },
};
num_rets
]
.into();
let trap = callback(&processed_args, &mut results);
if !trap.is_null() {
let trap: Box<wasm_trap_t> = Box::from_raw(trap);
return Err(trap.inner);
}
let processed_results = results
.into_slice()
.expect("Failed to convert `results` into a slice")
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<Val>, _>>()
.expect("Result conversion failed");
Ok(processed_results)
};
let function = Function::new(&store.inner, func_sig, inner_callback);
Some(Box::new(wasm_func_t {
instance: None,
inner: function,
}))
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_new_with_env(
store: Option<&wasm_store_t>,
function_type: Option<&wasm_functype_t>,
callback: Option<wasm_func_callback_with_env_t>,
env: *mut c_void,
env_finalizer: Option<wasm_env_finalizer_t>,
) -> Option<Box<wasm_func_t>> {
let store = store?;
let function_type = function_type?;
let callback = callback?;
let func_sig = &function_type.inner().function_type;
let num_rets = func_sig.results().len();
#[derive(wasmer::WasmerEnv, Clone)]
#[repr(C)]
struct WrapperEnv {
env: *mut c_void,
env_finalizer: Arc<Option<wasm_env_finalizer_t>>,
}
unsafe impl Send for WrapperEnv {}
unsafe impl Sync for WrapperEnv {}
impl Drop for WrapperEnv {
fn drop(&mut self) {
if let Some(env_finalizer) = Arc::get_mut(&mut self.env_finalizer)
.map(Option::take)
.flatten()
{
if !self.env.is_null() {
unsafe { (env_finalizer)(self.env as _) }
}
}
}
}
let trampoline = move |env: &WrapperEnv, args: &[Val]| -> Result<Vec<Val>, RuntimeError> {
let processed_args: wasm_val_vec_t = args
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<wasm_val_t>, _>>()
.expect("Argument conversion failed")
.into();
let mut results: wasm_val_vec_t = vec![
wasm_val_t {
kind: wasm_valkind_enum::WASM_I64 as _,
of: wasm_val_inner { int64_t: 0 },
};
num_rets
]
.into();
let trap = callback(env.env, &processed_args, &mut results);
if !trap.is_null() {
let trap: Box<wasm_trap_t> = Box::from_raw(trap);
return Err(trap.inner);
}
let processed_results = results
.into_slice()
.expect("Failed to convert `results` into a slice")
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<Val>, _>>()
.expect("Result conversion failed");
Ok(processed_results)
};
let function = Function::new_with_env(
&store.inner,
func_sig,
WrapperEnv {
env,
env_finalizer: Arc::new(env_finalizer),
},
trampoline,
);
Some(Box::new(wasm_func_t {
instance: None,
inner: function,
}))
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_delete(_func: Option<Box<wasm_func_t>>) {}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_call(
func: Option<&wasm_func_t>,
args: Option<&wasm_val_vec_t>,
results: &mut wasm_val_vec_t,
) -> Option<Box<wasm_trap_t>> {
let func = func?;
let args = args?;
let params = args
.into_slice()
.map(|slice| {
slice
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<Val>, _>>()
.expect("Arguments conversion failed")
})
.unwrap_or_default();
match func.inner.call(¶ms) {
Ok(wasm_results) => {
let vals = wasm_results
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<wasm_val_t>, _>>()
.expect("Results conversion failed");
if results.is_uninitialized() {
*results = vals.into();
}
else {
let slice = results
.into_slice_mut()
.expect("`wasm_func_call`, results' size is greater than 0 but data is NULL");
for (result, value) in slice.iter_mut().zip(vals.iter()) {
(*result).kind = value.kind;
(*result).of = value.of;
}
}
None
}
Err(e) => Some(Box::new(e.into())),
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_param_arity(func: &wasm_func_t) -> usize {
func.inner.ty().params().len()
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_result_arity(func: &wasm_func_t) -> usize {
func.inner.ty().results().len()
}
#[no_mangle]
pub extern "C" fn wasm_func_type(func: Option<&wasm_func_t>) -> Option<Box<wasm_functype_t>> {
let func = func?;
Some(Box::new(wasm_functype_t::new(func.inner.ty().clone())))
}