wasi.rs

  1use std::{
  2    collections::HashMap, fs::File, future::Future, marker::PhantomData, path::Path, pin::Pin,
  3};
  4
  5use anyhow::{anyhow, Error};
  6use serde::{de::DeserializeOwned, Serialize};
  7
  8use wasi_common::{dir, file};
  9use wasmtime::IntoFunc;
 10use wasmtime::{Caller, Config, Engine, Instance, Linker, Module, Store, TypedFunc};
 11use wasmtime_wasi::{Dir, WasiCtx, WasiCtxBuilder};
 12
 13pub struct WasiResource(u32);
 14
 15pub struct WasiFn<A: Serialize, R: DeserializeOwned> {
 16    function: TypedFunc<(u32, u32), u32>,
 17    _function_type: PhantomData<fn(A) -> R>,
 18}
 19
 20impl<A: Serialize, R: DeserializeOwned> Copy for WasiFn<A, R> {}
 21
 22impl<A: Serialize, R: DeserializeOwned> Clone for WasiFn<A, R> {
 23    fn clone(&self) -> Self {
 24        Self {
 25            function: self.function,
 26            _function_type: PhantomData,
 27        }
 28    }
 29}
 30
 31// impl<A: Serialize, R: DeserializeOwned> WasiFn<A, R> {
 32//     #[inline(always)]
 33//     pub async fn call(&self, runtime: &mut Wasi, arg: A) -> Result<R, Error> {
 34//         runtime.call(self, arg).await
 35//     }
 36// }
 37
 38pub struct Wasi {
 39    engine: Engine,
 40    module: Module,
 41    store: Store<WasiCtx>,
 42    instance: Instance,
 43    alloc_buffer: TypedFunc<u32, u32>,
 44    // free_buffer: TypedFunc<(u32, u32), ()>,
 45}
 46
 47// type signature derived from:
 48// https://docs.rs/wasmtime/latest/wasmtime/struct.Linker.html#method.func_wrap2_async
 49// macro_rules! dynHostFunction {
 50//     () => {
 51//         Box<
 52//             dyn for<'a> Fn(Caller<'a, WasiCtx>, u32, u32)
 53//                 -> Box<dyn Future<Output = u32> + Send + 'a>
 54//                     + Send
 55//                     + Sync
 56//                     + 'static
 57//         >
 58//     };
 59// }
 60
 61// macro_rules! implHostFunction {
 62//     () => {
 63//         impl for<'a> Fn(Caller<'a, WasiCtx>, u32, u32)
 64//             -> Box<dyn Future<Output = u32> + Send + 'a>
 65//                 + Send
 66//                 + Sync
 67//                 + 'static
 68//     };
 69// }
 70
 71// This type signature goodness gracious
 72pub type HostFunction = Box<dyn IntoFunc<WasiCtx, (u32, u32), u32>>;
 73
 74pub struct WasiPluginBuilder {
 75    // host_functions: HashMap<String, Box<dyn Fn(&str, &mut Linker<WasiCtx>) -> Result<(), Error>>>,
 76    wasi_ctx: WasiCtx,
 77    engine: Engine,
 78    linker: Linker<WasiCtx>,
 79}
 80
 81impl WasiPluginBuilder {
 82    pub fn new(wasi_ctx: WasiCtx) -> Result<Self, Error> {
 83        let mut config = Config::default();
 84        config.async_support(true);
 85        let engine = Engine::new(&config)?;
 86        let mut linker = Linker::new(&engine);
 87
 88        Ok(WasiPluginBuilder {
 89            // host_functions: HashMap::new(),
 90            wasi_ctx,
 91            engine,
 92            linker,
 93        })
 94    }
 95
 96    pub fn new_with_default_ctx() -> Result<Self, Error> {
 97        let wasi_ctx = WasiCtxBuilder::new()
 98            .inherit_stdin()
 99            .inherit_stderr()
100            .build();
101        Self::new(wasi_ctx)
102    }
103
104    pub fn host_function<A: Serialize, R: DeserializeOwned>(
105        mut self,
106        name: &str,
107        function: impl Fn(A) -> R + Send + Sync + 'static,
108    ) -> Result<Self, Error> {
109        self.linker
110            .func_wrap("env", name, move |ptr: u32, len: u32| {
111                // TODO: insert serialization code
112                function(todo!());
113                7u32
114            })?;
115        Ok(self)
116    }
117
118    pub async fn init<T: AsRef<[u8]>>(self, module: T) -> Result<Wasi, Error> {
119        Wasi::init(module.as_ref().to_vec(), self).await
120    }
121}
122
123// TODO: remove
124/// Represents a to-be-initialized plugin.
125/// Please use [`WasiPluginBuilder`], don't use this directly.
126pub struct WasiPlugin {
127    pub module: Vec<u8>,
128    pub wasi_ctx: WasiCtx,
129    pub host_functions:
130        HashMap<String, Box<dyn Fn(&str, &mut Linker<WasiCtx>) -> Result<(), Error>>>,
131}
132
133impl Wasi {
134    pub fn dump_memory(data: &[u8]) {
135        for (i, byte) in data.iter().enumerate() {
136            if i % 32 == 0 {
137                println!();
138            }
139            if i % 4 == 0 {
140                print!("|");
141            }
142            if *byte == 0 {
143                print!("__")
144            } else {
145                print!("{:02x}", byte);
146            }
147        }
148        println!();
149    }
150}
151
152impl Wasi {
153    async fn init(module: Vec<u8>, plugin: WasiPluginBuilder) -> Result<Self, Error> {
154        let engine = plugin.engine;
155        let mut linker = plugin.linker;
156
157        linker.func_wrap("env", "__hello", |x: u32| x * 2).unwrap();
158        linker.func_wrap("env", "__bye", |x: u32| x / 2).unwrap();
159
160        wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;
161
162        let mut store: Store<_> = Store::new(&engine, plugin.wasi_ctx);
163        let module = Module::new(&engine, module)?;
164
165        linker.module_async(&mut store, "", &module).await?;
166        let instance = linker.instantiate_async(&mut store, &module).await?;
167
168        let alloc_buffer = instance.get_typed_func(&mut store, "__alloc_buffer")?;
169        // let free_buffer = instance.get_typed_func(&mut store, "__free_buffer")?;
170
171        Ok(Wasi {
172            engine,
173            module,
174            store,
175            instance,
176            alloc_buffer,
177            // free_buffer,
178        })
179    }
180
181    /// Attaches a file or directory the the given system path to the runtime.
182    /// Note that the resource must be freed by calling `remove_resource` afterwards.
183    pub fn attach_path<T: AsRef<Path>>(&mut self, path: T) -> Result<WasiResource, Error> {
184        // grab the WASI context
185        let ctx = self.store.data_mut();
186
187        // open the file we want, and convert it into the right type
188        // this is a footgun and a half
189        let file = File::open(&path).unwrap();
190        let dir = Dir::from_std_file(file);
191        let dir = Box::new(wasmtime_wasi::dir::Dir::from_cap_std(dir));
192
193        // grab an empty file descriptor, specify capabilities
194        let fd = ctx.table().push(Box::new(()))?;
195        let caps = dir::DirCaps::all();
196        let file_caps = file::FileCaps::all();
197
198        // insert the directory at the given fd,
199        // return a handle to the resource
200        ctx.insert_dir(fd, dir, caps, file_caps, path.as_ref().to_path_buf());
201        Ok(WasiResource(fd))
202    }
203
204    /// Returns `true` if the resource existed and was removed.
205    pub fn remove_resource(&mut self, resource: WasiResource) -> Result<(), Error> {
206        self.store
207            .data_mut()
208            .table()
209            .delete(resource.0)
210            .ok_or_else(|| anyhow!("Resource did not exist, but a valid handle was passed in"))?;
211        Ok(())
212    }
213
214    // pub fn with_resource<T>(
215    //     &mut self,
216    //     resource: WasiResource,
217    //     callback: fn(&mut Self) -> Result<T, Error>,
218    // ) -> Result<T, Error> {
219    //     let result = callback(self);
220    //     self.remove_resource(resource)?;
221    //     return result;
222    // }
223
224    // So this call function is kinda a dance, I figured it'd be a good idea to document it.
225    // the high level is we take a serde type, serialize it to a byte array,
226    // (we're doing this using bincode for now)
227    // then toss that byte array into webassembly.
228    // webassembly grabs that byte array, does some magic,
229    // and serializes the result into yet another byte array.
230    // we then grab *that* result byte array and deserialize it into a result.
231    //
232    // phew...
233    //
234    // now the problem is, webassambly doesn't support buffers.
235    // only really like i32s, that's it (yeah, it's sad. Not even unsigned!)
236    // (ok, I'm exaggerating a bit).
237    //
238    // the Wasm function that this calls must have a very specific signature:
239    //
240    // fn(pointer to byte array: i32, length of byte array: i32)
241    //     -> pointer to (
242    //            pointer to byte_array: i32,
243    //            length of byte array: i32,
244    //     ): i32
245    //
246    // This pair `(pointer to byte array, length of byte array)` is called a `Buffer`
247    // and can be found in the cargo_test plugin.
248    //
249    // so on the wasm side, we grab the two parameters to the function,
250    // stuff them into a `Buffer`,
251    // and then pray to the `unsafe` Rust gods above that a valid byte array pops out.
252    //
253    // On the flip side, when returning from a wasm function,
254    // we convert whatever serialized result we get into byte array,
255    // which we stuff into a Buffer and allocate on the heap,
256    // which pointer to we then return.
257    // Note the double indirection!
258    //
259    // So when returning from a function, we actually leak memory *twice*:
260    //
261    // 1) once when we leak the byte array
262    // 2) again when we leak the allocated `Buffer`
263    //
264    // This isn't a problem because Wasm stops executing after the function returns,
265    // so the heap is still valid for our inspection when we want to pull things out.
266
267    /// Takes an item, allocates a buffer, serializes the argument to that buffer,
268    /// and returns a (ptr, len) pair to that buffer.
269    async fn serialize_to_buffer<T: Serialize>(&mut self, item: T) -> Result<(u32, u32), Error> {
270        // serialize the argument using bincode
271        let item = bincode::serialize(&item)?;
272        let buffer_len = item.len() as u32;
273
274        // allocate a buffer and write the argument to that buffer
275        let buffer_ptr = self
276            .alloc_buffer
277            .call_async(&mut self.store, buffer_len)
278            .await?;
279        let plugin_memory = self
280            .instance
281            .get_memory(&mut self.store, "memory")
282            .ok_or_else(|| anyhow!("Could not grab slice of plugin memory"))?;
283        plugin_memory.write(&mut self.store, buffer_ptr as usize, &item)?;
284        Ok((buffer_ptr, buffer_len))
285    }
286
287    /// Takes a ptr to a (ptr, len) pair and returns the corresponding deserialized buffer
288    fn deserialize_from_buffer<R: DeserializeOwned>(&mut self, buffer: u32) -> Result<R, Error> {
289        // create a buffer to read the (ptr, length) pair into
290        // this is a total of 4 + 4 = 8 bytes.
291        let raw_buffer = &mut [0; 8];
292        let plugin_memory = self
293            .instance
294            .get_memory(&mut self.store, "memory")
295            .ok_or_else(|| anyhow!("Could not grab slice of plugin memory"))?;
296        plugin_memory.read(&mut self.store, buffer as usize, raw_buffer)?;
297
298        // use these bytes (wasm stores things little-endian)
299        // to get a pointer to the buffer and its length
300        let b = raw_buffer;
301        let buffer_ptr = u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize;
302        let buffer_len = u32::from_le_bytes([b[4], b[5], b[6], b[7]]) as usize;
303        let buffer_end = buffer_ptr + buffer_len;
304
305        // read the buffer at this point into a byte array
306        // deserialize the byte array into the provided serde type
307        let result = &plugin_memory.data(&mut self.store)[buffer_ptr..buffer_end];
308        let result = bincode::deserialize(result)?;
309
310        // TODO: this is handled wasm-side, but I'd like to double-check
311        // // deallocate the argument buffer
312        // self.free_buffer.call(&mut self.store, arg_buffer);
313
314        Ok(result)
315    }
316
317    pub fn function<A: Serialize, R: DeserializeOwned, T: AsRef<str>>(
318        &mut self,
319        name: T,
320    ) -> Result<WasiFn<A, R>, Error> {
321        let fun_name = format!("__{}", name.as_ref());
322        let fun = self
323            .instance
324            .get_typed_func::<(u32, u32), u32, _>(&mut self.store, &fun_name)?;
325        Ok(WasiFn {
326            function: fun,
327            _function_type: PhantomData,
328        })
329    }
330
331    // TODO: dont' use as for conversions
332    pub async fn call<A: Serialize, R: DeserializeOwned>(
333        &mut self,
334        handle: &WasiFn<A, R>,
335        arg: A,
336    ) -> Result<R, Error> {
337        // dbg!(&handle.name);
338        // dbg!(serde_json::to_string(&arg)).unwrap();
339
340        // write the argument to linear memory
341        // this returns a (ptr, lentgh) pair
342        let arg_buffer = self.serialize_to_buffer(arg).await?;
343
344        // get the webassembly function we want to actually call
345        // TODO: precompute handle
346        // let fun_name = format!("__{}", handle);
347        // let fun = self
348        //     .instance
349        //     .get_typed_func::<(u32, u32), u32, _>(&mut self.store, &fun_name)?;
350        let fun = handle.function;
351
352        // call the function, passing in the buffer and its length
353        // this returns a ptr to a (ptr, lentgh) pair
354        let result_buffer = fun.call_async(&mut self.store, arg_buffer).await?;
355
356        self.deserialize_from_buffer(result_buffer)
357    }
358}