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
use std::collections::BTreeMap;

use crate::*;

/// Plugin contains everything needed to execute a WASM function
pub struct Plugin {
    pub module: Module,
    pub linker: Linker<Internal>,
    pub instance: Instance,
    pub last_error: Option<std::ffi::CString>,
    pub memory: PluginMemory,
    pub manifest: Manifest,
}

pub struct Internal {
    pub input_offset: usize,
    pub input_length: usize,
    pub output_offset: usize,
    pub output_length: usize,
    pub vars: BTreeMap<String, Vec<u8>>,
    pub wasi: wasmtime_wasi::WasiCtx,
    pub plugin: *mut Plugin,
}

impl Internal {
    fn new(manifest: &Manifest) -> Result<Self, Error> {
        let mut wasi = wasmtime_wasi::WasiCtxBuilder::new();
        for (k, v) in manifest.as_ref().config.iter() {
            wasi = wasi.env(k, v)?;
        }
        Ok(Internal {
            input_offset: 0,
            input_length: 0,
            output_offset: 0,
            output_length: 0,
            wasi: wasi.build(),
            vars: BTreeMap::new(),
            plugin: std::ptr::null_mut(),
        })
    }
}

const EXPORT_MODULE_NAME: &str = "env";

impl Plugin {
    /// Create a new plugin from the given WASM code
    pub fn new(wasm: impl AsRef<[u8]>, with_wasi: bool) -> Result<Plugin, Error> {
        let engine = Engine::default();
        let (manifest, modules) = Manifest::new(&engine, wasm.as_ref())?;
        let mut store = Store::new(&engine, Internal::new(&manifest)?);
        let memory = Memory::new(&mut store, MemoryType::new(4, manifest.as_ref().memory.max))?;
        let mut memory = PluginMemory::new(store, memory);

        let mut linker = Linker::new(&engine);
        linker.allow_shadowing(true);

        if with_wasi {
            wasmtime_wasi::add_to_linker(&mut linker, |x: &mut Internal| &mut x.wasi)?;
        }

        // Get the `main` module, or the last one if `main` doesn't exist
        let (main_name, main) = modules.get("main").map(|x| ("main", x)).unwrap_or_else(|| {
            let entry = modules.iter().last().unwrap();
            (entry.0.as_str(), entry.1)
        });

        // Collect exports
        let mut exports = BTreeMap::new();
        for (_name, module) in modules.iter() {
            for export in module.exports() {
                exports.insert(export.name(), export);
            }
        }

        macro_rules! define_funcs {
            ($m:expr, { $($name:ident($($args:expr),*) $(-> $($r:expr),*)?);* $(;)?}) => {
                match $m {
                $(
                    concat!("extism_", stringify!($name)) => {
                        let t = FuncType::new([$($args),*], [$($($r),*)?]);
                        let f = Func::new(&mut memory.store, t, export::$name);
                        linker.define(EXPORT_MODULE_NAME, concat!("extism_", stringify!($name)), Extern::Func(f))?;
                        continue
                    }
                )*
                    _ => ()
                }
            };
        }

        // Add builtins
        for (_name, module) in modules.iter() {
            for import in module.imports() {
                let m = import.module();
                let n = import.name();
                use ValType::*;

                if m == EXPORT_MODULE_NAME {
                    define_funcs!(n,  {
                        alloc(I64) -> I64;
                        free(I64);
                        load_u8(I64) -> I32;
                        load_u32(I64) -> I32;
                        load_u64(I64) -> I64;
                        store_u8(I64, I32);
                        store_u32(I64, I32);
                        store_u64(I64, I64);
                        input_offset() -> I64;
                        output_set(I64, I64);
                        error_set(I64);
                        config_get(I64) -> I64;
                        var_get(I64) -> I64;
                        var_set(I64, I64);
                        http_request(I64) -> I64;
                        length(I64) -> I64;
                    });
                }

                // Define memory or check to ensure the symbol is exported by another module
                // since it doesn't match one of our known exports
                match (m, n) {
                    ("env", "memory") => {
                        linker.define(m, n, Extern::Memory(memory.memory))?;
                    }
                    (module_name, name) => {
                        if !module_name.starts_with("wasi") && !exports.contains_key(name) {
                            panic!("Invalid export: {m}::{n}")
                        }
                    }
                }
            }
        }

        // Add modules to linker
        for (name, module) in modules.iter() {
            if name != main_name {
                linker.module(&mut memory.store, name, module)?;
                linker.alias_module(name, "env")?;
            }
        }

        let instance = linker.instantiate(&mut memory.store, main)?;

        Ok(Plugin {
            module: main.clone(),
            linker,
            memory,
            instance,
            last_error: None,
            manifest,
        })
    }

    /// Get a function by name
    pub fn get_func(&mut self, function: impl AsRef<str>) -> Option<Func> {
        self.instance
            .get_func(&mut self.memory.store, function.as_ref())
    }

    /// Set `last_error` field
    pub fn set_error(&mut self, e: impl std::fmt::Debug) {
        let x = format!("{:?}", e).into_bytes();
        let e = unsafe { std::ffi::CString::from_vec_unchecked(x) };
        self.last_error = Some(e);
    }

    pub fn error<E>(&mut self, e: impl std::fmt::Debug, x: E) -> E {
        self.set_error(e);
        x
    }

    /// Unset `last_error` field
    pub fn clear_error(&mut self) {
        self.last_error = None;
    }

    /// Store input in memory and initialize `Internal` pointer
    pub fn set_input(&mut self, handle: MemoryBlock) {
        let ptr = self as *mut _;
        let internal = self.memory.store.data_mut();
        internal.input_offset = handle.offset;
        internal.input_length = handle.length;
        internal.plugin = ptr;
    }

    #[cfg(feature = "debug")]
    pub fn dump_memory(&self) {
        self.memory.dump();
    }
}

/// A registry for plugins
pub static mut PLUGINS: std::sync::Mutex<Vec<Plugin>> = std::sync::Mutex::new(Vec::new());