plugin.rs

  1use std::future::Future;
  2
  3use std::{fs::File, marker::PhantomData, path::Path};
  4
  5use anyhow::{anyhow, Error};
  6use serde::{de::DeserializeOwned, Serialize};
  7
  8use wasi_common::{dir, file};
  9use wasmtime::Memory;
 10use wasmtime::{
 11    AsContext, AsContextMut, Caller, Config, Engine, Extern, Instance, Linker, Module, Store, Trap,
 12    TypedFunc,
 13};
 14use wasmtime_wasi::{Dir, WasiCtx, WasiCtxBuilder};
 15
 16/// Represents a resource currently managed by the plugin, like a file descriptor.
 17pub struct PluginResource(u32);
 18
 19/// This is the buffer that is used Host side.
 20/// Note that it mirrors the functionality of
 21/// the `__Buffer` found in the `plugin/src/lib.rs` prelude.
 22struct WasiBuffer {
 23    ptr: u32,
 24    len: u32,
 25}
 26
 27impl WasiBuffer {
 28    pub fn into_u64(self) -> u64 {
 29        ((self.ptr as u64) << 32) | (self.len as u64)
 30    }
 31
 32    pub fn from_u64(packed: u64) -> Self {
 33        WasiBuffer {
 34            ptr: (packed >> 32) as u32,
 35            len: packed as u32,
 36        }
 37    }
 38}
 39
 40/// Represents a typed WebAssembly function.
 41pub struct WasiFn<A: Serialize, R: DeserializeOwned> {
 42    function: TypedFunc<u64, u64>,
 43    _function_type: PhantomData<fn(A) -> R>,
 44}
 45
 46impl<A: Serialize, R: DeserializeOwned> Copy for WasiFn<A, R> {}
 47
 48impl<A: Serialize, R: DeserializeOwned> Clone for WasiFn<A, R> {
 49    fn clone(&self) -> Self {
 50        Self {
 51            function: self.function,
 52            _function_type: PhantomData,
 53        }
 54    }
 55}
 56
 57/// This struct is used to build a new [`Plugin`], using the builder pattern.
 58/// Create a new default plugin with `PluginBuilder::new_with_default_ctx`,
 59/// and add host-side exported functions using `host_function` and `host_function_async`.
 60/// Finalize the plugin by calling [`init`].
 61pub struct PluginBuilder {
 62    wasi_ctx: WasiCtx,
 63    engine: Engine,
 64    linker: Linker<WasiCtxAlloc>,
 65}
 66
 67impl PluginBuilder {
 68    /// Create a new [`PluginBuilder`] with the given WASI context.
 69    /// Using the default context is a safe bet, see [`new_with_default_context`].
 70    pub fn new(wasi_ctx: WasiCtx) -> Result<Self, Error> {
 71        let mut config = Config::default();
 72        config.async_support(true);
 73        // config.epoch_interruption(true);
 74        let engine = Engine::new(&config)?;
 75        let linker = Linker::new(&engine);
 76
 77        Ok(PluginBuilder {
 78            // host_functions: HashMap::new(),
 79            wasi_ctx,
 80            engine,
 81            linker,
 82        })
 83    }
 84
 85    /// Create a new `PluginBuilder` that inherits the
 86    /// host processes' access to `stdout` and `stderr`.
 87    pub fn new_with_default_ctx() -> Result<Self, Error> {
 88        let wasi_ctx = WasiCtxBuilder::new()
 89            .inherit_stdout()
 90            .inherit_stderr()
 91            .build();
 92        Self::new(wasi_ctx)
 93    }
 94
 95    /// Add an `async` host function. See [`host_function`] for details.
 96    pub fn host_function_async<F, A, R, Fut>(
 97        mut self,
 98        name: &str,
 99        function: F,
100    ) -> Result<Self, Error>
101    where
102        F: Fn(A) -> Fut + Send + Sync + 'static,
103        Fut: Future<Output = R> + Send + 'static,
104        A: DeserializeOwned + Send + 'static,
105        R: Serialize + Send + Sync + 'static,
106    {
107        self.linker.func_wrap1_async(
108            "env",
109            &format!("__{}", name),
110            move |mut caller: Caller<'_, WasiCtxAlloc>, packed_buffer: u64| {
111                // TODO: use try block once avaliable
112                let result: Result<(WasiBuffer, Memory, _), Trap> = (|| {
113                    // grab a handle to the memory
114                    let mut plugin_memory = match caller.get_export("memory") {
115                        Some(Extern::Memory(mem)) => mem,
116                        _ => return Err(Trap::new("Could not grab slice of plugin memory"))?,
117                    };
118
119                    let buffer = WasiBuffer::from_u64(packed_buffer);
120
121                    // get the args passed from Guest
122                    let args =
123                        Plugin::buffer_to_bytes(&mut plugin_memory, caller.as_context(), &buffer)?;
124
125                    let args: A = Plugin::deserialize_to_type(&args)?;
126
127                    // Call the Host-side function
128                    let result = function(args);
129
130                    Ok((buffer, plugin_memory, result))
131                })();
132
133                Box::new(async move {
134                    let (buffer, mut plugin_memory, future) = result?;
135
136                    let result: R = future.await;
137                    let result: Result<Vec<u8>, Error> = Plugin::serialize_to_bytes(result)
138                        .map_err(|_| {
139                            Trap::new("Could not serialize value returned from function").into()
140                        });
141                    let result = result?;
142
143                    Plugin::buffer_to_free(caller.data().free_buffer(), &mut caller, buffer)
144                        .await?;
145
146                    let buffer = Plugin::bytes_to_buffer(
147                        caller.data().alloc_buffer(),
148                        &mut plugin_memory,
149                        &mut caller,
150                        result,
151                    )
152                    .await?;
153
154                    Ok(buffer.into_u64())
155                })
156            },
157        )?;
158        Ok(self)
159    }
160
161    /// Add a new host function to the given `PluginBuilder`.
162    /// A host function is a function defined host-side, in Rust,
163    /// that is accessible guest-side, in WebAssembly.
164    /// You can specify host-side functions to import using
165    /// the `#[input]` macro attribute:
166    /// ```ignore
167    /// #[input]
168    /// fn total(counts: Vec<f64>) -> f64;
169    /// ```
170    /// When loading a plugin, you need to provide all host functions the plugin imports:
171    /// ```ignore
172    /// let plugin = PluginBuilder::new_with_default_context()
173    ///     .host_function("total", |counts| counts.iter().fold(0.0, |tot, n| tot + n))
174    ///     // and so on...
175    /// ```
176    /// And that's a wrap!
177    pub fn host_function<A, R>(
178        mut self,
179        name: &str,
180        function: impl Fn(A) -> R + Send + Sync + 'static,
181    ) -> Result<Self, Error>
182    where
183        A: DeserializeOwned + Send,
184        R: Serialize + Send + Sync,
185    {
186        self.linker.func_wrap1_async(
187            "env",
188            &format!("__{}", name),
189            move |mut caller: Caller<'_, WasiCtxAlloc>, packed_buffer: u64| {
190                // TODO: use try block once avaliable
191                let result: Result<(WasiBuffer, Memory, Vec<u8>), Trap> = (|| {
192                    // grab a handle to the memory
193                    let mut plugin_memory = match caller.get_export("memory") {
194                        Some(Extern::Memory(mem)) => mem,
195                        _ => return Err(Trap::new("Could not grab slice of plugin memory"))?,
196                    };
197
198                    let buffer = WasiBuffer::from_u64(packed_buffer);
199
200                    // get the args passed from Guest
201                    let args = Plugin::buffer_to_type(&mut plugin_memory, &mut caller, &buffer)?;
202
203                    // Call the Host-side function
204                    let result: R = function(args);
205
206                    // Serialize the result back to guest
207                    let result = Plugin::serialize_to_bytes(result).map_err(|_| {
208                        Trap::new("Could not serialize value returned from function")
209                    })?;
210
211                    Ok((buffer, plugin_memory, result))
212                })();
213
214                Box::new(async move {
215                    let (buffer, mut plugin_memory, result) = result?;
216
217                    Plugin::buffer_to_free(caller.data().free_buffer(), &mut caller, buffer)
218                        .await?;
219
220                    let buffer = Plugin::bytes_to_buffer(
221                        caller.data().alloc_buffer(),
222                        &mut plugin_memory,
223                        &mut caller,
224                        result,
225                    )
226                    .await?;
227
228                    Ok(buffer.into_u64())
229                })
230            },
231        )?;
232        Ok(self)
233    }
234
235    /// Initializes a [`Plugin`] from a given compiled Wasm module.
236    /// Both binary (`.wasm`) and text (`.wat`) module formats are supported.
237    pub async fn init<T: AsRef<[u8]>>(self, precompiled: bool, module: T) -> Result<Plugin, Error> {
238        Plugin::init(precompiled, module.as_ref().to_vec(), self).await
239    }
240}
241
242#[derive(Copy, Clone)]
243struct WasiAlloc {
244    alloc_buffer: TypedFunc<u32, u32>,
245    free_buffer: TypedFunc<u64, ()>,
246}
247
248struct WasiCtxAlloc {
249    wasi_ctx: WasiCtx,
250    alloc: Option<WasiAlloc>,
251}
252
253impl WasiCtxAlloc {
254    fn alloc_buffer(&self) -> TypedFunc<u32, u32> {
255        self.alloc
256            .expect("allocator has been not initialized, cannot allocate buffer!")
257            .alloc_buffer
258    }
259
260    fn free_buffer(&self) -> TypedFunc<u64, ()> {
261        self.alloc
262            .expect("allocator has been not initialized, cannot free buffer!")
263            .free_buffer
264    }
265
266    fn init_alloc(&mut self, alloc: WasiAlloc) {
267        self.alloc = Some(alloc)
268    }
269}
270
271/// Represents a WebAssembly plugin, with access to the WebAssembly System Inferface.
272/// Build a new plugin using [`PluginBuilder`].
273pub struct Plugin {
274    store: Store<WasiCtxAlloc>,
275    instance: Instance,
276}
277
278impl Plugin {
279    /// Dumps the *entirety* of Wasm linear memory to `stdout`.
280    /// Don't call this unless you're debugging a memory issue!
281    pub fn dump_memory(data: &[u8]) {
282        for (i, byte) in data.iter().enumerate() {
283            if i % 32 == 0 {
284                println!();
285            }
286            if i % 4 == 0 {
287                print!("|");
288            }
289            if *byte == 0 {
290                print!("__")
291            } else {
292                print!("{:02x}", byte);
293            }
294        }
295        println!();
296    }
297
298    async fn init(
299        precompiled: bool,
300        module: Vec<u8>,
301        plugin: PluginBuilder,
302    ) -> Result<Self, Error> {
303        // initialize the WebAssembly System Interface context
304        let engine = plugin.engine;
305        let mut linker = plugin.linker;
306        wasmtime_wasi::add_to_linker(&mut linker, |s| &mut s.wasi_ctx)?;
307
308        // create a store, note that we can't initialize the allocator,
309        // because we can't grab the functions until initialized.
310        let mut store: Store<WasiCtxAlloc> = Store::new(
311            &engine,
312            WasiCtxAlloc {
313                wasi_ctx: plugin.wasi_ctx,
314                alloc: None,
315            },
316        );
317        // store.epoch_deadline_async_yield_and_update(todo!());
318        let module = if precompiled {
319            unsafe { Module::deserialize(&engine, module)? }
320        } else {
321            Module::new(&engine, module)?
322        };
323
324        // load the provided module into the asynchronous runtime
325        linker.module_async(&mut store, "", &module).await?;
326        let instance = linker.instantiate_async(&mut store, &module).await?;
327
328        // now that the module is initialized,
329        // we can initialize the store's allocator
330        let alloc_buffer = instance.get_typed_func(&mut store, "__alloc_buffer")?;
331        let free_buffer = instance.get_typed_func(&mut store, "__free_buffer")?;
332        store.data_mut().init_alloc(WasiAlloc {
333            alloc_buffer,
334            free_buffer,
335        });
336
337        Ok(Plugin { store, instance })
338    }
339
340    /// Attaches a file or directory the the given system path to the runtime.
341    /// Note that the resource must be freed by calling `remove_resource` afterwards.
342    pub fn attach_path<T: AsRef<Path>>(&mut self, path: T) -> Result<PluginResource, Error> {
343        // grab the WASI context
344        let ctx = self.store.data_mut();
345
346        // open the file we want, and convert it into the right type
347        // this is a footgun and a half
348        let file = File::open(&path).unwrap();
349        let dir = Dir::from_std_file(file);
350        let dir = Box::new(wasmtime_wasi::dir::Dir::from_cap_std(dir));
351
352        // grab an empty file descriptor, specify capabilities
353        let fd = ctx.wasi_ctx.table().push(Box::new(()))?;
354        let caps = dir::DirCaps::all();
355        let file_caps = file::FileCaps::all();
356
357        // insert the directory at the given fd,
358        // return a handle to the resource
359        ctx.wasi_ctx
360            .insert_dir(fd, dir, caps, file_caps, path.as_ref().to_path_buf());
361        Ok(PluginResource(fd))
362    }
363
364    /// Returns `true` if the resource existed and was removed.
365    /// Currently the only resource we support is adding scoped paths (e.g. folders and files)
366    /// to plugins using [`attach_path`].
367    pub fn remove_resource(&mut self, resource: PluginResource) -> Result<(), Error> {
368        self.store
369            .data_mut()
370            .wasi_ctx
371            .table()
372            .delete(resource.0)
373            .ok_or_else(|| anyhow!("Resource did not exist, but a valid handle was passed in"))?;
374        Ok(())
375    }
376
377    // So this call function is kinda a dance, I figured it'd be a good idea to document it.
378    // the high level is we take a serde type, serialize it to a byte array,
379    // (we're doing this using bincode for now)
380    // then toss that byte array into webassembly.
381    // webassembly grabs that byte array, does some magic,
382    // and serializes the result into yet another byte array.
383    // we then grab *that* result byte array and deserialize it into a result.
384    //
385    // phew...
386    //
387    // now the problem is, webassambly doesn't support buffers.
388    // only really like i32s, that's it (yeah, it's sad. Not even unsigned!)
389    // (ok, I'm exaggerating a bit).
390    //
391    // the Wasm function that this calls must have a very specific signature:
392    //
393    // fn(pointer to byte array: i32, length of byte array: i32)
394    //     -> pointer to (
395    //            pointer to byte_array: i32,
396    //            length of byte array: i32,
397    //     ): i32
398    //
399    // This pair `(pointer to byte array, length of byte array)` is called a `Buffer`
400    // and can be found in the cargo_test plugin.
401    //
402    // so on the wasm side, we grab the two parameters to the function,
403    // stuff them into a `Buffer`,
404    // and then pray to the `unsafe` Rust gods above that a valid byte array pops out.
405    //
406    // On the flip side, when returning from a wasm function,
407    // we convert whatever serialized result we get into byte array,
408    // which we stuff into a Buffer and allocate on the heap,
409    // which pointer to we then return.
410    // Note the double indirection!
411    //
412    // So when returning from a function, we actually leak memory *twice*:
413    //
414    // 1) once when we leak the byte array
415    // 2) again when we leak the allocated `Buffer`
416    //
417    // This isn't a problem because Wasm stops executing after the function returns,
418    // so the heap is still valid for our inspection when we want to pull things out.
419
420    /// Serializes a given type to bytes.
421    fn serialize_to_bytes<A: Serialize>(item: A) -> Result<Vec<u8>, Error> {
422        // serialize the argument using bincode
423        let bytes = bincode::serialize(&item)?;
424        Ok(bytes)
425    }
426
427    /// Deserializes a given type from bytes.
428    fn deserialize_to_type<R: DeserializeOwned>(bytes: &[u8]) -> Result<R, Error> {
429        // serialize the argument using bincode
430        let bytes = bincode::deserialize(bytes)?;
431        Ok(bytes)
432    }
433
434    // fn deserialize<R: DeserializeOwned>(
435    //     plugin_memory: &mut Memory,
436    //     mut store: impl AsContextMut<Data = WasiCtxAlloc>,
437    //     buffer: WasiBuffer,
438    // ) -> Result<R, Error> {
439    //     let buffer_start = buffer.ptr as usize;
440    //     let buffer_end = buffer_start + buffer.len as usize;
441
442    //     // read the buffer at this point into a byte array
443    //     // deserialize the byte array into the provided serde type
444    //     let item = &plugin_memory.data(store.as_context())[buffer_start..buffer_end];
445    //     let item = bincode::deserialize(bytes)?;
446    //     Ok(item)
447    // }
448
449    /// Takes an item, allocates a buffer, serializes the argument to that buffer,
450    /// and returns a (ptr, len) pair to that buffer.
451    async fn bytes_to_buffer(
452        alloc_buffer: TypedFunc<u32, u32>,
453        plugin_memory: &mut Memory,
454        mut store: impl AsContextMut<Data = WasiCtxAlloc>,
455        item: Vec<u8>,
456    ) -> Result<WasiBuffer, Error> {
457        // allocate a buffer and write the argument to that buffer
458        let len = item.len() as u32;
459        let ptr = alloc_buffer.call_async(&mut store, len).await?;
460        plugin_memory.write(&mut store, ptr as usize, &item)?;
461        Ok(WasiBuffer { ptr, len })
462    }
463
464    /// Takes a `(ptr, len)` pair and returns the corresponding deserialized buffer.
465    fn buffer_to_type<R: DeserializeOwned>(
466        plugin_memory: &Memory,
467        store: impl AsContext<Data = WasiCtxAlloc>,
468        buffer: &WasiBuffer,
469    ) -> Result<R, Error> {
470        let buffer_start = buffer.ptr as usize;
471        let buffer_end = buffer_start + buffer.len as usize;
472
473        // read the buffer at this point into a byte array
474        // deserialize the byte array into the provided serde type
475        let result = &plugin_memory.data(store.as_context())[buffer_start..buffer_end];
476        let result = bincode::deserialize(result)?;
477
478        Ok(result)
479    }
480
481    /// Takes a `(ptr, len)` pair and returns the corresponding deserialized buffer.
482    fn buffer_to_bytes<'a>(
483        plugin_memory: &'a Memory,
484        store: wasmtime::StoreContext<'a, WasiCtxAlloc>,
485        buffer: &'a WasiBuffer,
486    ) -> Result<&'a [u8], Error> {
487        let buffer_start = buffer.ptr as usize;
488        let buffer_end = buffer_start + buffer.len as usize;
489
490        // read the buffer at this point into a byte array
491        // deserialize the byte array into the provided serde type
492        let result = &plugin_memory.data(store)[buffer_start..buffer_end];
493        Ok(result)
494    }
495
496    async fn buffer_to_free(
497        free_buffer: TypedFunc<u64, ()>,
498        mut store: impl AsContextMut<Data = WasiCtxAlloc>,
499        buffer: WasiBuffer,
500    ) -> Result<(), Error> {
501        // deallocate the argument buffer
502        Ok(free_buffer
503            .call_async(&mut store, buffer.into_u64())
504            .await?)
505    }
506
507    /// Retrieves the handle to a function of a given type.
508    pub fn function<A: Serialize, R: DeserializeOwned, T: AsRef<str>>(
509        &mut self,
510        name: T,
511    ) -> Result<WasiFn<A, R>, Error> {
512        let fun_name = format!("__{}", name.as_ref());
513        let fun = self
514            .instance
515            .get_typed_func::<u64, u64, _>(&mut self.store, &fun_name)?;
516        Ok(WasiFn {
517            function: fun,
518            _function_type: PhantomData,
519        })
520    }
521
522    /// Asynchronously calls a function defined Guest-side.
523    pub async fn call<A: Serialize, R: DeserializeOwned>(
524        &mut self,
525        handle: &WasiFn<A, R>,
526        arg: A,
527    ) -> Result<R, Error> {
528        let mut plugin_memory = self
529            .instance
530            .get_memory(&mut self.store, "memory")
531            .ok_or_else(|| anyhow!("Could not grab slice of plugin memory"))?;
532
533        // write the argument to linear memory
534        // this returns a (ptr, lentgh) pair
535        let arg_buffer = Self::bytes_to_buffer(
536            self.store.data().alloc_buffer(),
537            &mut plugin_memory,
538            &mut self.store,
539            Self::serialize_to_bytes(arg)?,
540        )
541        .await?;
542
543        // call the function, passing in the buffer and its length
544        // this returns a ptr to a (ptr, lentgh) pair
545        let result_buffer = handle
546            .function
547            .call_async(&mut self.store, arg_buffer.into_u64())
548            .await?;
549
550        Self::buffer_to_type(
551            &mut plugin_memory,
552            &mut self.store,
553            &WasiBuffer::from_u64(result_buffer),
554        )
555    }
556}