mirror of
https://github.com/extism/extism.git
synced 2026-01-11 14:58:01 -05:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e31806cdb1 | ||
|
|
c2866a7358 | ||
|
|
34096bd9c0 | ||
|
|
d2a3699f43 | ||
|
|
b6e1caad07 | ||
|
|
e979987dc7 | ||
|
|
ef2eeab6e3 | ||
|
|
9da8088ebf | ||
|
|
7c60b9340a | ||
|
|
00074fd56d | ||
|
|
f0c9640e1e | ||
|
|
d48dc4021c | ||
|
|
10e44c0006 | ||
|
|
b7fa319cb9 | ||
|
|
d04e2e42bf | ||
|
|
6d2735cec7 | ||
|
|
b1d0f335b3 | ||
|
|
3a7768ffd5 | ||
|
|
ee8c41ab26 | ||
|
|
8312e98463 | ||
|
|
17a546b2db |
4
.github/workflows/release.yml
vendored
4
.github/workflows/release.yml
vendored
@@ -61,10 +61,10 @@ jobs:
|
||||
static-pc-in: 'extism-static.pc.in'
|
||||
- os: 'ubuntu'
|
||||
target: 'x86_64-unknown-linux-musl'
|
||||
artifact: ''
|
||||
artifact: 'libextism.so'
|
||||
static-artifact: 'libextism.a'
|
||||
static-dll-artifact: ''
|
||||
pc-in: ''
|
||||
pc-in: 'extism.pc.in'
|
||||
static-pc-in: 'extism-static.pc.in'
|
||||
- os: 'windows'
|
||||
target: 'x86_64-pc-windows-gnu'
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
[](https://extism.org/discord)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ description = "Traits to make Rust types usable with Extism"
|
||||
anyhow = "1.0.75"
|
||||
base64 = "~0.22"
|
||||
bytemuck = {version = "1.14.0", optional = true }
|
||||
prost = { version = "0.12.0", optional = true }
|
||||
prost = { version = "0.13.1", optional = true }
|
||||
protobuf = { version = "3.2.0", optional = true }
|
||||
rmp-serde = { version = "1.1.2", optional = true }
|
||||
serde = "1.0.186"
|
||||
|
||||
@@ -81,10 +81,10 @@ mod tests {
|
||||
c: true,
|
||||
};
|
||||
let raw = Raw(&x).to_bytes().unwrap();
|
||||
let y = Raw::from_bytes(&raw).unwrap();
|
||||
let y = Raw::from_bytes(raw).unwrap();
|
||||
assert_eq!(&x, y.0);
|
||||
|
||||
let y: Result<Raw<[u8; std::mem::size_of::<TestRaw>()]>, Error> = Raw::from_bytes(&raw);
|
||||
let y: Result<Raw<[u8; std::mem::size_of::<TestRaw>()]>, Error> = Raw::from_bytes(raw);
|
||||
assert!(y.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -546,7 +546,8 @@ pub unsafe fn reset() {
|
||||
MemoryRoot::new().reset()
|
||||
}
|
||||
|
||||
/// Set the error message offset
|
||||
/// Set the error message offset, the handle passed to this
|
||||
/// function should not be freed after this call
|
||||
#[no_mangle]
|
||||
pub unsafe fn error_set(h: Handle) {
|
||||
let root = MemoryRoot::new();
|
||||
|
||||
@@ -279,7 +279,7 @@ pub struct Manifest {
|
||||
/// the path on disk to the path it should be available inside the plugin.
|
||||
/// For example, `".": "/tmp"` would mount the current directory as `/tmp` inside the module
|
||||
#[serde(default)]
|
||||
pub allowed_paths: Option<BTreeMap<PathBuf, PathBuf>>,
|
||||
pub allowed_paths: Option<BTreeMap<String, PathBuf>>,
|
||||
|
||||
/// The plugin timeout in milliseconds
|
||||
#[serde(default)]
|
||||
@@ -337,8 +337,7 @@ impl Manifest {
|
||||
}
|
||||
|
||||
/// Add a path to `allowed_paths`
|
||||
pub fn with_allowed_path(mut self, src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Self {
|
||||
let src = src.as_ref().to_path_buf();
|
||||
pub fn with_allowed_path(mut self, src: String, dest: impl AsRef<Path>) -> Self {
|
||||
let dest = dest.as_ref().to_path_buf();
|
||||
match &mut self.allowed_paths {
|
||||
Some(p) => {
|
||||
@@ -355,7 +354,7 @@ impl Manifest {
|
||||
}
|
||||
|
||||
/// Set `allowed_paths`
|
||||
pub fn with_allowed_paths(mut self, paths: impl Iterator<Item = (PathBuf, PathBuf)>) -> Self {
|
||||
pub fn with_allowed_paths(mut self, paths: impl Iterator<Item = (String, PathBuf)>) -> Self {
|
||||
self.allowed_paths = Some(paths.collect());
|
||||
self
|
||||
}
|
||||
|
||||
@@ -9,8 +9,9 @@ repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
wasmtime = ">= 20.0.0, < 22.0.0"
|
||||
wasi-common = ">= 20.0.0, < 22.0.0"
|
||||
wasmtime = ">= 20.0.0, < 24.0.0"
|
||||
wasi-common = ">= 20.0.0, < 24.0.0"
|
||||
wiggle = ">= 20.0.0, < 24.0.0"
|
||||
anyhow = "1"
|
||||
serde = {version = "1", features = ["derive"]}
|
||||
serde_json = "1"
|
||||
@@ -33,7 +34,7 @@ register-filesystem = [] # enables wasm to be loaded from disk
|
||||
http = ["ureq"] # enables extism_http_request
|
||||
|
||||
[build-dependencies]
|
||||
cbindgen = { version = "0.26", default-features = false }
|
||||
cbindgen = { version = "0.27", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = "0.5.1"
|
||||
|
||||
@@ -12,7 +12,7 @@ To use the `extism` crate, you can add it to your Cargo file:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
extism = "1.2.0"
|
||||
extism = "1.4.1"
|
||||
```
|
||||
|
||||
## Environment variables
|
||||
|
||||
@@ -35,6 +35,21 @@ pub fn create_plugin(c: &mut Criterion) {
|
||||
});
|
||||
}
|
||||
|
||||
pub fn create_plugin_no_cache(c: &mut Criterion) {
|
||||
let mut g = c.benchmark_group("create");
|
||||
g.noise_threshold(1.0);
|
||||
g.significance_level(0.2);
|
||||
g.bench_function("create_plugin_no_cache", |b| {
|
||||
b.iter(|| {
|
||||
let _plugin = PluginBuilder::new(COUNT_VOWELS)
|
||||
.with_cache_disabled()
|
||||
.with_wasi(true)
|
||||
.build()
|
||||
.unwrap();
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, PartialEq)]
|
||||
struct Count {
|
||||
count: u32,
|
||||
@@ -251,6 +266,7 @@ criterion_group!(
|
||||
reflect_linked,
|
||||
basic,
|
||||
create_plugin,
|
||||
create_plugin_no_cache,
|
||||
count_vowels
|
||||
);
|
||||
criterion_main!(benches);
|
||||
|
||||
33
runtime/examples/fs.rs
Normal file
33
runtime/examples/fs.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use extism::*;
|
||||
fn main() {
|
||||
let url = Wasm::file("../wasm/read_write.wasm");
|
||||
let manifest = Manifest::new([url])
|
||||
.with_allowed_path("ro:src/tests/data".to_string(), "/data")
|
||||
.with_config_key("path", "/data/data.txt");
|
||||
|
||||
let mut plugin = PluginBuilder::new(manifest)
|
||||
.with_wasi(true)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
println!("trying to read file: ");
|
||||
|
||||
let res = plugin.call::<&str, &str>("try_read", "").unwrap();
|
||||
|
||||
println!("{:?}", res);
|
||||
|
||||
println!("-----------------------------------------------------");
|
||||
|
||||
println!("trying to write file: ");
|
||||
let line = format!(
|
||||
"Hello World at {:?}\n",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
);
|
||||
let res2 = plugin.call::<&str, &str>("try_write", &line).unwrap();
|
||||
|
||||
println!("{:?}", res2);
|
||||
|
||||
println!("done!");
|
||||
}
|
||||
@@ -195,6 +195,17 @@ ExtismPlugin *extism_plugin_new(const uint8_t *wasm,
|
||||
bool with_wasi,
|
||||
char **errmsg);
|
||||
|
||||
/**
|
||||
* Create a new plugin and set the number of instructions a plugin is allowed to execute
|
||||
*/
|
||||
ExtismPlugin *extism_plugin_new_with_fuel_limit(const uint8_t *wasm,
|
||||
ExtismSize wasm_size,
|
||||
const ExtismFunction **functions,
|
||||
ExtismSize n_functions,
|
||||
bool with_wasi,
|
||||
uint64_t fuel_limit,
|
||||
char **errmsg);
|
||||
|
||||
/**
|
||||
* Free the error returned by `extism_plugin_new`, errors returned from `extism_plugin_error` don't need to be freed
|
||||
*/
|
||||
@@ -302,5 +313,5 @@ bool extism_plugin_reset(ExtismPlugin *plugin);
|
||||
const char *extism_version(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif // __cplusplus
|
||||
} // extern "C"
|
||||
#endif // __cplusplus
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use anyhow::Context;
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// CurrentPlugin stores data that is available to the caller in PDK functions, this should
|
||||
@@ -160,10 +162,10 @@ impl CurrentPlugin {
|
||||
}
|
||||
|
||||
pub fn memory_bytes_mut(&mut self, handle: MemoryHandle) -> Result<&mut [u8], Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(mem) = linker.get(&mut store, EXTISM_ENV_MODULE, "memory") {
|
||||
let (linker, store) = self.linker_and_store();
|
||||
if let Some(mem) = linker.get(&mut *store, EXTISM_ENV_MODULE, "memory") {
|
||||
let mem = mem.into_memory().unwrap();
|
||||
let ptr = unsafe { mem.data_ptr(&store).add(handle.offset() as usize) };
|
||||
let ptr = unsafe { mem.data_ptr(&*store).add(handle.offset() as usize) };
|
||||
if ptr.is_null() {
|
||||
return Ok(&mut []);
|
||||
}
|
||||
@@ -174,10 +176,10 @@ impl CurrentPlugin {
|
||||
}
|
||||
|
||||
pub fn memory_bytes(&mut self, handle: MemoryHandle) -> Result<&[u8], Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(mem) = linker.get(&mut store, EXTISM_ENV_MODULE, "memory") {
|
||||
let (linker, store) = self.linker_and_store();
|
||||
if let Some(mem) = linker.get(&mut *store, EXTISM_ENV_MODULE, "memory") {
|
||||
let mem = mem.into_memory().unwrap();
|
||||
let ptr = unsafe { mem.data_ptr(&store).add(handle.offset() as usize) };
|
||||
let ptr = unsafe { mem.data_ptr(&*store).add(handle.offset() as usize) };
|
||||
if ptr.is_null() {
|
||||
return Ok(&[]);
|
||||
}
|
||||
@@ -187,20 +189,26 @@ impl CurrentPlugin {
|
||||
anyhow::bail!("{} unable to locate extism memory", self.id)
|
||||
}
|
||||
|
||||
pub fn host_context<T: Clone + 'static>(&mut self) -> Result<T, Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
let Some(Extern::Global(xs)) = linker.get(&mut store, EXTISM_ENV_MODULE, "extism_context")
|
||||
pub fn host_context<T: 'static>(&mut self) -> Result<&mut T, Error> {
|
||||
let (linker, store) = self.linker_and_store();
|
||||
let Some(Extern::Global(xs)) = linker.get(&mut *store, EXTISM_ENV_MODULE, "extism_context")
|
||||
else {
|
||||
anyhow::bail!("unable to locate an extism kernel global: extism_context",)
|
||||
};
|
||||
|
||||
let Val::ExternRef(Some(xs)) = xs.get(&mut store) else {
|
||||
let Val::ExternRef(Some(xs)) = xs.get(&mut *store) else {
|
||||
anyhow::bail!("expected extism_context to be an externref value",)
|
||||
};
|
||||
|
||||
match xs.data(&mut store)?.downcast_ref::<T>().cloned() {
|
||||
Some(xs) => Ok(xs.clone()),
|
||||
None => anyhow::bail!("could not downcast extism_context",),
|
||||
match xs
|
||||
.data_mut(&mut *store)?
|
||||
.downcast_mut::<Box<dyn std::any::Any + Send + Sync>>()
|
||||
{
|
||||
Some(xs) => match xs.downcast_mut::<T>() {
|
||||
Some(xs) => Ok(xs),
|
||||
None => anyhow::bail!("could not downcast extism_context inner value"),
|
||||
},
|
||||
None => anyhow::bail!("could not downcast extism_context"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,9 +222,13 @@ impl CurrentPlugin {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
let output = &mut [Val::I64(0)];
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "alloc") {
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(n as i64)], output)?;
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[Val::I64(n as i64)], output)
|
||||
.context("failed to allocate extism memory")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("{} unable to allocate memory", self.id);
|
||||
}
|
||||
@@ -238,11 +250,15 @@ impl CurrentPlugin {
|
||||
|
||||
/// Free a block of Extism plugin memory
|
||||
pub fn memory_free(&mut self, handle: MemoryHandle) -> Result<(), Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "free") {
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(handle.offset as i64)], &mut [])?;
|
||||
let (linker, store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "free") {
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[Val::I64(handle.offset as i64)], &mut [])
|
||||
.context("failed to free extism memory")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("unable to locate an extism kernel function: free",)
|
||||
}
|
||||
@@ -250,12 +266,16 @@ impl CurrentPlugin {
|
||||
}
|
||||
|
||||
pub fn memory_length(&mut self, offs: u64) -> Result<u64, Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
let (linker, store) = self.linker_and_store();
|
||||
let output = &mut [Val::I64(0)];
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "length") {
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(offs as i64)], output)?;
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "length") {
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[Val::I64(offs as i64)], output)
|
||||
.context("failed to get length of extism memory handle")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("unable to locate an extism kernel function: length",)
|
||||
}
|
||||
@@ -270,12 +290,16 @@ impl CurrentPlugin {
|
||||
}
|
||||
|
||||
pub fn memory_length_unsafe(&mut self, offs: u64) -> Result<u64, Error> {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
let (linker, store) = self.linker_and_store();
|
||||
let output = &mut [Val::I64(0)];
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "length_unsafe") {
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(offs as i64)], output)?;
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "length_unsafe") {
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[Val::I64(offs as i64)], output)
|
||||
.context("failed to get length of extism memory using length_unsafe")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("unable to locate an extism kernel function: length_unsafe",)
|
||||
}
|
||||
@@ -320,9 +344,20 @@ impl CurrentPlugin {
|
||||
|
||||
if let Some(a) = &manifest.allowed_paths {
|
||||
for (k, v) in a.iter() {
|
||||
let file = Box::new(wasi_common::sync::dir::Dir::from_cap_std(
|
||||
wasi_common::sync::Dir::open_ambient_dir(k, auth)?,
|
||||
));
|
||||
let readonly = k.starts_with("ro:");
|
||||
|
||||
let dir_path = if readonly { &k[3..] } else { k };
|
||||
|
||||
let dir = wasi_common::sync::dir::Dir::from_cap_std(
|
||||
wasi_common::sync::Dir::open_ambient_dir(dir_path, auth)?,
|
||||
);
|
||||
|
||||
let file: Box<dyn wasi_common::dir::WasiDir> = if readonly {
|
||||
Box::new(readonly_dir::ReadOnlyDir::new(dir))
|
||||
} else {
|
||||
Box::new(dir)
|
||||
};
|
||||
|
||||
ctx.push_preopened_dir(file, v)?;
|
||||
}
|
||||
}
|
||||
@@ -340,7 +375,7 @@ impl CurrentPlugin {
|
||||
|
||||
let memory_limiter = if let Some(pgs) = available_pages {
|
||||
let n = pgs as usize * 65536;
|
||||
Some(crate::current_plugin::MemoryLimiter {
|
||||
Some(MemoryLimiter {
|
||||
max_bytes: n,
|
||||
bytes_left: n,
|
||||
})
|
||||
@@ -403,12 +438,12 @@ impl CurrentPlugin {
|
||||
/// Clear the current plugin error
|
||||
pub fn clear_error(&mut self) {
|
||||
trace!(plugin = self.id.to_string(), "CurrentPlugin::clear_error");
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "error_set") {
|
||||
let (linker, store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "error_set") {
|
||||
let res = f
|
||||
.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(0)], &mut []);
|
||||
.call(&mut *store, &[Val::I64(0)], &mut []);
|
||||
if let Err(e) = res {
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
@@ -439,13 +474,15 @@ impl CurrentPlugin {
|
||||
pub fn set_error(&mut self, s: impl AsRef<str>) -> Result<(u64, u64), Error> {
|
||||
let s = s.as_ref();
|
||||
debug!(plugin = self.id.to_string(), "set error: {:?}", s);
|
||||
let handle = self.current_plugin_mut().memory_new(s)?;
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "error_set") {
|
||||
f.into_func().unwrap().call(
|
||||
&mut store,
|
||||
&[Val::I64(handle.offset() as i64)],
|
||||
&mut [],
|
||||
let handle = self.memory_new(s)?;
|
||||
let (linker, store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "error_set") {
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[Val::I64(handle.offset() as i64)], &mut [])
|
||||
.context("failed to set extism error")
|
||||
)?;
|
||||
Ok((handle.offset(), s.len() as u64))
|
||||
} else {
|
||||
@@ -454,10 +491,13 @@ impl CurrentPlugin {
|
||||
}
|
||||
|
||||
pub(crate) fn get_error_position(&mut self) -> (u64, u64) {
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
let (linker, store) = self.linker_and_store();
|
||||
let output = &mut [Val::I64(0)];
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "error_get") {
|
||||
if let Err(e) = f.into_func().unwrap().call(&mut store, &[], output) {
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "error_get") {
|
||||
if let Err(e) = catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func().unwrap().call(&mut *store, &[], output)
|
||||
) {
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
"unable to call extism:host/env::error_get: {:?}", e
|
||||
|
||||
@@ -279,7 +279,7 @@ impl Function {
|
||||
/// For example, the following defines a host function named `add_newline` that takes a
|
||||
/// string parameter and returns a string result:
|
||||
/// ```rust
|
||||
/// extism::host_fn!(add_newline(_user_data: (), a: String) -> String { Ok(a + "\n") });
|
||||
/// extism::host_fn!(add_newline(_user_data: (); a: String) -> String { Ok(a + "\n") });
|
||||
/// ```
|
||||
/// A few things worth noting:
|
||||
/// - The function always returns a `Result` that wraps the specified return type
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
// Makes proc-macros able to resolve `::extism` correctly
|
||||
extern crate self as extism;
|
||||
|
||||
macro_rules! catch_out_of_fuel {
|
||||
($store: expr, $x:expr) => {{
|
||||
let y = $x;
|
||||
if y.is_err() && $store.get_fuel().is_ok_and(|x| x == 0) {
|
||||
Err(Error::msg("plugin ran out of fuel"))
|
||||
} else {
|
||||
y
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub(crate) use extism_convert::*;
|
||||
pub(crate) use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
@@ -18,6 +29,7 @@ pub(crate) mod manifest;
|
||||
pub(crate) mod pdk;
|
||||
mod plugin;
|
||||
mod plugin_builder;
|
||||
mod readonly_dir;
|
||||
mod timer;
|
||||
|
||||
/// Extism C API
|
||||
@@ -77,11 +89,16 @@ pub fn set_log_callback<F: 'static + Clone + Fn(&str)>(
|
||||
filter: impl AsRef<str>,
|
||||
) -> Result<(), Error> {
|
||||
let filter = filter.as_ref();
|
||||
let cfg = tracing_subscriber::FmtSubscriber::builder().with_env_filter(
|
||||
tracing_subscriber::EnvFilter::builder()
|
||||
.with_default_directive(tracing::Level::ERROR.into())
|
||||
.parse_lossy(filter),
|
||||
);
|
||||
let is_level = tracing::Level::from_str(filter).is_ok();
|
||||
let cfg = tracing_subscriber::FmtSubscriber::builder().with_env_filter({
|
||||
let x = tracing_subscriber::EnvFilter::builder()
|
||||
.with_default_directive(tracing::Level::ERROR.into());
|
||||
if is_level {
|
||||
x.parse_lossy(format!("extism={}", filter))
|
||||
} else {
|
||||
x.parse_lossy(filter)
|
||||
}
|
||||
});
|
||||
let w = LogFunction { func };
|
||||
cfg.with_ansi(false)
|
||||
.with_writer(move || w.clone())
|
||||
|
||||
@@ -301,6 +301,13 @@ pub fn log(
|
||||
_output: &mut [Val],
|
||||
) -> Result<(), Error> {
|
||||
let data: &mut CurrentPlugin = caller.data_mut();
|
||||
|
||||
// Check if the current log level should be logged
|
||||
let global_log_level = tracing::level_filters::LevelFilter::current();
|
||||
if global_log_level == tracing::level_filters::LevelFilter::OFF || level > global_log_level {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let offset = args!(input, 0, i64) as u64;
|
||||
|
||||
let handle = match data.memory_handle(offset) {
|
||||
@@ -377,3 +384,44 @@ pub(crate) fn log_error(
|
||||
) -> Result<(), Error> {
|
||||
log(tracing::Level::ERROR, caller, input, _output)
|
||||
}
|
||||
|
||||
/// Write to logs (trace)
|
||||
/// Params: i64 (offset)
|
||||
/// Returns: none
|
||||
pub(crate) fn log_trace(
|
||||
caller: Caller<CurrentPlugin>,
|
||||
input: &[Val],
|
||||
_output: &mut [Val],
|
||||
) -> Result<(), Error> {
|
||||
log(tracing::Level::TRACE, caller, input, _output)
|
||||
}
|
||||
|
||||
/// Get the log level
|
||||
/// Params: none
|
||||
/// Returns: i32 (log level)
|
||||
pub(crate) fn get_log_level(
|
||||
mut _caller: Caller<CurrentPlugin>,
|
||||
_input: &[Val],
|
||||
output: &mut [Val],
|
||||
) -> Result<(), Error> {
|
||||
let level = tracing::level_filters::LevelFilter::current();
|
||||
if level == tracing::level_filters::LevelFilter::OFF {
|
||||
output[0] = Val::I32(i32::MAX)
|
||||
} else {
|
||||
output[0] = Val::I32(log_level_to_int(
|
||||
level.into_level().unwrap_or(tracing::Level::ERROR),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert log level to integer
|
||||
pub(crate) const fn log_level_to_int(level: tracing::Level) -> i32 {
|
||||
match level {
|
||||
tracing::Level::TRACE => 0,
|
||||
tracing::Level::DEBUG => 1,
|
||||
tracing::Level::INFO => 2,
|
||||
tracing::Level::WARN => 3,
|
||||
tracing::Level::ERROR => 4,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ use std::{
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
use crate::*;
|
||||
|
||||
pub const EXTISM_ENV_MODULE: &str = "extism:host/env";
|
||||
@@ -81,6 +83,12 @@ pub struct Plugin {
|
||||
pub(crate) store_needs_reset: bool,
|
||||
|
||||
pub(crate) debug_options: DebugOptions,
|
||||
|
||||
pub(crate) error_msg: Option<Vec<u8>>,
|
||||
|
||||
pub(crate) fuel: Option<u64>,
|
||||
|
||||
pub(crate) host_context: Rooted<ExternRef>,
|
||||
}
|
||||
|
||||
unsafe impl Send for Plugin {}
|
||||
@@ -212,14 +220,24 @@ fn add_module<T: 'static>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn relink(
|
||||
engine: &Engine,
|
||||
mut store: &mut Store<CurrentPlugin>,
|
||||
imports: &[Function],
|
||||
modules: &BTreeMap<String, Module>,
|
||||
with_wasi: bool,
|
||||
) -> Result<(InstancePre<CurrentPlugin>, Linker<CurrentPlugin>), Error> {
|
||||
) -> Result<
|
||||
(
|
||||
InstancePre<CurrentPlugin>,
|
||||
Linker<CurrentPlugin>,
|
||||
Rooted<ExternRef>,
|
||||
),
|
||||
Error,
|
||||
> {
|
||||
let mut linker = Linker::new(engine);
|
||||
linker.allow_shadowing(true);
|
||||
|
||||
// Define PDK functions
|
||||
macro_rules! add_funcs {
|
||||
($($name:ident($($args:expr),*) $(-> $($r:expr),*)?);* $(;)?) => {
|
||||
@@ -242,6 +260,8 @@ fn relink(
|
||||
log_info(I64);
|
||||
log_debug(I64);
|
||||
log_error(I64);
|
||||
log_trace(I64);
|
||||
get_log_level() -> I32;
|
||||
);
|
||||
|
||||
let mut linked = BTreeSet::new();
|
||||
@@ -274,9 +294,12 @@ fn relink(
|
||||
)?;
|
||||
}
|
||||
|
||||
let inner: Box<dyn std::any::Any + Send + Sync> = Box::new(());
|
||||
let host_context = ExternRef::new(store, inner)?;
|
||||
|
||||
let main = &modules[MAIN_KEY];
|
||||
let instance_pre = linker.instantiate_pre(main)?;
|
||||
Ok((instance_pre, linker))
|
||||
Ok((instance_pre, linker, host_context))
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
@@ -287,7 +310,14 @@ impl Plugin {
|
||||
imports: impl IntoIterator<Item = Function>,
|
||||
with_wasi: bool,
|
||||
) -> Result<Plugin, Error> {
|
||||
Self::build_new(wasm.into(), imports, with_wasi, Default::default(), None)
|
||||
Self::build_new(
|
||||
wasm.into(),
|
||||
imports,
|
||||
with_wasi,
|
||||
Default::default(),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn build_new(
|
||||
@@ -296,6 +326,7 @@ impl Plugin {
|
||||
with_wasi: bool,
|
||||
debug_options: DebugOptions,
|
||||
cache_dir: Option<Option<PathBuf>>,
|
||||
fuel: Option<u64>,
|
||||
) -> Result<Plugin, Error> {
|
||||
// Setup wasmtime types
|
||||
let mut config = Config::new();
|
||||
@@ -308,6 +339,10 @@ impl Plugin {
|
||||
.wasm_function_references(true)
|
||||
.wasm_gc(true);
|
||||
|
||||
if fuel.is_some() {
|
||||
config.consume_fuel(true);
|
||||
}
|
||||
|
||||
match cache_dir {
|
||||
Some(None) => (),
|
||||
Some(Some(path)) => {
|
||||
@@ -341,10 +376,13 @@ impl Plugin {
|
||||
CurrentPlugin::new(manifest, with_wasi, available_pages, id)?,
|
||||
);
|
||||
store.set_epoch_deadline(1);
|
||||
if let Some(fuel) = fuel {
|
||||
store.set_fuel(fuel)?;
|
||||
}
|
||||
|
||||
let imports: Vec<Function> = imports.into_iter().collect();
|
||||
let (instance_pre, linker) = relink(&engine, &mut store, &imports, &modules, with_wasi)?;
|
||||
|
||||
let (instance_pre, linker, host_context) =
|
||||
relink(&engine, &mut store, &imports, &modules, with_wasi)?;
|
||||
let timer_tx = Timer::tx();
|
||||
let mut plugin = Plugin {
|
||||
modules,
|
||||
@@ -361,6 +399,9 @@ impl Plugin {
|
||||
store_needs_reset: false,
|
||||
debug_options,
|
||||
_functions: imports,
|
||||
error_msg: None,
|
||||
fuel,
|
||||
host_context,
|
||||
};
|
||||
|
||||
plugin.current_plugin_mut().store = &mut plugin.store;
|
||||
@@ -394,7 +435,11 @@ impl Plugin {
|
||||
);
|
||||
self.store.set_epoch_deadline(1);
|
||||
|
||||
let (instance_pre, linker) = relink(
|
||||
if let Some(fuel) = self.fuel {
|
||||
self.store.set_fuel(fuel)?;
|
||||
}
|
||||
|
||||
let (instance_pre, linker, host_context) = relink(
|
||||
&engine,
|
||||
&mut self.store,
|
||||
&self._functions,
|
||||
@@ -403,6 +448,7 @@ impl Plugin {
|
||||
)?;
|
||||
self.linker = linker;
|
||||
self.instance_pre = instance_pre;
|
||||
self.host_context = host_context;
|
||||
let store = &mut self.store as *mut _;
|
||||
let linker = &mut self.linker as *mut _;
|
||||
let current_plugin = self.current_plugin_mut();
|
||||
@@ -510,10 +556,16 @@ impl Plugin {
|
||||
.linker
|
||||
.get(&mut self.store, EXTISM_ENV_MODULE, "input_set")
|
||||
{
|
||||
f.into_func().unwrap().call(
|
||||
&mut self.store,
|
||||
&[Val::I64(handle.offset() as i64), Val::I64(len as i64)],
|
||||
&mut [],
|
||||
catch_out_of_fuel!(
|
||||
&self.store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(
|
||||
&mut self.store,
|
||||
&[Val::I64(handle.offset() as i64), Val::I64(len as i64)],
|
||||
&mut [],
|
||||
)
|
||||
.context("unable to set extism input")
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -521,7 +573,8 @@ impl Plugin {
|
||||
self.linker
|
||||
.get(&mut self.store, EXTISM_ENV_MODULE, "extism_context")
|
||||
{
|
||||
ctxt.set(&mut self.store, Val::ExternRef(host_context))?;
|
||||
ctxt.set(&mut self.store, Val::ExternRef(host_context))
|
||||
.context("unable to set extism host context")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -532,7 +585,13 @@ impl Plugin {
|
||||
let id = self.id.to_string();
|
||||
|
||||
if let Some(f) = self.linker.get(&mut self.store, EXTISM_ENV_MODULE, "reset") {
|
||||
f.into_func().unwrap().call(&mut self.store, &[], &mut [])?;
|
||||
catch_out_of_fuel!(
|
||||
&self.store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut self.store, &[], &mut [])
|
||||
.context("extism reset failed")
|
||||
)?;
|
||||
} else {
|
||||
error!(plugin = &id, "call to extism:host/env::reset failed");
|
||||
}
|
||||
@@ -608,19 +667,28 @@ impl Plugin {
|
||||
|
||||
// Initialize the guest runtime
|
||||
pub(crate) fn initialize_guest_runtime(&mut self) -> Result<(), Error> {
|
||||
let mut store = &mut self.store;
|
||||
let store = &mut self.store;
|
||||
if let Some(runtime) = &self.runtime {
|
||||
trace!(plugin = self.id.to_string(), "Plugin::initialize_runtime");
|
||||
match runtime {
|
||||
GuestRuntime::Haskell { init, reactor_init } => {
|
||||
if let Some(reactor_init) = reactor_init {
|
||||
reactor_init.call(&mut store, &[], &mut [])?;
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
reactor_init
|
||||
.call(&mut *store, &[], &mut [])
|
||||
.context("failed to initialize Haskell reactor runtime")
|
||||
)?;
|
||||
}
|
||||
let mut results = vec![Val::I32(0); init.ty(&store).results().len()];
|
||||
init.call(
|
||||
&mut store,
|
||||
&[Val::I32(0), Val::I32(0)],
|
||||
results.as_mut_slice(),
|
||||
let mut results = vec![Val::I32(0); init.ty(&*store).results().len()];
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
init.call(
|
||||
&mut *store,
|
||||
&[Val::I32(0), Val::I32(0)],
|
||||
results.as_mut_slice(),
|
||||
)
|
||||
.context("failed to initialize Haskell using hs_init")
|
||||
)?;
|
||||
debug!(
|
||||
plugin = self.id.to_string(),
|
||||
@@ -628,7 +696,11 @@ impl Plugin {
|
||||
);
|
||||
}
|
||||
GuestRuntime::Wasi { init } => {
|
||||
init.call(&mut store, &[], &mut [])?;
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
init.call(&mut *store, &[], &mut [])
|
||||
.context("failed to initialize wasi runtime")
|
||||
)?;
|
||||
debug!(plugin = self.id.to_string(), "initialied WASI runtime");
|
||||
}
|
||||
}
|
||||
@@ -641,20 +713,32 @@ impl Plugin {
|
||||
fn output_memory_position(&mut self) -> Result<(u64, u64), Error> {
|
||||
let out = &mut [Val::I64(0)];
|
||||
let out_len = &mut [Val::I64(0)];
|
||||
let mut store = &mut self.store;
|
||||
let store = &mut self.store;
|
||||
if let Some(f) = self
|
||||
.linker
|
||||
.get(&mut store, EXTISM_ENV_MODULE, "output_offset")
|
||||
.get(&mut *store, EXTISM_ENV_MODULE, "output_offset")
|
||||
{
|
||||
f.into_func().unwrap().call(&mut store, &[], out)?;
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[], out)
|
||||
.context("call to set extism output offset failed")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("unable to set output")
|
||||
}
|
||||
if let Some(f) = self
|
||||
.linker
|
||||
.get(&mut store, EXTISM_ENV_MODULE, "output_length")
|
||||
.get(&mut *store, EXTISM_ENV_MODULE, "output_length")
|
||||
{
|
||||
f.into_func().unwrap().call(&mut store, &[], out_len)?;
|
||||
catch_out_of_fuel!(
|
||||
&store,
|
||||
f.into_func()
|
||||
.unwrap()
|
||||
.call(&mut *store, &[], out_len)
|
||||
.context("call to set extism output length failed")
|
||||
)?;
|
||||
} else {
|
||||
anyhow::bail!("unable to set output length")
|
||||
}
|
||||
@@ -668,10 +752,10 @@ impl Plugin {
|
||||
fn output<'a, T: FromBytes<'a>>(&'a mut self) -> Result<T, Error> {
|
||||
let offs = self.output.offset;
|
||||
let len = self.output.length;
|
||||
T::from_bytes(
|
||||
self.current_plugin_mut()
|
||||
.memory_bytes(unsafe { MemoryHandle::new(offs, len) })?,
|
||||
)
|
||||
let x = self
|
||||
.current_plugin_mut()
|
||||
.memory_bytes(unsafe { MemoryHandle::new(offs, len) })?;
|
||||
T::from_bytes(x)
|
||||
}
|
||||
|
||||
// Cache output memory and error information after call is complete
|
||||
@@ -696,26 +780,40 @@ impl Plugin {
|
||||
|
||||
// Implements the build of the `call` function, `raw_call` is also used in the SDK
|
||||
// code
|
||||
pub(crate) fn raw_call(
|
||||
pub(crate) fn raw_call<T: 'static + Send + Sync>(
|
||||
&mut self,
|
||||
lock: &mut std::sync::MutexGuard<Option<Instance>>,
|
||||
name: impl AsRef<str>,
|
||||
input: impl AsRef<[u8]>,
|
||||
host_context: Option<Rooted<ExternRef>>,
|
||||
host_context: Option<T>,
|
||||
) -> Result<i32, (Error, i32)> {
|
||||
let name = name.as_ref();
|
||||
let input = input.as_ref();
|
||||
|
||||
if let Err(e) = self.reset_store(lock) {
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
"call to Plugin::reset_store failed: {e:?}"
|
||||
);
|
||||
if let Some(fuel) = self.fuel {
|
||||
self.store.set_fuel(fuel).map_err(|x| (x, -1))?;
|
||||
}
|
||||
|
||||
catch_out_of_fuel!(&self.store, self.reset_store(lock)).map_err(|x| (x, -1))?;
|
||||
|
||||
self.instantiate(lock).map_err(|e| (e, -1))?;
|
||||
|
||||
self.set_input(input.as_ptr(), input.len(), host_context)
|
||||
// Set host context
|
||||
let r = if let Some(host_context) = host_context {
|
||||
let inner = self
|
||||
.host_context
|
||||
.data_mut(&mut self.store)
|
||||
.map_err(|x| (x, -1))?;
|
||||
if let Some(inner) = inner.downcast_mut::<Box<dyn std::any::Any + Send + Sync>>() {
|
||||
let x: Box<T> = Box::new(host_context);
|
||||
*inner = x;
|
||||
}
|
||||
Some(self.host_context)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
self.set_input(input.as_ptr(), input.len(), r)
|
||||
.map_err(|x| (x, -1))?;
|
||||
|
||||
let func = match self.get_func(lock, name) {
|
||||
@@ -752,40 +850,57 @@ impl Plugin {
|
||||
let mut results = vec![wasmtime::Val::I32(0); n_results];
|
||||
let mut res = func.call(self.store_mut(), &[], results.as_mut_slice());
|
||||
|
||||
// Reset host context
|
||||
if let Ok(inner) = self.host_context.data_mut(&mut self.store) {
|
||||
if let Some(inner) = inner.downcast_mut::<Box<dyn std::any::Any + Send + Sync>>() {
|
||||
let x: Box<dyn Any + Send + Sync> = Box::new(());
|
||||
*inner = x;
|
||||
}
|
||||
}
|
||||
|
||||
// Stop timer
|
||||
self.store
|
||||
.epoch_deadline_callback(|_| Ok(UpdateDeadline::Continue(1)));
|
||||
let _ = self.timer_tx.send(TimerAction::Stop { id: self.id });
|
||||
self.store_needs_reset = name == "_start";
|
||||
|
||||
// Get extism error
|
||||
self.get_output_after_call().map_err(|x| (x, -1))?;
|
||||
let mut rc = 0;
|
||||
if !results.is_empty() {
|
||||
rc = results[0].i32().unwrap_or(-1);
|
||||
debug!(plugin = self.id.to_string(), "got return code: {}", rc);
|
||||
}
|
||||
if self.store.get_fuel().is_ok_and(|x| x == 0) {
|
||||
res = Err(Error::msg("plugin ran out of fuel"));
|
||||
rc = -1;
|
||||
} else {
|
||||
// Get extism error
|
||||
self.get_output_after_call().map_err(|x| (x, -1))?;
|
||||
if !results.is_empty() {
|
||||
rc = results[0].i32().unwrap_or(-1);
|
||||
debug!(plugin = self.id.to_string(), "got return code: {}", rc);
|
||||
}
|
||||
|
||||
if self.output.error_offset != 0 && self.output.error_length != 0 {
|
||||
let handle = MemoryHandle {
|
||||
offset: self.output.error_offset,
|
||||
length: self.output.error_length,
|
||||
};
|
||||
if let Ok(e) = self.current_plugin_mut().memory_str(handle) {
|
||||
let x = e.to_string();
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
"call to {name} returned with error message: {}", x
|
||||
);
|
||||
if let Err(e) = res {
|
||||
res = Err(Error::msg(x).context(e));
|
||||
} else {
|
||||
res = Err(Error::msg(x))
|
||||
if self.output.error_offset != 0 && self.output.error_length != 0 {
|
||||
let handle = MemoryHandle {
|
||||
offset: self.output.error_offset,
|
||||
length: self.output.error_length,
|
||||
};
|
||||
match self.current_plugin_mut().memory_str(handle) {
|
||||
Ok(e) => {
|
||||
let x = e.to_string();
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
"call to {name} returned with error message: {}", x
|
||||
);
|
||||
if let Err(e) = res {
|
||||
res = Err(Error::msg(x).context(e));
|
||||
} else {
|
||||
res = Err(Error::msg(x))
|
||||
}
|
||||
}
|
||||
Err(msg) => {
|
||||
res = Err(Error::msg(format!(
|
||||
"Call to Extism plugin function {name} encountered an error: {}",
|
||||
msg,
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
res = Err(Error::msg(format!(
|
||||
"Call to Extism plugin function {name} encountered an error"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -897,7 +1012,7 @@ impl Plugin {
|
||||
let lock = self.instance.clone();
|
||||
let mut lock = lock.lock().unwrap();
|
||||
let data = input.to_bytes()?;
|
||||
self.raw_call(&mut lock, name, data, None)
|
||||
self.raw_call(&mut lock, name, data, None::<()>)
|
||||
.map_err(|e| e.0)
|
||||
.and_then(move |rc| {
|
||||
if rc != 0 {
|
||||
@@ -922,8 +1037,7 @@ impl Plugin {
|
||||
let lock = self.instance.clone();
|
||||
let mut lock = lock.lock().unwrap();
|
||||
let data = input.to_bytes()?;
|
||||
let ctx = ExternRef::new(&mut self.store, host_context)?;
|
||||
self.raw_call(&mut lock, name, data, Some(ctx))
|
||||
self.raw_call(&mut lock, name, data, Some(host_context))
|
||||
.map_err(|e| e.0)
|
||||
.and_then(move |_| self.output())
|
||||
}
|
||||
@@ -942,7 +1056,7 @@ impl Plugin {
|
||||
let lock = self.instance.clone();
|
||||
let mut lock = lock.lock().unwrap();
|
||||
let data = input.to_bytes().map_err(|e| (e, -1))?;
|
||||
self.raw_call(&mut lock, name, data, None)
|
||||
self.raw_call(&mut lock, name, data, None::<()>)
|
||||
.and_then(move |_| self.output().map_err(|e| (e, -1)))
|
||||
}
|
||||
|
||||
@@ -953,42 +1067,21 @@ impl Plugin {
|
||||
|
||||
pub(crate) fn clear_error(&mut self) -> Result<(), Error> {
|
||||
trace!(plugin = self.id.to_string(), "clearing error");
|
||||
self.error_msg = None;
|
||||
let (linker, mut store) = self.linker_and_store();
|
||||
if let Some(f) = linker.get(&mut store, EXTISM_ENV_MODULE, "error_set") {
|
||||
f.into_func()
|
||||
#[allow(clippy::needless_borrows_for_generic_args)]
|
||||
if let Some(f) = linker.get(&mut *store, EXTISM_ENV_MODULE, "error_set") {
|
||||
let x = f
|
||||
.into_func()
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(0)], &mut [])?;
|
||||
.call(&mut store, &[Val::I64(0)], &mut [])
|
||||
.context("unable to clear error message");
|
||||
catch_out_of_fuel!(&store, x)?;
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!("Plugin::clear_error failed, extism:host/env::error_set not found")
|
||||
}
|
||||
}
|
||||
|
||||
// A convenience method to set the plugin error and return a value
|
||||
pub(crate) fn return_error<E>(
|
||||
&mut self,
|
||||
instance_lock: &mut std::sync::MutexGuard<Option<Instance>>,
|
||||
e: impl std::fmt::Display,
|
||||
x: E,
|
||||
) -> E {
|
||||
if instance_lock.is_none() {
|
||||
error!(
|
||||
plugin = self.id.to_string(),
|
||||
"no instance, unable to set error: {}", e
|
||||
);
|
||||
return x;
|
||||
}
|
||||
match self.current_plugin_mut().set_error(e.to_string()) {
|
||||
Ok((a, b)) => {
|
||||
self.output.error_offset = a;
|
||||
self.output.error_length = b;
|
||||
}
|
||||
Err(e) => {
|
||||
error!(plugin = self.id.to_string(), "unable to set error: {e:?}")
|
||||
}
|
||||
}
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
// Enumerates the PDK languages that need some additional initialization
|
||||
|
||||
@@ -39,6 +39,7 @@ pub struct PluginBuilder<'a> {
|
||||
functions: Vec<Function>,
|
||||
debug_options: DebugOptions,
|
||||
cache_config: Option<Option<PathBuf>>,
|
||||
fuel: Option<u64>,
|
||||
}
|
||||
|
||||
impl<'a> PluginBuilder<'a> {
|
||||
@@ -50,6 +51,7 @@ impl<'a> PluginBuilder<'a> {
|
||||
functions: vec![],
|
||||
debug_options: DebugOptions::default(),
|
||||
cache_config: None,
|
||||
fuel: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,6 +150,12 @@ impl<'a> PluginBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
// Limit the number of instructions that can be executed
|
||||
pub fn with_fuel_limit(mut self, fuel: u64) -> Self {
|
||||
self.fuel = Some(fuel);
|
||||
self
|
||||
}
|
||||
|
||||
/// Generate a new plugin with the configured settings
|
||||
pub fn build(self) -> Result<Plugin, Error> {
|
||||
Plugin::build_new(
|
||||
@@ -156,6 +164,7 @@ impl<'a> PluginBuilder<'a> {
|
||||
self.wasi,
|
||||
self.debug_options,
|
||||
self.cache_config,
|
||||
self.fuel,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
109
runtime/src/readonly_dir.rs
Normal file
109
runtime/src/readonly_dir.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use crate::*;
|
||||
|
||||
use wasi_common::{Error, ErrorExt};
|
||||
|
||||
pub struct ReadOnlyDir<D: wasi_common::WasiDir> {
|
||||
inner: std::sync::Arc<D>,
|
||||
}
|
||||
|
||||
impl<D: wasi_common::WasiDir> ReadOnlyDir<D> {
|
||||
pub fn new(inner: D) -> Self {
|
||||
ReadOnlyDir {
|
||||
inner: std::sync::Arc::new(inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[wiggle::async_trait]
|
||||
impl<D: wasi_common::WasiDir> wasi_common::WasiDir for ReadOnlyDir<D> {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self.inner.as_any()
|
||||
}
|
||||
|
||||
async fn open_file(
|
||||
&self,
|
||||
symlink_follow: bool,
|
||||
path: &str,
|
||||
oflags: wasi_common::file::OFlags,
|
||||
read: bool,
|
||||
write: bool,
|
||||
fdflags: wasi_common::file::FdFlags,
|
||||
) -> Result<wasi_common::dir::OpenResult, Error> {
|
||||
if write {
|
||||
return Err(Error::not_supported());
|
||||
}
|
||||
self.inner
|
||||
.open_file(symlink_follow, path, oflags, read, false, fdflags)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_dir(&self, _path: &str) -> Result<(), Error> {
|
||||
Err(Error::not_supported())
|
||||
}
|
||||
|
||||
async fn readdir(
|
||||
&self,
|
||||
cursor: wasi_common::dir::ReaddirCursor,
|
||||
) -> Result<
|
||||
Box<dyn Iterator<Item = Result<wasi_common::dir::ReaddirEntity, Error>> + Send>,
|
||||
Error,
|
||||
> {
|
||||
self.inner.readdir(cursor).await
|
||||
}
|
||||
|
||||
async fn symlink(&self, _old_path: &str, _new_path: &str) -> Result<(), Error> {
|
||||
Err(Error::not_supported())
|
||||
}
|
||||
|
||||
async fn remove_dir(&self, _path: &str) -> Result<(), Error> {
|
||||
Err(Error::not_supported())
|
||||
}
|
||||
|
||||
async fn unlink_file(&self, _path: &str) -> Result<(), Error> {
|
||||
Err(Error::not_supported())
|
||||
}
|
||||
|
||||
async fn read_link(&self, path: &str) -> Result<std::path::PathBuf, Error> {
|
||||
self.inner.read_link(path).await
|
||||
}
|
||||
|
||||
async fn get_filestat(&self) -> Result<wasi_common::file::Filestat, Error> {
|
||||
self.inner.get_filestat().await
|
||||
}
|
||||
|
||||
async fn get_path_filestat(
|
||||
&self,
|
||||
path: &str,
|
||||
follow_symlinks: bool,
|
||||
) -> Result<wasi_common::file::Filestat, Error> {
|
||||
self.inner.get_path_filestat(path, follow_symlinks).await
|
||||
}
|
||||
|
||||
async fn rename(
|
||||
&self,
|
||||
_path: &str,
|
||||
_dest_dir: &dyn wasi_common::WasiDir,
|
||||
_dest_path: &str,
|
||||
) -> Result<(), Error> {
|
||||
Err(wasi_common::Error::not_supported())
|
||||
}
|
||||
|
||||
async fn hard_link(
|
||||
&self,
|
||||
_path: &str,
|
||||
_target_dir: &dyn wasi_common::WasiDir,
|
||||
_target_path: &str,
|
||||
) -> Result<(), Error> {
|
||||
Err(wasi_common::Error::not_supported())
|
||||
}
|
||||
|
||||
async fn set_times(
|
||||
&self,
|
||||
_path: &str,
|
||||
_atime: std::option::Option<wasi_common::SystemTimeSpec>,
|
||||
_mtime: std::option::Option<wasi_common::SystemTimeSpec>,
|
||||
_follow_symlinks: bool,
|
||||
) -> Result<(), Error> {
|
||||
Err(wasi_common::Error::not_supported())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
use std::os::raw::c_char;
|
||||
use std::{os::raw::c_char, ptr::null_mut};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -11,6 +11,12 @@ pub struct ExtismFunction(std::cell::Cell<Option<Function>>);
|
||||
/// The return code used to specify a successful plugin call
|
||||
pub static EXTISM_SUCCESS: i32 = 0;
|
||||
|
||||
fn make_error_msg(s: String) -> Vec<u8> {
|
||||
let mut s = s.into_bytes();
|
||||
s.push(0);
|
||||
s
|
||||
}
|
||||
|
||||
/// A union type for host function argument/return values
|
||||
#[repr(C)]
|
||||
pub union ValUnion {
|
||||
@@ -96,7 +102,7 @@ pub unsafe extern "C" fn extism_current_plugin_host_context(
|
||||
|
||||
let plugin = &mut *plugin;
|
||||
if let Ok(CVoidContainer(ptr)) = plugin.host_context::<CVoidContainer>() {
|
||||
ptr
|
||||
*ptr
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
@@ -231,12 +237,28 @@ pub unsafe extern "C" fn extism_function_new(
|
||||
})
|
||||
.collect();
|
||||
|
||||
// We cannot simply "get" the Vec's storage pointer because
|
||||
// the underlying storage might be invalid when the Vec is empty.
|
||||
// In that case, we return (null, 0).
|
||||
|
||||
let (inputs_ptr, inputs_len) = if inputs.is_empty() {
|
||||
(core::ptr::null(), 0 as Size)
|
||||
} else {
|
||||
(inputs.as_ptr(), inputs.len() as Size)
|
||||
};
|
||||
|
||||
let (output_ptr, output_len) = if output_tmp.is_empty() {
|
||||
(null_mut(), 0 as Size)
|
||||
} else {
|
||||
(output_tmp.as_mut_ptr(), output_tmp.len() as Size)
|
||||
};
|
||||
|
||||
func(
|
||||
plugin,
|
||||
inputs.as_ptr(),
|
||||
inputs.len() as Size,
|
||||
output_tmp.as_mut_ptr(),
|
||||
output_tmp.len() as Size,
|
||||
inputs_ptr,
|
||||
inputs_len,
|
||||
output_ptr,
|
||||
output_len,
|
||||
user_data.as_ptr(),
|
||||
);
|
||||
|
||||
@@ -334,6 +356,66 @@ pub unsafe extern "C" fn extism_plugin_new(
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new plugin and set the number of instructions a plugin is allowed to execute
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn extism_plugin_new_with_fuel_limit(
|
||||
wasm: *const u8,
|
||||
wasm_size: Size,
|
||||
functions: *mut *const ExtismFunction,
|
||||
n_functions: Size,
|
||||
with_wasi: bool,
|
||||
fuel_limit: u64,
|
||||
errmsg: *mut *mut std::ffi::c_char,
|
||||
) -> *mut Plugin {
|
||||
trace!(
|
||||
"Call to extism_plugin_new_with_fuel_limit with wasm pointer {:?}",
|
||||
wasm
|
||||
);
|
||||
let data = std::slice::from_raw_parts(wasm, wasm_size as usize);
|
||||
let mut funcs = vec![];
|
||||
|
||||
if !functions.is_null() {
|
||||
for i in 0..n_functions {
|
||||
unsafe {
|
||||
let f = *functions.add(i as usize);
|
||||
if f.is_null() {
|
||||
continue;
|
||||
}
|
||||
if let Some(f) = (*f).0.take() {
|
||||
funcs.push(f);
|
||||
} else {
|
||||
let e = std::ffi::CString::new(
|
||||
"Function cannot be registered with multiple different Plugins",
|
||||
)
|
||||
.unwrap();
|
||||
*errmsg = e.into_raw();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugin = Plugin::build_new(
|
||||
data.into(),
|
||||
funcs,
|
||||
with_wasi,
|
||||
Default::default(),
|
||||
None,
|
||||
Some(fuel_limit),
|
||||
);
|
||||
|
||||
match plugin {
|
||||
Err(e) => {
|
||||
if !errmsg.is_null() {
|
||||
let e = std::ffi::CString::new(format!("Unable to create Extism plugin: {}", e))
|
||||
.unwrap();
|
||||
*errmsg = e.into_raw();
|
||||
}
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
Ok(p) => Box::into_raw(Box::new(p)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Free the error returned by `extism_plugin_new`, errors returned from `extism_plugin_error` don't need to be freed
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn extism_plugin_new_error_free(err: *mut std::ffi::c_char) {
|
||||
@@ -394,8 +476,6 @@ pub unsafe extern "C" fn extism_plugin_config(
|
||||
return false;
|
||||
}
|
||||
let plugin = &mut *plugin;
|
||||
let _lock = plugin.instance.clone();
|
||||
let mut lock = _lock.lock().unwrap();
|
||||
|
||||
trace!(
|
||||
plugin = plugin.id.to_string(),
|
||||
@@ -406,8 +486,8 @@ pub unsafe extern "C" fn extism_plugin_config(
|
||||
let json: std::collections::BTreeMap<String, Option<String>> =
|
||||
match serde_json::from_slice(data) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
return plugin.return_error(&mut lock, e, false);
|
||||
Err(_) => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -440,9 +520,6 @@ pub unsafe extern "C" fn extism_plugin_function_exists(
|
||||
return false;
|
||||
}
|
||||
let plugin = &mut *plugin;
|
||||
let _lock = plugin.instance.clone();
|
||||
let mut lock = _lock.lock().unwrap();
|
||||
|
||||
let name = std::ffi::CStr::from_ptr(func_name);
|
||||
trace!(
|
||||
plugin = plugin.id.to_string(),
|
||||
@@ -452,8 +529,8 @@ pub unsafe extern "C" fn extism_plugin_function_exists(
|
||||
|
||||
let name = match name.to_str() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
return plugin.return_error(&mut lock, e, false);
|
||||
Err(_) => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -509,7 +586,10 @@ pub unsafe extern "C" fn extism_plugin_call_with_host_context(
|
||||
let name = std::ffi::CStr::from_ptr(func_name);
|
||||
let name = match name.to_str() {
|
||||
Ok(name) => name,
|
||||
Err(e) => return plugin.return_error(&mut lock, e, -1),
|
||||
Err(e) => {
|
||||
plugin.error_msg = Some(make_error_msg(e.to_string()));
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
trace!(
|
||||
@@ -518,13 +598,17 @@ pub unsafe extern "C" fn extism_plugin_call_with_host_context(
|
||||
name
|
||||
);
|
||||
let input = std::slice::from_raw_parts(data, data_len as usize);
|
||||
let r = match ExternRef::new(&mut plugin.store, CVoidContainer(host_context)) {
|
||||
Err(e) => return plugin.return_error(&mut lock, e, -1),
|
||||
Ok(x) => x,
|
||||
let r = if host_context.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(CVoidContainer(host_context))
|
||||
};
|
||||
let res = plugin.raw_call(&mut lock, name, input, Some(r));
|
||||
let res = plugin.raw_call(&mut lock, name, input, r);
|
||||
match res {
|
||||
Err((e, rc)) => plugin.return_error(&mut lock, e, rc),
|
||||
Err((e, rc)) => {
|
||||
plugin.error_msg = Some(make_error_msg(e.to_string()));
|
||||
rc
|
||||
}
|
||||
Ok(x) => x,
|
||||
}
|
||||
}
|
||||
@@ -547,14 +631,26 @@ pub unsafe extern "C" fn extism_plugin_error(plugin: *mut Plugin) -> *const c_ch
|
||||
let _lock = _lock.lock().unwrap();
|
||||
|
||||
if plugin.output.error_offset == 0 {
|
||||
if let Some(err) = &plugin.error_msg {
|
||||
return err.as_ptr() as *const _;
|
||||
}
|
||||
trace!(plugin = plugin.id.to_string(), "error is NULL");
|
||||
return std::ptr::null();
|
||||
}
|
||||
|
||||
plugin
|
||||
let offs = plugin.output.error_offset;
|
||||
|
||||
let ptr = plugin.current_plugin_mut().memory_ptr().add(offs as usize) as *const _;
|
||||
|
||||
let len = plugin
|
||||
.current_plugin_mut()
|
||||
.memory_ptr()
|
||||
.add(plugin.output.error_offset as usize) as *const _
|
||||
.memory_length(offs)
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut data = std::slice::from_raw_parts(ptr, len as usize).to_vec();
|
||||
data.push(0);
|
||||
plugin.error_msg = Some(data);
|
||||
plugin.error_msg.as_ref().unwrap().as_ptr() as *const _
|
||||
}
|
||||
|
||||
/// Get the length of a plugin's output data
|
||||
@@ -629,7 +725,6 @@ pub unsafe extern "C" fn extism_log_file(
|
||||
fn set_log_file(log_file: impl Into<std::path::PathBuf>, filter: &str) -> Result<(), Error> {
|
||||
let log_file = log_file.into();
|
||||
let s = log_file.to_str();
|
||||
|
||||
let is_level = tracing::Level::from_str(filter).is_ok();
|
||||
let cfg = tracing_subscriber::FmtSubscriber::builder().with_env_filter({
|
||||
let x = tracing_subscriber::EnvFilter::builder()
|
||||
@@ -680,6 +775,7 @@ pub unsafe extern "C" fn extism_log_custom(log_level: *const c_char) -> bool {
|
||||
} else {
|
||||
"error"
|
||||
};
|
||||
|
||||
set_log_buffer(level).is_ok()
|
||||
}
|
||||
|
||||
|
||||
1
runtime/src/tests/data/data.txt
Normal file
1
runtime/src/tests/data/data.txt
Normal file
@@ -0,0 +1 @@
|
||||
hello world!
|
||||
@@ -3,36 +3,32 @@ use quickcheck::*;
|
||||
|
||||
const KERNEL: &[u8] = include_bytes!("../extism-runtime.wasm");
|
||||
|
||||
fn extism_alloc<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, n: u64) -> u64 {
|
||||
fn extism_alloc<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, n: u64) -> u64 {
|
||||
let out_alloc = &mut [Val::I64(0)];
|
||||
instance
|
||||
.get_func(&mut store, "alloc")
|
||||
.get_func(&mut *store, "alloc")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(n as i64)], out_alloc)
|
||||
.call(store, &[Val::I64(n as i64)], out_alloc)
|
||||
.unwrap();
|
||||
out_alloc[0].unwrap_i64() as u64
|
||||
}
|
||||
|
||||
fn extism_length<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u64 {
|
||||
fn extism_length<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u64 {
|
||||
let out = &mut [Val::I64(0)];
|
||||
instance
|
||||
.get_func(&mut store, "length")
|
||||
.get_func(&mut *store, "length")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], out)
|
||||
.call(store, &[Val::I64(p as i64)], out)
|
||||
.unwrap();
|
||||
out[0].unwrap_i64() as u64
|
||||
}
|
||||
|
||||
fn extism_length_unsafe<T>(
|
||||
mut store: &mut wasmtime::Store<T>,
|
||||
instance: &mut Instance,
|
||||
p: u64,
|
||||
) -> u64 {
|
||||
fn extism_length_unsafe<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u64 {
|
||||
let out = &mut [Val::I64(0)];
|
||||
instance
|
||||
.get_func(&mut store, "length_unsafe")
|
||||
.get_func(&mut *store, "length_unsafe")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], out)
|
||||
.call(store, &[Val::I64(p as i64)], out)
|
||||
.unwrap();
|
||||
out[0].unwrap_i64() as u64
|
||||
}
|
||||
@@ -47,122 +43,96 @@ fn extism_load_u8<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance
|
||||
out[0].unwrap_i32() as u8
|
||||
}
|
||||
|
||||
fn extism_load_u64<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u64 {
|
||||
fn extism_load_u64<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u64 {
|
||||
let out = &mut [Val::I32(0)];
|
||||
instance
|
||||
.get_func(&mut store, "load_u64")
|
||||
.get_func(&mut *store, "load_u64")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], out)
|
||||
.call(store, &[Val::I64(p as i64)], out)
|
||||
.unwrap();
|
||||
out[0].unwrap_i64() as u64
|
||||
}
|
||||
|
||||
fn extism_input_load_u8<T>(
|
||||
mut store: &mut wasmtime::Store<T>,
|
||||
instance: &mut Instance,
|
||||
p: u64,
|
||||
) -> u8 {
|
||||
fn extism_input_load_u8<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) -> u8 {
|
||||
let out = &mut [Val::I32(0)];
|
||||
instance
|
||||
.get_func(&mut store, "input_load_u8")
|
||||
.get_func(&mut *store, "input_load_u8")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], out)
|
||||
.call(store, &[Val::I64(p as i64)], out)
|
||||
.unwrap();
|
||||
out[0].unwrap_i32() as u8
|
||||
}
|
||||
|
||||
fn extism_input_load_u64<T>(
|
||||
mut store: &mut wasmtime::Store<T>,
|
||||
store: &mut wasmtime::Store<T>,
|
||||
instance: &mut Instance,
|
||||
p: u64,
|
||||
) -> u64 {
|
||||
let out = &mut [Val::I32(0)];
|
||||
instance
|
||||
.get_func(&mut store, "input_load_u64")
|
||||
.get_func(&mut *store, "input_load_u64")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], out)
|
||||
.call(store, &[Val::I64(p as i64)], out)
|
||||
.unwrap();
|
||||
out[0].unwrap_i64() as u64
|
||||
}
|
||||
|
||||
fn extism_store_u8<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64, x: u8) {
|
||||
fn extism_store_u8<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64, x: u8) {
|
||||
instance
|
||||
.get_func(&mut store, "store_u8")
|
||||
.get_func(&mut *store, "store_u8")
|
||||
.unwrap()
|
||||
.call(
|
||||
&mut store,
|
||||
&[Val::I64(p as i64), Val::I32(x as i32)],
|
||||
&mut [],
|
||||
)
|
||||
.call(store, &[Val::I64(p as i64), Val::I32(x as i32)], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn extism_store_u64<T>(
|
||||
mut store: &mut wasmtime::Store<T>,
|
||||
instance: &mut Instance,
|
||||
p: u64,
|
||||
x: u64,
|
||||
) {
|
||||
fn extism_store_u64<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64, x: u64) {
|
||||
instance
|
||||
.get_func(&mut store, "store_u64")
|
||||
.get_func(&mut *store, "store_u64")
|
||||
.unwrap()
|
||||
.call(
|
||||
&mut store,
|
||||
&[Val::I64(p as i64), Val::I64(x as i64)],
|
||||
&mut [],
|
||||
)
|
||||
.call(store, &[Val::I64(p as i64), Val::I64(x as i64)], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn extism_free<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) {
|
||||
fn extism_free<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) {
|
||||
instance
|
||||
.get_func(&mut store, "free")
|
||||
.get_func(&mut *store, "free")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], &mut [])
|
||||
.call(store, &[Val::I64(p as i64)], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn extism_error_set<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) {
|
||||
fn extism_error_set<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64) {
|
||||
instance
|
||||
.get_func(&mut store, "error_set")
|
||||
.get_func(&mut *store, "error_set")
|
||||
.unwrap()
|
||||
.call(&mut store, &[Val::I64(p as i64)], &mut [])
|
||||
.call(store, &[Val::I64(p as i64)], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn extism_error_get<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance) -> u64 {
|
||||
fn extism_error_get<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance) -> u64 {
|
||||
let out = &mut [Val::I64(0)];
|
||||
instance
|
||||
.get_func(&mut store, "error_get")
|
||||
.get_func(&mut *store, "error_get")
|
||||
.unwrap()
|
||||
.call(&mut store, &[], out)
|
||||
.call(store, &[], out)
|
||||
.unwrap();
|
||||
|
||||
out[0].unwrap_i64() as u64
|
||||
}
|
||||
|
||||
fn extism_reset<T>(mut store: &mut wasmtime::Store<T>, instance: &mut Instance) {
|
||||
fn extism_reset<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance) {
|
||||
instance
|
||||
.get_func(&mut store, "reset")
|
||||
.get_func(&mut *store, "reset")
|
||||
.unwrap()
|
||||
.call(&mut store, &[], &mut [])
|
||||
.call(store, &[], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn extism_input_set<T>(
|
||||
mut store: &mut wasmtime::Store<T>,
|
||||
instance: &mut Instance,
|
||||
p: u64,
|
||||
l: u64,
|
||||
) {
|
||||
fn extism_input_set<T>(store: &mut wasmtime::Store<T>, instance: &mut Instance, p: u64, l: u64) {
|
||||
instance
|
||||
.get_func(&mut store, "input_set")
|
||||
.get_func(&mut *store, "input_set")
|
||||
.unwrap()
|
||||
.call(
|
||||
&mut store,
|
||||
&[Val::I64(p as i64), Val::I64(l as i64)],
|
||||
&mut [],
|
||||
)
|
||||
.call(store, &[Val::I64(p as i64), Val::I64(l as i64)], &mut [])
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ const WASM_LOOP: &[u8] = include_bytes!("../../../wasm/loop.wasm");
|
||||
const WASM_GLOBALS: &[u8] = include_bytes!("../../../wasm/globals.wasm");
|
||||
const WASM_REFLECT: &[u8] = include_bytes!("../../../wasm/reflect.wasm");
|
||||
const WASM_HTTP: &[u8] = include_bytes!("../../../wasm/http.wasm");
|
||||
const WASM_FS: &[u8] = include_bytes!("../../../wasm/read_write.wasm");
|
||||
|
||||
host_fn!(pub hello_world (a: String) -> String { Ok(a) });
|
||||
|
||||
@@ -241,6 +242,23 @@ fn test_timeout() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fuel() {
|
||||
let manifest = Manifest::new([extism_manifest::Wasm::data(WASM_LOOP)]);
|
||||
let mut plugin = PluginBuilder::new(manifest)
|
||||
.with_wasi(true)
|
||||
.with_fuel_limit(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
for _ in 0..10001 {
|
||||
let output: Result<&[u8], Error> = plugin.call("loop_forever", "abc123");
|
||||
let err = output.unwrap_err().root_cause().to_string();
|
||||
println!("Fuel limited plugin exited with error: {:?}", &err);
|
||||
assert!(err.contains("fuel"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "http")]
|
||||
fn test_http_timeout() {
|
||||
let f = Function::new(
|
||||
"hello_world",
|
||||
@@ -316,8 +334,10 @@ fn test_multiple_instantiations() {
|
||||
#[test]
|
||||
fn test_globals() {
|
||||
let mut plugin = Plugin::new(WASM_GLOBALS, [], true).unwrap();
|
||||
for i in 0..100000 {
|
||||
let Json(count) = plugin.call::<_, Json<Count>>("globals", "").unwrap();
|
||||
for i in 0..100001 {
|
||||
let Json(count) = plugin
|
||||
.call_with_host_context::<_, Json<Count>, _>("globals", "", ())
|
||||
.unwrap();
|
||||
assert_eq!(count.count, i);
|
||||
}
|
||||
}
|
||||
@@ -348,7 +368,7 @@ fn test_call_with_host_context() {
|
||||
[PTR],
|
||||
UserData::default(),
|
||||
|current_plugin, _val, ret, _user_data: UserData<()>| {
|
||||
let foo = current_plugin.host_context::<Foo>()?;
|
||||
let foo = current_plugin.host_context::<Foo>()?.clone();
|
||||
let hnd = current_plugin.memory_new(foo.message)?;
|
||||
ret[0] = current_plugin.memory_to_val(hnd);
|
||||
Ok(())
|
||||
@@ -750,3 +770,26 @@ fn test_linking() {
|
||||
assert_eq!(plugin.call::<&str, i64>("run", "Hello, world!").unwrap(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_readonly_dirs() {
|
||||
let wasm = Wasm::data(WASM_FS);
|
||||
let manifest = Manifest::new([wasm])
|
||||
.with_allowed_path("ro:src/tests/data".to_string(), "/data")
|
||||
.with_config_key("path", "/data/data.txt");
|
||||
|
||||
let mut plugin = PluginBuilder::new(manifest)
|
||||
.with_wasi(true)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let res = plugin.call::<&str, &str>("try_read", "").unwrap();
|
||||
assert_eq!(res, "hello world!");
|
||||
|
||||
let line = "hello world 2";
|
||||
let res2 = plugin.call::<&str, &str>("try_write", line);
|
||||
assert!(
|
||||
res2.is_err(),
|
||||
"Expected try_write to fail, but it succeeded."
|
||||
);
|
||||
}
|
||||
|
||||
BIN
wasm/read_write.wasm
Normal file
BIN
wasm/read_write.wasm
Normal file
Binary file not shown.
Reference in New Issue
Block a user