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
//! Host functions
use crate::metadata::{result::Result, StoreData};
use wasmtime::{
    AsContext, AsContextMut, Caller, Extern, Func, Linker, Memory, MemoryType, Store, Trap,
};

pub fn alloc(ctx: impl AsContextMut<Data = StoreData>, memory: Memory) -> Extern {
    Extern::Func(Func::wrap(
        ctx,
        move |mut caller: Caller<'_, StoreData>, pages: i32| {
            memory
                .clone()
                .grow(caller.as_context_mut(), pages as u64)
                .map_err(|e| {
                    log::error!("{:?}", e);

                    Trap::i32_exit(1)
                })
                .map(|pages| pages as i32)
        },
    ))
}

pub fn free(ctx: impl AsContextMut<Data = StoreData>) -> Extern {
    Extern::Func(Func::wrap(ctx, |_: i32| {}))
}

pub fn gr_debug(ctx: impl AsContextMut<Data = StoreData>, memory: Memory) -> Extern {
    Extern::Func(Func::wrap(
        ctx,
        move |caller: Caller<'_, StoreData>, ptr: i32, len: i32| {
            let (ptr, len) = (ptr as usize, len as usize);

            let mut msg = vec![0; len];
            memory
                .clone()
                .read(caller.as_context(), ptr, &mut msg)
                .map_err(|e| {
                    log::error!("{:?}", e);
                    Trap::i32_exit(1)
                })?;

            log::debug!("{:?}", String::from_utf8_lossy(&msg));
            Ok(())
        },
    ))
}

pub fn gr_read(ctx: impl AsContextMut<Data = StoreData>, memory: Memory) -> Extern {
    Extern::Func(Func::wrap(
        ctx,
        move |mut caller: Caller<'_, StoreData>, ptr: i32, len: i32, dest: i32| {
            let (ptr, len, dest) = (ptr as usize, len as usize, dest as usize);

            let mut msg = vec![0; len];
            msg.copy_from_slice(&caller.data().msg[ptr..(ptr + len)]);

            memory
                .clone()
                .write(caller.as_context_mut(), dest, &msg)
                .map_err(|e| {
                    log::error!("{:?}", e);

                    Trap::i32_exit(1)
                })?;

            Ok(())
        },
    ))
}

pub fn gr_size(ctx: impl AsContextMut<Data = StoreData>) -> Extern {
    Extern::Func(Func::wrap(ctx, |caller: Caller<'_, StoreData>| {
        caller.data().msg.len() as i32
    }))
}