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
use alloc::boxed::Box;

use core::mem;
use core::ptr::{self, NonNull};
use core::slice;

use crate::environment::Environment;
use crate::error::{Error, Result, Trap};
use crate::function::{CallContext, Function, NNM3Function, RawCall};
use crate::runtime::Runtime;
use crate::utils::{cstr_to_str, eq_cstr_str};
use crate::wasm3_priv;

/// A parsed module which can be loaded into a [`Runtime`].
pub struct ParsedModule {
    data: Box<[u8]>,
    raw: ffi::IM3Module,
    env: Environment,
}

impl ParsedModule {
    /// Parses a wasm module from raw bytes.
    pub fn parse<TData: Into<Box<[u8]>>>(env: &Environment, data: TData) -> Result<Self> {
        let data = data.into();
        assert!(data.len() <= !0u32 as usize);
        let mut module = ptr::null_mut();
        let res = unsafe {
            ffi::m3_ParseModule(env.as_ptr(), &mut module, data.as_ptr(), data.len() as u32)
        };
        Error::from_ffi_res(res).map(|_| ParsedModule {
            data,
            raw: module,
            env: env.clone(),
        })
    }

    pub(crate) fn as_ptr(&self) -> ffi::IM3Module {
        self.raw
    }

    pub(crate) fn take_data(self) -> Box<[u8]> {
        let res = unsafe { ptr::read(&self.data) };
        mem::forget(self);
        res
    }

    /// The environment this module was parsed in.
    pub fn environment(&self) -> &Environment {
        &self.env
    }
}

impl Drop for ParsedModule {
    fn drop(&mut self) {
        unsafe { ffi::m3_FreeModule(self.raw) };
    }
}

/// A loaded module belonging to a specific runtime. Allows for linking and looking up functions.
// needs no drop as loaded modules will be cleaned up by the runtime
pub struct Module<'rt> {
    raw: ffi::IM3Module,
    rt: &'rt Runtime,
}

impl<'rt> Module<'rt> {
    /// Parses a wasm module from raw bytes.
    #[inline]
    pub fn parse<TData: Into<Box<[u8]>>>(
        environment: &Environment,
        bytes: TData,
    ) -> Result<ParsedModule> {
        ParsedModule::parse(environment, bytes)
    }

    /// Links the given function to the corresponding module and function name.
    /// This allows linking a more verbose function, as it gets access to the unsafe
    /// runtime parts. For easier use the [`make_func_wrapper`] should be used to create
    /// the unsafe facade for your function that then can be passed to this.
    ///
    /// For a simple API see [`link_closure`] which takes a closure instead.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations:
    ///
    /// * a memory allocation failed
    /// * no function by the given name in the given module could be found
    /// * the function has been found but the signature did not match
    ///
    /// [`link_closure`]: #method.link_closure
    pub fn link_function<Args, Ret>(
        &mut self,
        module_name: &str,
        function_name: &str,
        f: RawCall,
    ) -> Result<()>
    where
        Args: crate::WasmArgs,
        Ret: crate::WasmType,
    {
        let func = self.find_import_function(module_name, function_name)?;
        Function::<'_, Args, Ret>::validate_sig(func)
            .and_then(|_| unsafe { self.link_func_impl(func, f) })
    }

    /// Links the given closure to the corresponding module and function name.
    /// This boxes the closure and therefor requires a heap allocation.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations:
    ///
    /// * a memory allocation failed
    /// * no function by the given name in the given module could be found
    /// * the function has been found but the signature did not match
    pub fn link_closure<Args, Ret, F>(
        &mut self,
        module_name: &str,
        function_name: &str,
        closure: F,
    ) -> Result<()>
    where
        Args: crate::WasmArgs,
        Ret: crate::WasmType,
        F: for<'cc> FnMut(CallContext<'cc>, Args) -> core::result::Result<Ret, Trap> + 'static,
    {
        let func = self.find_import_function(module_name, function_name)?;
        Function::<'_, Args, Ret>::validate_sig(func)?;
        let mut closure = Box::pin(closure);
        unsafe { self.link_closure_impl(func, closure.as_mut().get_unchecked_mut()) }?;
        self.rt.push_closure(closure);
        Ok(())
    }

    /// Looks up a function by the given name in this module.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations:
    ///
    /// * a memory allocation failed
    /// * no function by the given name in the given module could be found
    /// * the function has been found but the signature did not match
    pub fn find_function<Args, Ret>(&self, function_name: &str) -> Result<Function<'rt, Args, Ret>>
    where
        Args: crate::WasmArgs,
        Ret: crate::WasmType,
    {
        let func = unsafe {
            slice::from_raw_parts_mut(
                if (*self.raw).functions.is_null() {
                    NonNull::dangling().as_ptr()
                } else {
                    (*self.raw).functions
                },
                (*self.raw).numFunctions as usize,
            )
            .iter_mut()
            .find(|func| eq_cstr_str(func.name, function_name))
            .map(NonNull::from)
            .ok_or(Error::FunctionNotFound)?
        };
        Function::from_raw(self.rt, func).and_then(Function::compile)
    }

    /// Looks up a function by its index in this module.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations:
    ///
    /// * a memory allocation failed
    /// * the index is out of bounds
    /// * the function has been found but the signature did not match
    pub fn function<Args, Ret>(&self, function_index: usize) -> Result<Function<'rt, Args, Ret>>
    where
        Args: crate::WasmArgs,
        Ret: crate::WasmType,
    {
        let func = unsafe {
            slice::from_raw_parts_mut(
                if (*self.raw).functions.is_null() {
                    NonNull::dangling().as_ptr()
                } else {
                    (*self.raw).functions
                },
                (*self.raw).numFunctions as usize,
            )
            .get(function_index)
            .map(NonNull::from)
            .ok_or(Error::FunctionNotFound)?
        };
        Function::from_raw(self.rt, func).and_then(Function::compile)
    }

    /// The name of this module.
    pub fn name(&self) -> &str {
        unsafe { cstr_to_str((*self.raw).name) }
    }

    /// Links wasi to this module.
    #[cfg(feature = "wasi")]
    pub fn link_wasi(&mut self) -> Result<()> {
        unsafe { Error::from_ffi_res(ffi::m3_LinkWASI(self.raw)) }
    }
}

impl<'rt> Module<'rt> {
    pub(crate) fn from_raw(rt: &'rt Runtime, raw: ffi::IM3Module) -> Self {
        Module { raw, rt }
    }

    unsafe fn link_func_impl(&self, mut m3_func: NNM3Function, func: RawCall) -> Result<()> {
        let page = wasm3_priv::AcquireCodePageWithCapacity(self.rt.as_ptr(), 2);
        if page.is_null() {
            Error::from_ffi_res(ffi::m3Err_mallocFailedCodePage)
        } else {
            m3_func.as_mut().compiled = wasm3_priv::GetPagePC(page);
            m3_func.as_mut().module = self.raw;
            wasm3_priv::EmitWord_impl(page, crate::wasm3_priv::op_CallRawFunction as _);
            wasm3_priv::EmitWord_impl(page, func as _);

            wasm3_priv::ReleaseCodePage(self.rt.as_ptr(), page);
            Ok(())
        }
    }

    unsafe fn link_closure_impl<Args, Ret, F>(
        &self,
        mut m3_func: NNM3Function,
        closure: *mut F,
    ) -> Result<()>
    where
        Args: crate::WasmArgs,
        Ret: crate::WasmType,
        F: for<'cc> FnMut(CallContext<'cc>, Args) -> core::result::Result<Ret, Trap> + 'static,
    {
        unsafe extern "C" fn _impl<Args, Ret, F>(
            runtime: ffi::IM3Runtime,
            sp: ffi::m3stack_t,
            _mem: *mut cty::c_void,
            closure: *mut cty::c_void,
        ) -> *const cty::c_void
        where
            Args: crate::WasmArgs,
            Ret: crate::WasmType,
            F: for<'cc> FnMut(CallContext<'cc>, Args) -> core::result::Result<Ret, Trap> + 'static,
        {
            // use https://doc.rust-lang.org/std/primitive.pointer.html#method.offset_from once stable
            let stack_base = (*runtime).stack as ffi::m3stack_t;
            let stack_occupied =
                (sp as usize - stack_base as usize) / core::mem::size_of::<ffi::m3slot_t>();
            let stack = ptr::slice_from_raw_parts_mut(
                sp,
                (*runtime).numStackSlots as usize - stack_occupied,
            );

            let args = Args::pop_from_stack(stack);
            let context = CallContext::from_rt(NonNull::new_unchecked(runtime));
            let res = (&mut *closure.cast::<F>())(context, args);
            match res {
                Ok(ret) => {
                    ret.push_on_stack(stack.cast());
                    ffi::m3Err_none as _
                }
                Err(err) => err.as_ptr() as _,
            }
        }

        let page = wasm3_priv::AcquireCodePageWithCapacity(self.rt.as_ptr(), 3);
        if page.is_null() {
            Error::from_ffi_res(ffi::m3Err_mallocFailedCodePage)
        } else {
            m3_func.as_mut().compiled = wasm3_priv::GetPagePC(page);
            m3_func.as_mut().module = self.raw;
            wasm3_priv::EmitWord_impl(page, crate::wasm3_priv::op_CallRawFunctionEx as _);
            wasm3_priv::EmitWord_impl(page, _impl::<Args, Ret, F> as _);
            wasm3_priv::EmitWord_impl(page, closure.cast());

            wasm3_priv::ReleaseCodePage(self.rt.as_ptr(), page);
            Ok(())
        }
    }

    fn find_import_function(&self, module_name: &str, function_name: &str) -> Result<NNM3Function> {
        unsafe {
            slice::from_raw_parts_mut(
                if (*self.raw).functions.is_null() {
                    NonNull::dangling().as_ptr()
                } else {
                    (*self.raw).functions
                },
                (*self.raw).numFunctions as usize,
            )
            .iter_mut()
            .filter(|func| eq_cstr_str(func.import.moduleUtf8, module_name))
            .find(|func| eq_cstr_str(func.import.fieldUtf8, function_name))
            .map(NonNull::from)
            .ok_or(Error::FunctionNotFound)
        }
    }
}

#[test]
fn module_parse() {
    let env = Environment::new().expect("env alloc failure");
    let fib32 = [
        0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01,
        0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03, 0x66, 0x69, 0x62, 0x00, 0x00, 0x0a,
        0x1f, 0x01, 0x1d, 0x00, 0x20, 0x00, 0x41, 0x02, 0x49, 0x04, 0x40, 0x20, 0x00, 0x0f, 0x0b,
        0x20, 0x00, 0x41, 0x02, 0x6b, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6b, 0x10, 0x00, 0x6a,
        0x0f, 0x0b,
    ];
    let _ = Module::parse(&env, &fib32[..]).unwrap();
}