mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 22:39:07 +00:00
Merge main into feat/plugin-importers
This commit is contained in:
@@ -0,0 +1,507 @@
|
||||
//! What a plug-in may import from the host ([`IMPORTS`]), from plug-in API level 2 on:
|
||||
//! `vc_progress` reports how far a run has got, `vc_cancelled` tells it the user or a host limit
|
||||
//! asked it to stop, and `vc_log` writes a log line. A module may import them only when its
|
||||
//! manifest gives `api` 2 and lists the `progress` permission, and the host checks each import when
|
||||
//! the module is loaded ([`check_imports`], [`check_granted`]): one it doesn't offer, one with
|
||||
//! another signature and one the manifest doesn't allow are refused by name.
|
||||
//!
|
||||
//! Each call's arguments are checked: progress is clamped and passed on only when it changes (with
|
||||
//! a known total, to another tenth of a percent; past [`MAX_PROGRESS_REPORTS`], once per
|
||||
//! [`PROGRESS_STRIDE`] changes), log text must lie inside the module's memory and be UTF-8, and
|
||||
//! each line ([`MAX_LOG_LINE`]) and each run ([`MAX_LOG_LINES`], [`MAX_LOG_BYTES`],
|
||||
//! [`MAX_LOG_READ`]) are capped. Nothing a module passes can panic the host.
|
||||
|
||||
use wasmi::{Caller, Engine, Extern, ExternType, Linker, Module, StoreLimits, ValType};
|
||||
|
||||
use crate::manifest::Manifest;
|
||||
use crate::permissions::{self, PROGRESS_API, Permission};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The module a plug-in imports host functions from (the name a Rust or C toolchain gives
|
||||
/// `extern` functions by default).
|
||||
pub const MODULE: &str = "env";
|
||||
|
||||
/// What the host passes as the step's description with a plug-in's progress
|
||||
/// ([`vectorcraft_doc::cancel::progress`]), so a progress window shows a share rather than a count
|
||||
/// of artboards or files.
|
||||
pub const PROGRESS_STEP: &str = "plug-in";
|
||||
|
||||
/// Longest log line: its first 1,024 bytes of text, shown as at most 1,024 characters with hidden
|
||||
/// characters escaped. A longer one is cut and ends with `…`.
|
||||
pub const MAX_LOG_LINE: usize = 1024;
|
||||
|
||||
/// Most log lines one run writes; later ones are dropped, after one "log truncated" line.
|
||||
pub const MAX_LOG_LINES: usize = 200;
|
||||
|
||||
/// Most bytes of log text, as written with its escapes, one run writes; lines past it are dropped
|
||||
/// as past [`MAX_LOG_LINES`].
|
||||
pub const MAX_LOG_BYTES: usize = 32 * 1024;
|
||||
|
||||
/// Most bytes of text the host reads from a run's `vc_log` calls, checked or not: a call that
|
||||
/// would read past it is dropped as past [`MAX_LOG_LINES`].
|
||||
pub const MAX_LOG_READ: usize = 1024 * 1024;
|
||||
|
||||
/// Most progress reports one run passes on at the full rate; after them, one changed report in
|
||||
/// [`PROGRESS_STRIDE`] is, and so is the first after a total becomes known or unknown. The run's
|
||||
/// last report is always kept ([`Report::progress`]).
|
||||
pub const MAX_PROGRESS_REPORTS: usize = 2000;
|
||||
|
||||
/// Past [`MAX_PROGRESS_REPORTS`], how many changed reports go by for each one passed on.
|
||||
pub const PROGRESS_STRIDE: usize = 1000;
|
||||
|
||||
/// What `vc_log` returns: the line was written.
|
||||
pub const LOG_WRITTEN: i32 = 0;
|
||||
/// What `vc_log` returns: the run's log budget is spent, so the line was dropped.
|
||||
pub const LOG_DROPPED: i32 = 1;
|
||||
/// What `vc_log` returns: the text doesn't lie inside the module's memory.
|
||||
pub const LOG_OUTSIDE_MEMORY: i32 = -1;
|
||||
/// What `vc_log` returns: the text is not UTF-8.
|
||||
pub const LOG_NOT_UTF8: i32 = -2;
|
||||
/// What `vc_log` returns: the level is not 0 to 3.
|
||||
pub const LOG_BAD_LEVEL: i32 = -3;
|
||||
|
||||
/// One host import: its name and its type.
|
||||
pub struct Import {
|
||||
pub name: &'static str,
|
||||
params: &'static [ValType],
|
||||
results: &'static [ValType],
|
||||
/// Its type as WebAssembly text writes it.
|
||||
pub signature: &'static str,
|
||||
}
|
||||
|
||||
/// The host imports of API level 2, in module [`MODULE`]:
|
||||
///
|
||||
/// - `vc_progress(done: i64, total: i64)`: `done` of `total` steps are finished (`total` 0 or less:
|
||||
/// not known). Negative values count as 0 and `done` is clamped to `total`;
|
||||
/// - `vc_cancelled() -> i32`: 1 once the user cancelled the run or its time budget ran out, else 0;
|
||||
/// - `vc_log(level: i32, ptr: i32, len: i32) -> i32`: writes the UTF-8 text at `ptr` as a log line
|
||||
/// of `level` (0 error, 1 warning, 2 information, 3 debug) → [`LOG_WRITTEN`], [`LOG_DROPPED`],
|
||||
/// [`LOG_OUTSIDE_MEMORY`], [`LOG_NOT_UTF8`] or [`LOG_BAD_LEVEL`].
|
||||
pub const IMPORTS: [Import; 3] = [
|
||||
Import { name: "vc_progress", params: &[ValType::I64, ValType::I64], results: &[], signature: "(param i64 i64)" },
|
||||
Import { name: "vc_cancelled", params: &[], results: &[ValType::I32], signature: "(result i32)" },
|
||||
Import {
|
||||
name: "vc_log",
|
||||
params: &[ValType::I32, ValType::I32, ValType::I32],
|
||||
results: &[ValType::I32],
|
||||
signature: "(param i32 i32 i32) (result i32)",
|
||||
},
|
||||
];
|
||||
|
||||
/// A log line's level.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LogLevel {
|
||||
Error,
|
||||
Warn,
|
||||
Info,
|
||||
Debug,
|
||||
}
|
||||
|
||||
impl LogLevel {
|
||||
/// The level `vc_log`'s `level` names.
|
||||
fn from_code(code: i32) -> Option<LogLevel> {
|
||||
match code {
|
||||
0 => Some(LogLevel::Error),
|
||||
1 => Some(LogLevel::Warn),
|
||||
2 => Some(LogLevel::Info),
|
||||
3 => Some(LogLevel::Debug),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn log_level(self) -> log::Level {
|
||||
match self {
|
||||
LogLevel::Error => log::Level::Error,
|
||||
LogLevel::Warn => log::Level::Warn,
|
||||
LogLevel::Info => log::Level::Info,
|
||||
LogLevel::Debug => log::Level::Debug,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line a plug-in wrote with `vc_log`: its control and bidirectional formatting characters
|
||||
/// escaped ([`permissions::display_text`]), and cut to [`MAX_LOG_LINE`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LogLine {
|
||||
pub level: LogLevel,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The text of the line that stands for the lines a run's log budget dropped.
|
||||
pub const LOG_TRUNCATED: &str = "log truncated: later lines were dropped";
|
||||
|
||||
/// What a run reported through the host imports.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Report {
|
||||
/// Its last progress report, clamped: `(done, total)`, `total` 0 when not known.
|
||||
pub progress: Option<(u64, u64)>,
|
||||
/// The lines it wrote, then [`LOG_TRUNCATED`] once its budget dropped one.
|
||||
pub lines: Vec<LogLine>,
|
||||
/// Did its log budget drop a line?
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// When a run must stop (native: a wall-clock deadline).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Deadline {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant,
|
||||
}
|
||||
|
||||
impl Deadline {
|
||||
pub(crate) fn new(wall_time_ms: u64) -> Self {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = wall_time_ms;
|
||||
Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant::now() + std::time::Duration::from_millis(wall_time_ms),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn passed(&self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::time::Instant::now() >= self.at {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn check(&self) -> Result<()> {
|
||||
if self.passed() { Err(Error::Limit("time budget".into())) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One run's state that the host imports read and write.
|
||||
pub(crate) struct Run {
|
||||
/// The plug-in's id, which its log lines carry.
|
||||
id: String,
|
||||
/// Are its progress reports passed on ([`vectorcraft_doc::cancel::progress`])? A live
|
||||
/// effect's are not: it is drawn as part of something else, such as an export.
|
||||
forward: bool,
|
||||
/// Are its log lines written to the app's log? Not while the module is being loaded.
|
||||
logged: bool,
|
||||
deadline: Deadline,
|
||||
/// The last report passed on, as per mille of a known total (with 1) or the count of an
|
||||
/// unknown one (with 0), how many were, and how many changed ones went by since the last.
|
||||
last: Option<(u64, u64)>,
|
||||
reports: usize,
|
||||
skipped: usize,
|
||||
/// Bytes of log text written (with their escapes) and read.
|
||||
log_bytes: usize,
|
||||
log_read: usize,
|
||||
pub(crate) report: Report,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
pub(crate) fn new(id: &str, forward: bool, logged: bool, deadline: Deadline) -> Self {
|
||||
Run {
|
||||
id: id.to_string(),
|
||||
forward,
|
||||
logged,
|
||||
deadline,
|
||||
last: None,
|
||||
reports: 0,
|
||||
skipped: 0,
|
||||
log_bytes: 0,
|
||||
log_read: 0,
|
||||
report: Report::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn progress(&mut self, done: i64, total: i64) {
|
||||
let total = u64::try_from(total).unwrap_or(0);
|
||||
let done = u64::try_from(done).unwrap_or(0);
|
||||
let done = if total > 0 { done.min(total) } else { done };
|
||||
self.report.progress = Some((done, total));
|
||||
let key = if total > 0 { ((u128::from(done) * 1000 / u128::from(total)) as u64, 1) } else { (done, 0) };
|
||||
if !self.forward || self.last == Some(key) {
|
||||
return;
|
||||
}
|
||||
let switched = self.last.is_some_and(|(_, t)| (t > 0) != (total > 0));
|
||||
if self.reports >= MAX_PROGRESS_REPORTS && !switched {
|
||||
self.skipped += 1;
|
||||
if self.skipped < PROGRESS_STRIDE {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.skipped = 0;
|
||||
self.last = Some(key);
|
||||
self.reports += 1;
|
||||
vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP);
|
||||
}
|
||||
|
||||
fn cancelled(&self) -> i32 {
|
||||
i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed())
|
||||
}
|
||||
|
||||
/// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns.
|
||||
fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 {
|
||||
let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL };
|
||||
let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY };
|
||||
if self.report.truncated {
|
||||
return LOG_DROPPED;
|
||||
}
|
||||
if self.log_read.saturating_add(len) > MAX_LOG_READ {
|
||||
return self.truncate();
|
||||
}
|
||||
self.log_read += len;
|
||||
let Ok(text) = std::str::from_utf8(bytes) else { return LOG_NOT_UTF8 };
|
||||
// A character the cut splits is left out.
|
||||
let head = text.get(..text.floor_char_boundary(MAX_LOG_LINE)).unwrap_or(text);
|
||||
let shown = if head.len() < text.len() {
|
||||
let mut shown = permissions::display_text(head, MAX_LOG_LINE - 1);
|
||||
if !shown.ends_with('…') {
|
||||
shown.push('…');
|
||||
}
|
||||
shown
|
||||
} else {
|
||||
permissions::display_text(head, MAX_LOG_LINE)
|
||||
};
|
||||
if self.report.lines.len() >= MAX_LOG_LINES || self.log_bytes + shown.len() > MAX_LOG_BYTES {
|
||||
return self.truncate();
|
||||
}
|
||||
self.log_bytes += shown.len();
|
||||
self.write(level, shown);
|
||||
LOG_WRITTEN
|
||||
}
|
||||
|
||||
/// Drops the line and the run's later ones, after one line that says so → [`LOG_DROPPED`].
|
||||
fn truncate(&mut self) -> i32 {
|
||||
self.report.truncated = true;
|
||||
self.write(LogLevel::Warn, LOG_TRUNCATED.to_string());
|
||||
LOG_DROPPED
|
||||
}
|
||||
|
||||
fn write(&mut self, level: LogLevel, text: String) {
|
||||
if self.logged {
|
||||
log::log!(target: "vectorcraft_plugins", level.log_level(), "{}: {text}", self.id);
|
||||
}
|
||||
self.report.lines.push(LogLine { level, text });
|
||||
}
|
||||
}
|
||||
|
||||
/// What a store holds: its memory limits and the run's state.
|
||||
pub(crate) struct Host {
|
||||
pub(crate) limits: StoreLimits,
|
||||
pub(crate) run: Run,
|
||||
}
|
||||
|
||||
/// A linker that offers the host imports when `granted`, and no import otherwise.
|
||||
pub(crate) fn linker(engine: &Engine, granted: bool) -> Linker<Host> {
|
||||
let mut linker = Linker::<Host>::new(engine);
|
||||
if granted {
|
||||
// Each name is defined once, so none of these fails.
|
||||
let _ = linker.func_wrap(MODULE, "vc_progress", |mut caller: Caller<'_, Host>, done: i64, total: i64| {
|
||||
caller.data_mut().run.progress(done, total);
|
||||
});
|
||||
let _ = linker.func_wrap(MODULE, "vc_cancelled", |caller: Caller<'_, Host>| -> i32 { caller.data().run.cancelled() });
|
||||
let _ = linker.func_wrap(MODULE, "vc_log", |mut caller: Caller<'_, Host>, level: i32, ptr: i32, len: i32| -> i32 {
|
||||
let Some(Extern::Memory(memory)) = caller.get_export("memory") else { return LOG_OUTSIDE_MEMORY };
|
||||
let (data, host) = memory.data_and_store_mut(&mut caller);
|
||||
host.run.log(level, data, ptr as u32 as usize, len as u32 as usize)
|
||||
});
|
||||
}
|
||||
linker
|
||||
}
|
||||
|
||||
/// Checks that every import of `module` is a host import with the host's signature → their names.
|
||||
/// Any other import is refused, and the error names it.
|
||||
pub(crate) fn check_imports(module: &Module) -> Result<Vec<&'static str>> {
|
||||
let mut names = Vec::new();
|
||||
for imp in module.imports() {
|
||||
let offered = if imp.module() == MODULE { IMPORTS.iter().find(|i| i.name == imp.name()) } else { None };
|
||||
let (from, name) = (permissions::display_text(imp.module(), 64), permissions::display_text(imp.name(), 64));
|
||||
let Some(host) = offered else {
|
||||
return Err(Error::Abi(format!(
|
||||
"the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only `env.vc_progress`, `env.vc_cancelled` and `env.vc_log` (plug-in API level 2), and no WASI, files or network"
|
||||
)));
|
||||
};
|
||||
match imp.ty() {
|
||||
ExternType::Func(f) if f.params() == host.params && f.results() == host.results => names.push(host.name),
|
||||
_ => {
|
||||
let signature = host.signature;
|
||||
return Err(Error::Abi(format!("the module imports `env.{name}` with another type than the host's: it is {signature}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Checks that `manifest` allows the host imports `imports`: `api` 2 and the `progress`
|
||||
/// permission. The error names the first import it doesn't allow.
|
||||
pub(crate) fn check_granted(manifest: &Manifest, imports: &[&str]) -> Result<()> {
|
||||
match imports.first() {
|
||||
Some(name) if manifest.api < PROGRESS_API || !manifest.permissions().contains(&Permission::Progress) => Err(Error::Abi(format!(
|
||||
"the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `progress`"
|
||||
))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run() -> Run {
|
||||
Run::new("test", true, false, Deadline::new(60_000))
|
||||
}
|
||||
|
||||
/// Progress is clamped: negative counts are 0 and `done` never passes a known total.
|
||||
#[test]
|
||||
fn progress_is_clamped() {
|
||||
let mut r = run();
|
||||
for ((done, total), want) in
|
||||
[((5, 3), (3, 3)), ((-4, 10), (0, 10)), ((7, -1), (7, 0)), ((i64::MAX, i64::MAX), (i64::MAX as u64, i64::MAX as u64))]
|
||||
{
|
||||
r.progress(done, total);
|
||||
assert_eq!(r.report.progress, Some(want), "{done} of {total}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports are passed on only when they change (with a known total, to another tenth of a
|
||||
/// percent, however the total changes; with an unknown total, each change of `done`), and past
|
||||
/// [`MAX_PROGRESS_REPORTS`] once per [`PROGRESS_STRIDE`] changes, except the first after the
|
||||
/// total becomes known; the last one is always kept.
|
||||
#[test]
|
||||
fn progress_is_passed_on_at_a_bounded_rate() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = {
|
||||
let seen = seen.clone();
|
||||
Rc::new(move |d, t, w| seen.borrow_mut().push((d, t, w.to_string())))
|
||||
};
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
let mut r = run();
|
||||
vectorcraft_doc::cancel::scope(&token, Some(sink), || {
|
||||
for done in 0..=1_000_000 {
|
||||
r.progress(done, 1_000_000);
|
||||
}
|
||||
});
|
||||
let seen = seen.borrow();
|
||||
assert_eq!(seen.len(), 1001, "one per tenth of a percent");
|
||||
assert_eq!(seen.last(), Some(&(1_000_000, 1_000_000, PROGRESS_STEP.to_string())));
|
||||
let mut unknown = run();
|
||||
let later = Rc::new(RefCell::new(Vec::new()));
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = {
|
||||
let later = later.clone();
|
||||
Rc::new(move |d, t, _| later.borrow_mut().push((d, t)))
|
||||
};
|
||||
vectorcraft_doc::cancel::scope(&token, Some(sink), || {
|
||||
for done in 0..10_000 {
|
||||
unknown.progress(done, 0);
|
||||
}
|
||||
assert_eq!(unknown.reports, MAX_PROGRESS_REPORTS + (10_000 - MAX_PROGRESS_REPORTS) / PROGRESS_STRIDE);
|
||||
assert_eq!(unknown.report.progress, Some((9_999, 0)), "the last report is kept");
|
||||
// A total that becomes known is passed on at once, and the reports after it keep
|
||||
// coming at the slower rate.
|
||||
unknown.progress(10, 100);
|
||||
assert_eq!(later.borrow().last(), Some(&(10, 100)));
|
||||
for done in 11..=100 {
|
||||
unknown.progress(done, 100);
|
||||
}
|
||||
});
|
||||
assert_eq!(later.borrow().last(), Some(&(10, 100)), "90 changes are fewer than the stride");
|
||||
assert_eq!(unknown.report.progress, Some((100, 100)));
|
||||
// A new total at the same tenth of a percent is not a new step.
|
||||
let mut retotalled = run();
|
||||
let steps = Rc::new(RefCell::new(Vec::new()));
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = {
|
||||
let steps = steps.clone();
|
||||
Rc::new(move |d, t, _| steps.borrow_mut().push((d, t)))
|
||||
};
|
||||
vectorcraft_doc::cancel::scope(&token, Some(sink), || {
|
||||
for total in 10..2_010 {
|
||||
retotalled.progress(total / 10, total - total % 10);
|
||||
}
|
||||
});
|
||||
assert_eq!(*steps.borrow(), [(1, 10)]);
|
||||
assert_eq!(retotalled.report.progress, Some((200, 2_000)));
|
||||
}
|
||||
|
||||
/// Text outside memory, text that isn't UTF-8 and an unknown level are errors; a long line is
|
||||
/// cut, also inside a character, and hidden characters are escaped.
|
||||
#[test]
|
||||
fn log_text_is_checked_and_cut() {
|
||||
let mut r = run();
|
||||
let memory = b"hello\xff\xfe\nworld";
|
||||
assert_eq!(r.log(2, memory, 0, 5), LOG_WRITTEN);
|
||||
assert_eq!(r.log(2, memory, 0, memory.len() + 1), LOG_OUTSIDE_MEMORY);
|
||||
assert_eq!(r.log(2, memory, usize::MAX, 2), LOG_OUTSIDE_MEMORY);
|
||||
assert_eq!(r.log(2, memory, 4, 3), LOG_NOT_UTF8);
|
||||
assert_eq!(r.log(4, memory, 0, 5), LOG_BAD_LEVEL);
|
||||
assert_eq!(r.log(-1, memory, 0, 5), LOG_BAD_LEVEL);
|
||||
assert_eq!(r.log(0, memory, 7, 6), LOG_WRITTEN);
|
||||
// The cut falls inside the 512th "é", which is left out.
|
||||
let long = format!("a{}", "é".repeat(MAX_LOG_LINE));
|
||||
assert_eq!(r.log(1, long.as_bytes(), 0, long.len()), LOG_WRITTEN);
|
||||
let lines = &r.report.lines;
|
||||
assert_eq!(lines[0], LogLine { level: LogLevel::Info, text: "hello".into() });
|
||||
assert_eq!(lines[1], LogLine { level: LogLevel::Error, text: "\\u{000A}world".into() });
|
||||
assert_eq!(lines[2], LogLine { level: LogLevel::Warn, text: format!("a{}…", "é".repeat(MAX_LOG_LINE / 2 - 1)) });
|
||||
assert!(!r.report.truncated);
|
||||
// Text past the cut is checked too.
|
||||
let bad_tail = [vec![b'a'; MAX_LOG_LINE * 2], vec![0xff]].concat();
|
||||
assert_eq!(r.log(2, &bad_tail, 0, bad_tail.len()), LOG_NOT_UTF8);
|
||||
// A cut line of escapes is at most MAX_LOG_LINE characters, its ellipsis included.
|
||||
let controls = vec![1u8; MAX_LOG_LINE * 2];
|
||||
assert_eq!(r.log(2, &controls, 0, controls.len()), LOG_WRITTEN);
|
||||
let text = &r.report.lines[3].text;
|
||||
assert!(text.starts_with("\\u{0001}") && text.ends_with('…') && text.chars().count() <= MAX_LOG_LINE, "{text}");
|
||||
}
|
||||
|
||||
/// The byte budget counts a line as written, with its escapes, so short lines of hidden
|
||||
/// characters can't write more than [`MAX_LOG_BYTES`].
|
||||
#[test]
|
||||
fn log_budget_counts_escaped_text() {
|
||||
let mut r = run();
|
||||
let controls = [1u8; 100];
|
||||
let shown = "\\u{0001}".len() * controls.len();
|
||||
let fit = MAX_LOG_BYTES / shown;
|
||||
for i in 0..fit {
|
||||
assert_eq!(r.log(2, &controls, 0, controls.len()), LOG_WRITTEN, "line {i}");
|
||||
}
|
||||
assert_eq!(r.log(2, &controls, 0, controls.len()), LOG_DROPPED);
|
||||
let written: usize = r.report.lines.iter().filter(|l| l.text != LOG_TRUNCATED).map(|l| l.text.len()).sum();
|
||||
assert!(written <= MAX_LOG_BYTES, "{written}");
|
||||
}
|
||||
|
||||
/// The host reads at most [`MAX_LOG_READ`] bytes of log text in a run, so long texts can't
|
||||
/// make it check more; once past it, later calls are dropped without reading.
|
||||
#[test]
|
||||
fn log_text_read_is_bounded() {
|
||||
let mut r = run();
|
||||
let big = vec![b'a'; MAX_LOG_READ / 4];
|
||||
for _ in 0..4 {
|
||||
assert_eq!(r.log(2, &big, 0, big.len()), LOG_WRITTEN);
|
||||
}
|
||||
assert_eq!(r.log(2, b"x", 0, 1), LOG_DROPPED);
|
||||
assert!(r.report.truncated);
|
||||
let mut huge = run();
|
||||
let over = vec![0xffu8; MAX_LOG_READ + 1];
|
||||
assert_eq!(huge.log(2, &over, 0, over.len()), LOG_DROPPED, "dropped before it is checked");
|
||||
assert_eq!(huge.log(2, b"x", 0, 1), LOG_DROPPED);
|
||||
}
|
||||
|
||||
/// Lines past the run's budget are dropped, with one line that says so.
|
||||
#[test]
|
||||
fn log_lines_past_the_budget_are_dropped_with_one_truncation_line() {
|
||||
let mut r = run();
|
||||
for i in 0..MAX_LOG_LINES + 50 {
|
||||
let want = if i < MAX_LOG_LINES { LOG_WRITTEN } else { LOG_DROPPED };
|
||||
assert_eq!(r.log(2, b"line", 0, 4), want, "line {i}");
|
||||
}
|
||||
assert_eq!(r.report.lines.len(), MAX_LOG_LINES + 1);
|
||||
assert_eq!(r.report.lines.last(), Some(&LogLine { level: LogLevel::Warn, text: LOG_TRUNCATED.into() }));
|
||||
assert!(r.report.truncated);
|
||||
// So is text past the run's bytes.
|
||||
let mut bytes = run();
|
||||
let big = vec![b'x'; MAX_LOG_LINE];
|
||||
let fit = MAX_LOG_BYTES / MAX_LOG_LINE;
|
||||
for _ in 0..fit {
|
||||
assert_eq!(bytes.log(2, &big, 0, big.len()), LOG_WRITTEN);
|
||||
}
|
||||
assert_eq!(bytes.log(2, b"x", 0, 1), LOG_DROPPED);
|
||||
assert_eq!(bytes.report.lines.len(), fit + 1);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
//! A plug-in is a WebAssembly module that implements the VectorCraft plug-in ABI (v1, documented
|
||||
//! in `docs/plugins.md`). It runs in [`wasmi`], a pure-Rust interpreter, with:
|
||||
//!
|
||||
//! - **no host imports**: no WASI, file system, network, clock or randomness. A module that
|
||||
//! imports anything is rejected;
|
||||
//! - **no host imports but the three of API level 2** ([`host`]: progress, Cancel and log lines,
|
||||
//! with the `progress` permission): no WASI, file system, network, clock or randomness. A module
|
||||
//! that imports anything else is rejected;
|
||||
//! - an **instruction budget** (fuel) per call, metered in slices so a wall-clock deadline is
|
||||
//! also enforced (native builds), so infinite loops end with an error. A filter may ask for a
|
||||
//! larger one ([`Budget::Heavy`]), which the host lets the user allow before installing it;
|
||||
@@ -29,6 +30,7 @@
|
||||
pub mod dialog;
|
||||
pub mod effect;
|
||||
pub mod export;
|
||||
pub mod host;
|
||||
pub mod import;
|
||||
pub mod manifest;
|
||||
pub mod objects;
|
||||
@@ -38,6 +40,7 @@ mod runtime;
|
||||
pub mod wat;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Kind, Manifest, Param, ParamSpec};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, Permission};
|
||||
use crate::permissions::{self, API_LEVEL, PROGRESS_API, Permission};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -311,8 +311,11 @@ impl Manifest {
|
||||
if !(1..=API_LEVEL).contains(&self.api) {
|
||||
return Err(Error::Manifest(format!("`api` is {}; this host implements plug-in API levels 1 to {API_LEVEL}", self.api)));
|
||||
}
|
||||
if let Some(names) = &self.permissions {
|
||||
permissions::validate(self.kind, names)?;
|
||||
if let Some(names) = &self.permissions
|
||||
&& permissions::validate(self.kind, names)?.contains(&Permission::Progress)
|
||||
&& self.api < PROGRESS_API
|
||||
{
|
||||
return Err(Error::Manifest(format!("permission `progress` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_extensions()?;
|
||||
match (self.budget, self.kind) {
|
||||
@@ -681,12 +684,20 @@ mod tests {
|
||||
let exporter = Manifest::parse(br#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"]}"#).unwrap();
|
||||
assert_eq!(exporter.permissions(), [Permission::DocRead, Permission::ExportWrite]);
|
||||
assert!(!Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","permissions":[]}"#).unwrap().asks_permissions());
|
||||
// Level 2 adds `progress`, which only a level-2 manifest may list.
|
||||
let level2 = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["progress","doc.read"]}"#).unwrap();
|
||||
assert_eq!((level2.api, level2.permissions()), (2, vec![Permission::DocRead, Permission::Progress]));
|
||||
assert_eq!(serde_json::to_value(&level2).unwrap()["api"], json!(2));
|
||||
let plain2 = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","api":2}"#).unwrap();
|
||||
assert!(!plain2.permissions().contains(&Permission::Progress), "never implied");
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["doc.read","net.fetch"]}"#, "unknown permission `net.fetch`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["ui.panel"]}"#, "reserved"),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","permissions":["doc.read"]}"#, "effect.render"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":"doc.read"}"#, "manifest"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2}"#, "`api` is 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["progress"]}"#, "`progress` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"),
|
||||
] {
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
//! approves when it is installed ([`Grant`], kept in [`crate::registry`]), and which the host
|
||||
//! enforces on every run.
|
||||
//!
|
||||
//! `doc.read`, `doc.write`, `state` and the reserved `progress` are the names of the plug-in
|
||||
//! capability model in storytold/photocraft#662; the other names are VectorCraft's own. A manifest
|
||||
//! without `permissions` gets the ones its kind implies ([`Permission::implied`]): what every
|
||||
//! plug-in of that kind could do before manifests listed them.
|
||||
//! `doc.read`, `doc.write`, `state` and `progress` are the names of the plug-in capability model in
|
||||
//! storytold/photocraft#662; the other names are VectorCraft's own. A manifest without
|
||||
//! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of
|
||||
//! that kind could do before manifests listed them. `progress`, which lets a plug-in use the host
|
||||
//! imports of API level 2 ([`crate::host`]), is never implied: a manifest lists it.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -13,7 +14,11 @@ use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this.
|
||||
pub const API_LEVEL: u32 = 1;
|
||||
pub const API_LEVEL: u32 = 2;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`
|
||||
/// permission they need.
|
||||
pub const PROGRESS_API: u32 = 2;
|
||||
|
||||
/// Most permissions a manifest may list.
|
||||
pub const MAX_PERMISSIONS: usize = 16;
|
||||
@@ -26,7 +31,7 @@ pub const MAX_SHOWN_FIELD: usize = 64;
|
||||
|
||||
/// Names kept for host calls a later plug-in API adds. This host grants none of them, so a
|
||||
/// manifest that lists one is refused when it is installed.
|
||||
pub const RESERVED: &[&str] = &["progress", "ui.panel", "ui.tool"];
|
||||
pub const RESERVED: &[&str] = &["ui.panel", "ui.tool"];
|
||||
|
||||
/// One thing a plug-in may do.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
@@ -50,11 +55,22 @@ pub enum Permission {
|
||||
/// Read a file the user opens and make a new document from it (an importer).
|
||||
#[serde(rename = "import.read")]
|
||||
ImportRead,
|
||||
/// Report how far a run has got, see that the user asked it to stop and write log lines: the
|
||||
/// host imports of API level 2 ([`crate::host::IMPORTS`]).
|
||||
#[serde(rename = "progress")]
|
||||
Progress,
|
||||
}
|
||||
|
||||
/// Every permission this host grants, in the order prompts list them.
|
||||
pub const ALL: [Permission; 6] =
|
||||
[Permission::DocRead, Permission::DocWrite, Permission::State, Permission::EffectRender, Permission::ExportWrite, Permission::ImportRead];
|
||||
pub const ALL: [Permission; 7] = [
|
||||
Permission::DocRead,
|
||||
Permission::DocWrite,
|
||||
Permission::State,
|
||||
Permission::EffectRender,
|
||||
Permission::ExportWrite,
|
||||
Permission::ImportRead,
|
||||
Permission::Progress,
|
||||
];
|
||||
|
||||
impl Permission {
|
||||
/// Its name in a manifest and in `plugin.install`'s `grant`.
|
||||
@@ -66,6 +82,7 @@ impl Permission {
|
||||
Permission::EffectRender => "effect.render",
|
||||
Permission::ExportWrite => "export.write",
|
||||
Permission::ImportRead => "import.read",
|
||||
Permission::Progress => "progress",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,11 +100,18 @@ impl Permission {
|
||||
Permission::EffectRender => "Change how the objects its effect is applied to are drawn",
|
||||
Permission::ExportWrite => "Write the document as a file in its own format",
|
||||
Permission::ImportRead => "Read files you open in its format and make documents from them",
|
||||
Permission::Progress => "Show its progress, see Cancel and write log lines",
|
||||
}
|
||||
}
|
||||
|
||||
/// The permissions a plug-in of `kind` may list, which are also the ones a manifest without
|
||||
/// `permissions` gets.
|
||||
/// May a plug-in of `kind` list it: one its kind implies, or `progress`, which any kind may
|
||||
/// list.
|
||||
pub fn applies(self, kind: Kind) -> bool {
|
||||
self == Permission::Progress || Permission::implied(kind).contains(&self)
|
||||
}
|
||||
|
||||
/// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list
|
||||
/// `progress` ([`Permission::applies`]).
|
||||
pub fn implied(kind: Kind) -> &'static [Permission] {
|
||||
match kind {
|
||||
Kind::Filter => &[Permission::DocRead, Permission::DocWrite, Permission::State],
|
||||
@@ -124,7 +148,7 @@ pub(crate) fn validate(kind: Kind, names: &[String]) -> Result<Vec<Permission>>
|
||||
}
|
||||
return Err(Error::Manifest(format!("unknown permission `{shown}`")));
|
||||
};
|
||||
if !Permission::implied(kind).contains(&p) {
|
||||
if !p.applies(kind) {
|
||||
return Err(Error::Manifest(format!("permission `{shown}` doesn't apply to a plug-in of kind `{}`", kind.name())));
|
||||
}
|
||||
if out.contains(&p) {
|
||||
@@ -226,12 +250,21 @@ mod tests {
|
||||
assert!(validate(Kind::Effect, &list(&["doc.read", "effect.render"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, &list(&["export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, &list(&["import.read"])).unwrap(), [Permission::ImportRead]);
|
||||
// Any kind may list `progress`, which no kind implies.
|
||||
assert_eq!(validate(Kind::Filter, &list(&["progress", "doc.read"])).unwrap(), [Permission::DocRead, Permission::Progress]);
|
||||
assert!(validate(Kind::Effect, &list(&["doc.read", "effect.render", "progress"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, &list(&["progress", "export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, &list(&["progress", "import.read"])).unwrap(), [Permission::ImportRead, Permission::Progress]);
|
||||
assert!(
|
||||
[Kind::Filter, Kind::Effect, Kind::Exporter, Kind::Importer].iter().all(|k| !Permission::implied(*k).contains(&Permission::Progress))
|
||||
);
|
||||
for (kind, names, says) in [
|
||||
(Kind::Importer, &["import.read", "doc.read"][..], "`doc.read` doesn't apply to a plug-in of kind `importer`"),
|
||||
(Kind::Importer, &[], "needs the permission `import.read`"),
|
||||
(Kind::Exporter, &["export.write", "doc.read", "import.read"], "`import.read` doesn't apply to a plug-in of kind `exporter`"),
|
||||
(Kind::Filter, &["doc.read", "clipboard"][..], "unknown permission `clipboard`"),
|
||||
(Kind::Filter, &["progress"], "`progress` is reserved"),
|
||||
(Kind::Filter, &["ui.panel"], "`ui.panel` is reserved"),
|
||||
(Kind::Filter, &["progress", "progress"], "`progress` is listed twice"),
|
||||
(Kind::Filter, &["export.write"], "doesn't apply to a plug-in of kind `filter`"),
|
||||
(Kind::Exporter, &["doc.read", "export.write", "doc.read"], "`doc.read` is listed twice"),
|
||||
(Kind::Effect, &["doc.read"], "needs the permission `effect.render`"),
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
|
||||
|
||||
use wasmi::{
|
||||
Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc,
|
||||
TypedResumableCall, WasmParams, WasmResults,
|
||||
Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, WasmParams,
|
||||
WasmResults,
|
||||
};
|
||||
|
||||
use crate::host::{self, Deadline, Host, Report, Run};
|
||||
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest};
|
||||
use crate::{Error, Result};
|
||||
use crate::permissions::Permission;
|
||||
use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in ABI version this host implements (`vc_abi_version` must return it).
|
||||
pub const ABI_VERSION: i32 = 1;
|
||||
@@ -96,33 +98,10 @@ impl std::fmt::Debug for Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
/// When a run must stop (native: a wall-clock deadline).
|
||||
struct Deadline {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant,
|
||||
}
|
||||
|
||||
impl Deadline {
|
||||
fn new(limits: &Limits) -> Self {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = limits;
|
||||
Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
at: std::time::Instant::now() + std::time::Duration::from_millis(limits.wall_time_ms),
|
||||
}
|
||||
}
|
||||
fn check(&self) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::time::Instant::now() >= self.at {
|
||||
return Err(Error::Limit("time budget".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One live instance: a store with its own memory limit, and the module's exports.
|
||||
/// One live instance: a store with its own memory limit and the run's state, and the module's
|
||||
/// exports.
|
||||
struct Live {
|
||||
store: Store<StoreLimits>,
|
||||
store: Store<Host>,
|
||||
instance: Instance,
|
||||
memory: Memory,
|
||||
}
|
||||
@@ -152,7 +131,9 @@ fn wasm_err(e: wasmi::Error) -> Error {
|
||||
type RunArgs = (i32, i32, i32, i32);
|
||||
|
||||
impl Plugin {
|
||||
/// Validates and loads a module: checks the ABI version, the exports and reads the manifest.
|
||||
/// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and
|
||||
/// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`])
|
||||
/// and its manifest allows.
|
||||
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
|
||||
if bytes.len() > limits.max_module_bytes {
|
||||
return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes)));
|
||||
@@ -168,17 +149,12 @@ impl Plugin {
|
||||
.set_max_recursion_depth(limits.max_recursion_depth.max(16));
|
||||
let engine = Engine::new(&config);
|
||||
let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?;
|
||||
if let Some(imp) = module.imports().next() {
|
||||
return Err(Error::Abi(format!(
|
||||
"the module imports `{}.{}`, but plug-ins get no host imports (no WASI, files or network)",
|
||||
imp.module(),
|
||||
imp.name()
|
||||
)));
|
||||
}
|
||||
let imports = host::check_imports(&module)?;
|
||||
let hash = crate::permissions::sha256_hex(bytes);
|
||||
let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 };
|
||||
let deadline = Deadline::new(&p.limits);
|
||||
let mut live = p.instantiate()?;
|
||||
let deadline = Deadline::new(p.limits.wall_time_ms);
|
||||
// The manifest isn't read yet: every host import is linked, and what it reports is dropped.
|
||||
let mut live = p.instantiate(Run::new("", false, false, deadline), true, &mut Report::default())?;
|
||||
let version: TypedFunc<(), i32> = live.func("vc_abi_version")?;
|
||||
let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?;
|
||||
if v != ABI_VERSION {
|
||||
@@ -191,6 +167,7 @@ impl Plugin {
|
||||
e => e,
|
||||
})?;
|
||||
p.manifest = Manifest::parse(&text)?;
|
||||
host::check_granted(&p.manifest, &imports)?;
|
||||
// A heavy filter's runs get the larger budget the host allows for one, which the host
|
||||
// lets the user allow or refuse before installing it.
|
||||
if p.manifest.budget == crate::Budget::Heavy {
|
||||
@@ -237,16 +214,24 @@ impl Plugin {
|
||||
self.serial = serial;
|
||||
}
|
||||
|
||||
fn instantiate(&self) -> Result<Live> {
|
||||
/// A new instance for `run`, with the host imports linked when `granted`. When the module's
|
||||
/// start function fails, what it reported through the host imports goes to `report`.
|
||||
fn instantiate(&self, run: Run, granted: bool, report: &mut Report) -> Result<Live> {
|
||||
let limits =
|
||||
StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build();
|
||||
let mut store = Store::new(&self.engine, limits);
|
||||
store.limiter(|l| l);
|
||||
let mut store = Store::new(&self.engine, Host { limits, run });
|
||||
store.limiter(|h| &mut h.limits);
|
||||
// The start function (if any) runs on one slice of fuel: it runs before `call` can check
|
||||
// the deadline or a cancel between slices, so a heavy budget would let it run for minutes.
|
||||
store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?;
|
||||
let linker = Linker::<StoreLimits>::new(&self.engine);
|
||||
let instance = linker.instantiate_and_start(&mut store, &self.module).map_err(wasm_err)?;
|
||||
let linker = host::linker(&self.engine, granted);
|
||||
let instance = match linker.instantiate_and_start(&mut store, &self.module) {
|
||||
Ok(instance) => instance,
|
||||
Err(e) => {
|
||||
*report = std::mem::take(&mut store.data_mut().run.report);
|
||||
return Err(wasm_err(e));
|
||||
}
|
||||
};
|
||||
let memory =
|
||||
instance.get_memory(&store, "memory").ok_or_else(|| Error::Abi("the module must export its linear memory as `memory`".into()))?;
|
||||
Ok(Live { store, instance, memory })
|
||||
@@ -254,6 +239,12 @@ impl Plugin {
|
||||
|
||||
/// Calls `f` with at most `fuel` instructions, in slices, checking the deadline and the
|
||||
/// caller's cancellation ([`vectorcraft_doc::cancel`]) between them.
|
||||
///
|
||||
/// wasmi pauses before an instruction that the store's fuel can't pay for, and charges nothing
|
||||
/// for it. It charges a `memory.fill` or `memory.copy` for its whole length before writing, so
|
||||
/// up to that cost can be left in the store at a pause. Each slice tops the store up to the
|
||||
/// slice size, keeping that fuel, and a run ends with the instruction budget only when the
|
||||
/// store's fuel and the rest of the budget together can't pay for the next instruction.
|
||||
fn call<P: WasmParams, R: WasmResults>(&self, live: &mut Live, f: &TypedFunc<P, R>, params: P, fuel: u64, deadline: &Deadline) -> Result<R> {
|
||||
let mut left = fuel;
|
||||
let give = left.min(FUEL_SLICE);
|
||||
@@ -266,14 +257,16 @@ impl Plugin {
|
||||
TypedResumableCall::HostTrap(_) => return Err(Error::Trap("unexpected host trap".into())),
|
||||
TypedResumableCall::OutOfFuel(inv) => {
|
||||
let need = inv.required_fuel();
|
||||
if left == 0 || need > left {
|
||||
let held = live.store.get_fuel().map_err(wasm_err)?;
|
||||
let total = held.saturating_add(left);
|
||||
if need > total {
|
||||
return Err(Error::Limit("instruction budget".into()));
|
||||
}
|
||||
deadline.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
let give = left.min(FUEL_SLICE.max(need));
|
||||
left -= give;
|
||||
live.store.set_fuel(give).map_err(wasm_err)?;
|
||||
let fill = total.min(FUEL_SLICE.max(need)).max(held);
|
||||
left -= fill - held;
|
||||
live.store.set_fuel(fill).map_err(wasm_err)?;
|
||||
call = inv.resume(&mut live.store).map_err(wasm_err)?;
|
||||
}
|
||||
}
|
||||
@@ -288,21 +281,39 @@ impl Plugin {
|
||||
|
||||
/// [`Plugin::run`] with other time and instruction budgets (live effects get a shorter one).
|
||||
pub fn run_limited(&self, input: &[u8], params: &[u8], limits: &Limits) -> Result<Vec<u8>> {
|
||||
// wasmi reports misbehaving modules as errors; a panic would be a bug in it, and must
|
||||
// still not take the document down (native builds; wasm aborts on panic anyway).
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits)));
|
||||
run.map_err(|_| Error::Trap("the runtime panicked".into()))?
|
||||
self.run_reporting(input, params, limits).0
|
||||
}
|
||||
|
||||
fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits) -> Result<Vec<u8>> {
|
||||
/// [`Plugin::run_limited`], and what the run reported through the host imports: its last
|
||||
/// progress report and its log lines, which also go to the app's log under its id. Inside a
|
||||
/// [`vectorcraft_doc::cancel::scope`] its progress goes to the scope's sink (a live effect's
|
||||
/// doesn't) and `vc_cancelled` sees the scope's Cancel.
|
||||
pub fn run_reporting(&self, input: &[u8], params: &[u8], limits: &Limits) -> (Result<Vec<u8>>, Report) {
|
||||
let mut report = Report::default();
|
||||
// wasmi reports misbehaving modules as errors; a panic would be a bug in it, and must
|
||||
// still not take the document down (native builds; wasm aborts on panic anyway).
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report)));
|
||||
(run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report)
|
||||
}
|
||||
|
||||
fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report) -> Result<Vec<u8>> {
|
||||
let total = input.len().checked_add(params.len()).filter(|b| *b <= i32::MAX as usize && *b <= self.limits.max_memory_bytes / 2);
|
||||
total.ok_or_else(|| Error::Limit("memory budget (the selection is too large to hand over)".into()))?;
|
||||
let deadline = Deadline::new(limits);
|
||||
let mut live = self.instantiate()?;
|
||||
let deadline = Deadline::new(limits.wall_time_ms);
|
||||
let m = &self.manifest;
|
||||
let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline);
|
||||
let mut live = self.instantiate(run, m.permissions().contains(&Permission::Progress), report)?;
|
||||
let out = self.run_live(&mut live, input, params, limits, &deadline);
|
||||
*report = std::mem::take(&mut live.store.data_mut().run.report);
|
||||
out
|
||||
}
|
||||
|
||||
/// Hands `input` and `params` to the instance `live` and runs `vc_run` → the output JSON bytes.
|
||||
fn run_live(&self, live: &mut Live, input: &[u8], params: &[u8], limits: &Limits, deadline: &Deadline) -> Result<Vec<u8>> {
|
||||
let alloc: TypedFunc<i32, i32> = live.func("vc_alloc")?;
|
||||
let run: TypedFunc<RunArgs, i64> = live.func("vc_run")?;
|
||||
let place = |live: &mut Live, bytes: &[u8]| -> Result<usize> {
|
||||
let ptr = self.call(live, &alloc, bytes.len().max(1) as i32, limits.fuel_base, &deadline)? as u32 as usize;
|
||||
let ptr = self.call(live, &alloc, bytes.len().max(1) as i32, limits.fuel_base, deadline)? as u32 as usize;
|
||||
if ptr == 0 {
|
||||
return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into()));
|
||||
}
|
||||
@@ -311,10 +322,14 @@ impl Plugin {
|
||||
live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(bytes);
|
||||
Ok(ptr)
|
||||
};
|
||||
let iptr = place(&mut live, input)?;
|
||||
let pptr = place(&mut live, params)?;
|
||||
let iptr = place(live, input)?;
|
||||
let pptr = place(live, params)?;
|
||||
let fuel = limits.fuel_base.saturating_add((input.len() as u64).saturating_mul(limits.fuel_per_byte));
|
||||
let packed = self.call(&mut live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, &deadline)?;
|
||||
let packed = self.call(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline)?;
|
||||
// A cancelled run, or one past its time budget, changes nothing, also when the plug-in saw
|
||||
// `vc_cancelled` and returned.
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
deadline.check()?;
|
||||
if packed < 0 {
|
||||
return Err(Error::Failed(format!("vc_run returned error code {packed}")));
|
||||
}
|
||||
|
||||
@@ -42,11 +42,51 @@ pub fn returning(manifest: &str, output: &str) -> String {
|
||||
/// A plug-in whose `vc_run` runs `first` (instructions, with the locals it declares first), then
|
||||
/// returns `output`.
|
||||
fn then_returning(manifest: &str, first: &str, output: &str) -> String {
|
||||
with_imports(manifest, "", first, output)
|
||||
}
|
||||
|
||||
/// A plug-in with the module fields `imports` before the others, whose `vc_run` runs `first`, then
|
||||
/// returns `output`.
|
||||
pub fn with_imports(manifest: &str, imports: &str, first: &str, output: &str) -> String {
|
||||
let run = format!("{first} (i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const {OUTPUT_AT}))", output.len());
|
||||
let extra = format!(r#"(data (i32.const {OUTPUT_AT}) "{}")"#, string(output));
|
||||
let extra = format!(r#"{imports} (data (i32.const {OUTPUT_AT}) "{}")"#, string(output));
|
||||
module(manifest, &run, &extra, (OUTPUT_AT + output.len()).div_ceil(0x1_0000) as u32 + 1)
|
||||
}
|
||||
|
||||
/// The host imports of plug-in API level 2 ([`crate::host::IMPORTS`]), as `$vc_progress`,
|
||||
/// `$vc_cancelled` and `$vc_log`.
|
||||
pub const HOST_IMPORTS: &str = r#"(import "env" "vc_progress" (func $vc_progress (param i64 i64)))
|
||||
(import "env" "vc_cancelled" (func $vc_cancelled (result i32)))
|
||||
(import "env" "vc_log" (func $vc_log (param i32 i32 i32) (result i32)))"#;
|
||||
|
||||
/// A plug-in of API level 2 (its manifest gives `api` 2 and lists `progress`) that imports the
|
||||
/// host functions ([`HOST_IMPORTS`]) and whose `vc_run` runs `first`, which may call them, then
|
||||
/// returns `output`.
|
||||
pub fn reporting(manifest: &str, first: &str, output: &str) -> String {
|
||||
with_imports(manifest, HOST_IMPORTS, first, output)
|
||||
}
|
||||
|
||||
/// A plug-in of API level 2 that counts `steps` down, reporting each step's progress and checking
|
||||
/// `vc_cancelled` before it: when that says the run was cancelled it returns `stopped`, else
|
||||
/// `output` once the steps are done.
|
||||
pub fn cooperating(manifest: &str, steps: u64, stopped: &str, output: &str) -> String {
|
||||
let first = format!(
|
||||
r#"(local $n i64) (local.set $n (i64.const {steps}))
|
||||
(block $done (loop $step
|
||||
(br_if $done (i64.le_s (local.get $n) (i64.const 0)))
|
||||
(call $vc_progress (i64.sub (i64.const {steps}) (local.get $n)) (i64.const {steps}))
|
||||
(if (call $vc_cancelled) (then (return (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const {STOPPED_AT})))))
|
||||
(local.set $n (i64.sub (local.get $n) (i64.const 1)))
|
||||
(br $step)))"#,
|
||||
len = stopped.len(),
|
||||
);
|
||||
let imports = format!(r#"{HOST_IMPORTS} (data (i32.const {STOPPED_AT}) "{}")"#, string(stopped));
|
||||
with_imports(manifest, &imports, &first, output)
|
||||
}
|
||||
|
||||
/// Where [`cooperating`] keeps what it returns when it is cancelled.
|
||||
const STOPPED_AT: usize = 0x8000;
|
||||
|
||||
/// A plug-in that counts `steps` down before it returns `output`. Each step costs a few
|
||||
/// instructions, so a test picks work that a light budget can't finish and a heavy one can, or
|
||||
/// that runs until it is cancelled.
|
||||
|
||||
Reference in New Issue
Block a user