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
use alloc::borrow::ToOwned;
use core::convert::TryFrom;
use core::fmt;

mod convert;
mod wasi;

use self::convert::WasmPrimitive;

macro_rules! option_helper {
    (Some $rt:expr) => {
        Some($rt)
    };
    (Some) => {
        None
    };
}

#[derive(Debug)]
pub struct Host {
    pub module: wasmi::ModuleRef,
    // FIXME: The wasmi crate currently provides no way to determine the
    // caller's module or memory from a host function. This effectively means
    // that if a module imports and calls a function from another module, and
    // that module calls a host function, the memory region of the first module
    // will be used.
    //
    // We will need to either modify the wasmi interpreter and host function API
    // to pass in function context when calling host methods, or use host
    // function trampolines which change the `Host` value, to avoid this issue.
    pub memory: wasmi::MemoryRef,
}

impl Host {
    // Create a new host for the given instance.
    // NOTE: The instance may not have been started yet.
    pub fn new(instance: &wasmi::ModuleRef) -> Result<Self, wasmi::Error> {
        let memory = match instance.export_by_name("memory") {
            Some(wasmi::ExternVal::Memory(memory)) => memory,
            _ => {
                return Err(wasmi::Error::Instantiation(
                    "required memory export".to_owned(),
                ))
            }
        };

        Ok(Host {
            module: instance.clone(),
            memory,
        })
    }
}

macro_rules! host_funcs {
    ($(
        fn $module:literal :: $name:literal ($($p:ident : $t:ident),*) $( -> $rt:ident)?
            as $variant:ident impl $method:path;
    )*) => {
        #[repr(usize)]
        #[derive(Copy, Clone, Debug, Eq, PartialEq)]
        enum HostFunc {
            $($variant),*
        }

        impl HostFunc {
            fn resolve_func(
                module_name: &str,
                field_name: &str,
                _signature: &wasmi::Signature,
            ) -> Result<HostFunc, wasmi::Error> {
                match (module_name, field_name) {
                    $(($module, $name) => Ok(HostFunc::$variant),)*
                    _ => Err(wasmi::Error::Instantiation("unresolved func import".to_owned()))
                }
            }

            fn signature(self) -> wasmi::Signature {
                match self {
                    $(
                        HostFunc::$variant => wasmi::Signature::new(
                            &[$(<$t as WasmPrimitive>::TYPE),*][..],
                            option_helper!(Some $(<$rt as WasmPrimitive>::TYPE)?),
                        )
                    ),*
                }
            }

            fn func_ref(self) -> wasmi::FuncRef {
                wasmi::FuncInstance::alloc_host(self.signature(), self as usize)
            }

            fn module_name(self) -> &'static str {
                match self {
                    $(HostFunc::$variant => $module),*
                }
            }

            fn field_name(self) -> &'static str {
                match self {
                    $(HostFunc::$variant => $name),*
                }
            }
        }

        impl TryFrom<usize> for HostFunc {
            type Error = wasmi::Trap;
            fn try_from(x: usize) -> Result<Self, Self::Error> {
                $(
                    if x == (HostFunc::$variant as usize) {
                        return Ok(HostFunc::$variant);
                    }
                )*
                Err(wasmi::TrapKind::UnexpectedSignature.into())
            }
        }

        impl fmt::Display for HostFunc {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{}::{}", self.module_name(), self.field_name())
            }
        }

        impl wasmi::Externals for Host {
            fn invoke_index(
                &mut self,
                index: usize,
                args: wasmi::RuntimeArgs,
            ) -> Result<Option<wasmi::RuntimeValue>, wasmi::Trap> {
                let span = tracing::trace_span!("invoke_index", index, ?args);
                let _enter = span.enter();

                match HostFunc::try_from(index)? {
                    $(
                        HostFunc::$variant => match args.as_ref() {
                            [$($p),*] => {
                                let _result = $method(
                                    self,
                                    $(<$t as WasmPrimitive>::from_wasm_value(*$p)?),*
                                )?;
                                Ok(option_helper!(
                                    Some $(<$rt as WasmPrimitive>::into_wasm_value(_result))?
                                ))
                            }
                            _ => Err(wasmi::TrapKind::UnexpectedSignature.into()),
                        }
                    ),*
                }
            }
        }
    }
}

host_funcs! {
    fn "wasi_unstable"::"fd_write"(fd: u32, iovs: u32, iovs_len: u32, nwritten: u32) -> u16
        as FdWrite impl wasi::fd_write;
}

struct HostResolver;
impl wasmi::ImportResolver for HostResolver {
    fn resolve_func(
        &self,
        module_name: &str,
        field_name: &str,
        signature: &wasmi::Signature,
    ) -> Result<wasmi::FuncRef, wasmi::Error> {
        let host_fn = HostFunc::resolve_func(module_name, field_name, signature)?;
        Ok(host_fn.func_ref())
    }

    fn resolve_global(
        &self,
        module_name: &str,
        field_name: &str,
        descriptor: &wasmi::GlobalDescriptor,
    ) -> Result<wasmi::GlobalRef, wasmi::Error> {
        tracing::error!(
            module_name,
            field_name,
            ?descriptor,
            "unresolved global import"
        );
        Err(wasmi::Error::Instantiation(
            "unresolved global import".to_owned(),
        ))
    }

    fn resolve_memory(
        &self,
        module_name: &str,
        field_name: &str,
        descriptor: &wasmi::MemoryDescriptor,
    ) -> Result<wasmi::MemoryRef, wasmi::Error> {
        tracing::error!(
            module_name,
            field_name,
            ?descriptor,
            "unresolved memory import"
        );
        Err(wasmi::Error::Instantiation(
            "unresolved memory import".to_owned(),
        ))
    }

    fn resolve_table(
        &self,
        module_name: &str,
        field_name: &str,
        descriptor: &wasmi::TableDescriptor,
    ) -> Result<wasmi::TableRef, wasmi::Error> {
        tracing::error!(
            module_name,
            field_name,
            ?descriptor,
            "unresolved table import"
        );
        Err(wasmi::Error::Instantiation(
            "unresolved table import".to_owned(),
        ))
    }
}

pub fn run_wasm(binary: &[u8]) -> Result<(), wasmi::Error> {
    let module = wasmi::Module::from_buffer(binary)?;
    // Instantiate the module and it's corresponding `Host` instance.
    let instance = wasmi::ModuleInstance::new(&module, &HostResolver)?;
    let mut host = Host::new(instance.not_started_instance())?;
    let instance = instance.run_start(&mut host)?;

    // FIXME: We should probably use resumable calls here.
    instance.invoke_export("_start", &[], &mut host)?;
    Ok(())
}