wasi.rs

  1use std::{fs::File, os::unix::prelude::AsRawFd, path::Path};
  2
  3use anyhow::{anyhow, Error};
  4use serde::{de::DeserializeOwned, Serialize};
  5
  6use wasi_common::{dir, file};
  7use wasmtime::{Engine, Instance, Linker, Module, Store, TypedFunc};
  8use wasmtime_wasi::{Dir, WasiCtx, WasiCtxBuilder};
  9
 10pub struct WasiResource(u32);
 11
 12pub struct Wasi {
 13    engine: Engine,
 14    module: Module,
 15    store: Store<WasiCtx>,
 16    instance: Instance,
 17    alloc_buffer: TypedFunc<i32, i32>,
 18    // free_buffer: TypedFunc<(i32, i32), ()>,
 19}
 20
 21pub struct WasiPlugin {
 22    pub module: Vec<u8>,
 23    pub wasi_ctx: WasiCtx,
 24}
 25
 26impl Wasi {
 27    pub fn dump_memory(data: &[u8]) {
 28        for (i, byte) in data.iter().enumerate() {
 29            if i % 32 == 0 {
 30                println!();
 31            }
 32            if i % 4 == 0 {
 33                print!("|");
 34            }
 35            if *byte == 0 {
 36                print!("__")
 37            } else {
 38                print!("{:02x}", byte);
 39            }
 40        }
 41        println!();
 42    }
 43}
 44
 45impl Wasi {
 46    pub fn default_ctx() -> WasiCtx {
 47        WasiCtxBuilder::new()
 48            .inherit_stdout()
 49            .inherit_stderr()
 50            .build()
 51    }
 52
 53    pub fn init(plugin: WasiPlugin) -> Result<Self, Error> {
 54        let engine = Engine::default();
 55        let mut linker = Linker::new(&engine);
 56
 57        linker.func_wrap("env", "hello", |x: u32| x * 2).unwrap();
 58        linker.func_wrap("env", "bye", |x: u32| x / 2).unwrap();
 59
 60        println!("linking");
 61        wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;
 62
 63        println!("linked");
 64        let mut store: Store<_> = Store::new(&engine, plugin.wasi_ctx);
 65        println!("moduling");
 66        let module = Module::new(&engine, plugin.module)?;
 67        println!("moduled");
 68
 69        linker.module(&mut store, "", &module)?;
 70        println!("linked again");
 71
 72        let instance = linker.instantiate(&mut store, &module)?;
 73        println!("instantiated");
 74
 75        let alloc_buffer = instance.get_typed_func(&mut store, "__alloc_buffer")?;
 76        // let free_buffer = instance.get_typed_func(&mut store, "__free_buffer")?;
 77        println!("can alloc");
 78        Ok(Wasi {
 79            engine,
 80            module,
 81            store,
 82            instance,
 83            alloc_buffer,
 84            // free_buffer,
 85        })
 86    }
 87
 88    /// Attaches a file or directory the the given system path to the runtime.
 89    /// Note that the resource must be freed by calling `remove_resource` afterwards.
 90    pub fn attach_path<T: AsRef<Path>>(&mut self, path: T) -> Result<WasiResource, Error> {
 91        // grab the WASI context
 92        let ctx = self.store.data_mut();
 93
 94        // open the file we want, and convert it into the right type
 95        // this is a footgun and a half
 96        let file = File::open(&path).unwrap();
 97        let dir = Dir::from_std_file(file);
 98        let dir = Box::new(wasmtime_wasi::dir::Dir::from_cap_std(dir));
 99
100        // grab an empty file descriptor, specify capabilities
101        let fd = ctx.table().push(Box::new(()))?;
102        dbg!(fd);
103        let caps = dir::DirCaps::all();
104        let file_caps = file::FileCaps::all();
105
106        // insert the directory at the given fd,
107        // return a handle to the resource
108        ctx.insert_dir(fd, dir, caps, file_caps, path.as_ref().to_path_buf());
109        Ok(WasiResource(fd))
110    }
111
112    /// Returns `true` if the resource existed and was removed.
113    pub fn remove_resource(&mut self, resource: WasiResource) -> Result<(), Error> {
114        self.store
115            .data_mut()
116            .table()
117            .delete(resource.0)
118            .ok_or_else(|| anyhow!("Resource did not exist, but a valid handle was passed in"))?;
119        Ok(())
120    }
121
122    // pub fn with_resource<T>(
123    //     &mut self,
124    //     resource: WasiResource,
125    //     callback: fn(&mut Self) -> Result<T, Error>,
126    // ) -> Result<T, Error> {
127    //     let result = callback(self);
128    //     self.remove_resource(resource)?;
129    //     return result;
130    // }
131
132    // So this call function is kinda a dance, I figured it'd be a good idea to document it.
133    // the high level is we take a serde type, serialize it to a byte array,
134    // (we're doing this using bincode for now)
135    // then toss that byte array into webassembly.
136    // webassembly grabs that byte array, does some magic,
137    // and serializes the result into yet another byte array.
138    // we then grab *that* result byte array and deserialize it into a result.
139    //
140    // phew...
141    //
142    // now the problem is, webassambly doesn't support buffers.
143    // only really like i32s, that's it (yeah, it's sad. Not even unsigned!)
144    // (ok, I'm exaggerating a bit).
145    //
146    // the Wasm function that this calls must have a very specific signature:
147    //
148    // fn(pointer to byte array: i32, length of byte array: i32)
149    //     -> pointer to (
150    //            pointer to byte_array: i32,
151    //            length of byte array: i32,
152    //     ): i32
153    //
154    // This pair `(pointer to byte array, length of byte array)` is called a `Buffer`
155    // and can be found in the cargo_test plugin.
156    //
157    // so on the wasm side, we grab the two parameters to the function,
158    // stuff them into a `Buffer`,
159    // and then pray to the `unsafe` Rust gods above that a valid byte array pops out.
160    //
161    // On the flip side, when returning from a wasm function,
162    // we convert whatever serialized result we get into byte array,
163    // which we stuff into a Buffer and allocate on the heap,
164    // which pointer to we then return.
165    // Note the double indirection!
166    //
167    // So when returning from a function, we actually leak memory *twice*:
168    //
169    // 1) once when we leak the byte array
170    // 2) again when we leak the allocated `Buffer`
171    //
172    // This isn't a problem because Wasm stops executing after the function returns,
173    // so the heap is still valid for our inspection when we want to pull things out.
174
175    // TODO: dont' use as for conversions
176    pub fn call<A: Serialize, R: DeserializeOwned>(
177        &mut self,
178        handle: &str,
179        arg: A,
180    ) -> Result<R, Error> {
181        dbg!(&handle);
182        // dbg!(serde_json::to_string(&arg)).unwrap();
183
184        // serialize the argument using bincode
185        let arg = bincode::serialize(&arg)?;
186        let arg_buffer_len = arg.len();
187
188        // allocate a buffer and write the argument to that buffer
189        let arg_buffer_ptr = self
190            .alloc_buffer
191            .call(&mut self.store, arg_buffer_len as i32)?;
192        let plugin_memory = self
193            .instance
194            .get_memory(&mut self.store, "memory")
195            .ok_or_else(|| anyhow!("Could not grab slice of plugin memory"))?;
196        plugin_memory.write(&mut self.store, arg_buffer_ptr as usize, &arg)?;
197
198        // get the webassembly function we want to actually call
199        // TODO: precompute handle
200        let fun_name = format!("__{}", handle);
201        let fun = self
202            .instance
203            .get_typed_func::<(i32, i32), i32, _>(&mut self.store, &fun_name)?;
204
205        // call the function, passing in the buffer and its length
206        // this should return a pointer to a (ptr, lentgh) pair
207        let arg_buffer = (arg_buffer_ptr, arg_buffer_len as i32);
208        let result_buffer = fun.call(&mut self.store, arg_buffer)?;
209
210        // create a buffer to read the (ptr, length) pair into
211        // this is a total of 4 + 4 = 8 bytes.
212        let buffer = &mut [0; 8];
213        plugin_memory.read(&mut self.store, result_buffer as usize, buffer)?;
214
215        // use these bytes (wasm stores things little-endian)
216        // to get a pointer to the buffer and its length
217        let b = buffer;
218        let result_buffer_ptr = u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize;
219        let result_buffer_len = u32::from_le_bytes([b[4], b[5], b[6], b[7]]) as usize;
220        let result_buffer_end = result_buffer_ptr + result_buffer_len;
221
222        // read the buffer at this point into a byte array
223        // deserialize the byte array into the provided serde type
224        let result = &plugin_memory.data(&mut self.store)[result_buffer_ptr..result_buffer_end];
225        let result = bincode::deserialize(result)?;
226
227        // TODO: this is handled wasm-side, but I'd like to double-check
228        // // deallocate the argument buffer
229        // self.free_buffer.call(&mut self.store, arg_buffer);
230
231        return Ok(result);
232    }
233}