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