Merge main into feat/plugin-api-importers-place

This commit is contained in:
dotCooCoo committed 2026-11-25 09:46:45 -08:00
commit 388e1f29ef
1401 files changed
+204519 -268412

No files matched your search

+5 -5
View File
@@ -807,7 +807,7 @@ mod tests {
crate::safe_mode::set_active(None);
let dir = std::env::temp_dir().join(format!("vc-effect-overlap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(crate::safe_mode::begin_launch(&dir), None);
assert_eq!(crate::safe_mode::begin_launch(&dir), []);
let marker = || {
let files = std::fs::read_dir(&dir).unwrap().filter_map(|e| Some(e.ok()?.path()));
let json = files.filter(|p| p.extension().is_some_and(|x| x == "json")).collect::<Vec<_>>();
@@ -816,8 +816,8 @@ mod tests {
};
let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#);
let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap();
let named = Some(crate::safe_mode::Item::of(&plugin));
assert_eq!(marker(), None);
let named = vec![crate::safe_mode::Item::of(&plugin)];
assert_eq!(marker(), []);
assert!(begin_run(&plugin), "the first run is guarded");
assert!(begin_run(&plugin), "a run that starts while the first is running is guarded");
@@ -829,9 +829,9 @@ mod tests {
end_run(plugin.serial(), true);
assert_eq!(marker(), named, "the third run is still running");
end_run(plugin.serial(), false);
assert_eq!(marker(), None, "no run is running");
assert_eq!(marker(), [], "no run is running");
assert!(!begin_run(&plugin), "later runs aren't guarded");
assert_eq!(marker(), None);
assert_eq!(marker(), []);
crate::safe_mode::end_launch();
crate::safe_mode::forget_previous();
+2 -1
View File
@@ -40,6 +40,7 @@ pub mod effect;
pub mod export;
pub mod host;
pub mod import;
pub mod loader;
pub mod manifest;
pub mod objects;
pub mod painted;
@@ -52,7 +53,7 @@ pub mod wat;
pub use dialog::ParamUi;
pub use host::{LogLevel, LogLine, Report};
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec};
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec};
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
#[doc(hidden)]
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
+753
View File
@@ -0,0 +1,753 @@
//! Loads plug-ins on worker threads.
//!
//! [`Loads::start`] hands its jobs to a pool of at most [`MAX_WORKERS`] threads and returns at
//! once. The web build has no threads, so there it runs the jobs one after the other before it
//! returns. Each job runs inside a panic boundary: a job that panics fails with [`Error::Failed`],
//! and the launch marker stops naming its item ([`crate::safe_mode::loading`]), as when it loads.
//! A job that takes [`LOAD_DEADLINE`] or longer fails too, and the marker names its item until its
//! thread returns; while it is still running, its thread is left to finish on its own, and another worker
//! takes the jobs after it, up to twice as many threads as were started. While
//! [`MAX_STUCK_THREADS`] threads in the process still run jobs past their deadline, no load starts
//! a thread. When no thread is left to take them, the jobs not started fail.
//!
//! The caller takes the outcomes in the order of the jobs, whatever order they finish in
//! ([`Loads::ready`]), so it installs them in the same order on every launch. A job starts only
//! while fewer than twice the workers' count of outcomes before it are waiting to be taken or are
//! still held by the caller ([`Loads::release`]), so the loaded modules held at once stay bounded
//! however many jobs there are.
use std::collections::VecDeque;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::Duration;
use web_time::Instant;
use crate::safe_mode::{self, Item};
use crate::{Error, Result};
/// The most worker threads one [`Loads`] starts, besides those that replace a worker whose job
/// passed [`LOAD_DEADLINE`].
pub const MAX_WORKERS: usize = 4;
/// How long one job may take; one that takes longer fails as not finished.
pub const LOAD_DEADLINE: Duration = Duration::from_secs(10);
/// How often a wait looks at the deadlines while no job finishes.
const TICK: Duration = Duration::from_millis(50);
/// The most loader threads in the process still running a job past its deadline. While that many
/// are, no [`Loads`] starts another thread, so loads started again and again on files whose reads
/// never return don't pile up threads.
pub const MAX_STUCK_THREADS: usize = 2 * MAX_WORKERS;
/// Loader threads in the process running a job past its deadline, across every [`Loads`].
static STUCK_THREADS: AtomicUsize = AtomicUsize::new(0);
/// The [`Error::Failed`] message of a job that failed because no thread was left to run it.
pub const NO_THREAD: &str = "no thread was left to load it";
/// One plug-in to load: the item the launch marker names while it loads, and the work, which runs
/// on a worker thread.
pub struct Job<T> {
pub item: Option<Item>,
pub work: Box<dyn FnOnce() -> Result<T> + Send>,
}
impl<T> Job<T> {
pub fn new(item: Option<Item>, work: impl FnOnce() -> Result<T> + Send + 'static) -> Self {
Job { item, work: Box::new(work) }
}
}
/// The time since a fixed start, for the deadlines.
type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
/// A job's outcome as its worker sends it: the job, its result and how long it took.
type Done<T> = (usize, Result<T>, Duration);
/// What the workers and [`Loads`] share.
struct State<T> {
/// The jobs not started yet, in order.
queue: VecDeque<(usize, Job<T>)>,
/// When each job started, and whether it has finished or passed its deadline.
started: Vec<Option<Duration>>,
finished: Vec<bool>,
expired: Vec<bool>,
/// Jobs whose index is below this may start.
limit: usize,
/// Worker threads alive, and how many of them run a job past its deadline.
workers: usize,
stuck: usize,
}
struct Pool<T> {
state: Mutex<State<T>>,
/// Told when a job may start, or when the queue is emptied.
wake: Condvar,
}
impl<T> Pool<T> {
fn lock(&self) -> MutexGuard<'_, State<T>> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
/// Counts a worker as alive until its thread ends, however it ends.
struct Alive<T>(Arc<Pool<T>>);
impl<T> Drop for Alive<T> {
fn drop(&mut self) {
self.0.lock().workers -= 1;
}
}
/// Jobs loading on worker threads ([`Loads::start`]).
pub struct Loads<T: Send + 'static> {
pool: Arc<Pool<T>>,
results: Mutex<Receiver<Done<T>>>,
send: Sender<Done<T>>,
outcomes: Vec<Option<Result<T>>>,
/// The outcomes before this one were taken ([`Loads::ready`]).
next: usize,
/// Of those, the ones the caller is done with ([`Loads::release`]).
released: usize,
/// How many jobs past `next` may start.
window: usize,
clock: Clock,
deadline: Duration,
/// The workers [`Loads::begin`] starts, and whether it has.
workers: usize,
begun: bool,
/// The process's count of stuck loader threads ([`STUCK_THREADS`]), and its most.
stuck_threads: &'static AtomicUsize,
max_stuck: usize,
/// Tests: no thread can be started from now on.
#[cfg(test)]
pub(crate) refuse_threads: bool,
}
impl<T: Send + 'static> Loads<T> {
/// Starts `jobs` on `min(available parallelism, MAX_WORKERS)` threads.
pub fn start(jobs: Vec<Job<T>>) -> Self {
let mut loads = Self::deferred(jobs);
loads.begin();
loads
}
/// `jobs` to start on `min(available parallelism, MAX_WORKERS)` threads once [`Loads::begin`]
/// is called (or something waits for them).
pub fn deferred(jobs: Vec<Job<T>>) -> Self {
Self::deferred_on(jobs, std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_WORKERS))
}
/// [`Loads::deferred`] on `workers` threads (at least one).
pub(crate) fn deferred_on(jobs: Vec<Job<T>>, workers: usize) -> Self {
let origin = Instant::now();
Self::with(jobs, workers, LOAD_DEADLINE, Arc::new(move || origin.elapsed()))
}
/// Starts the jobs, unless they started already.
pub fn begin(&mut self) {
if self.begun {
return;
}
self.begun = true;
if cfg!(target_arch = "wasm32") {
// The web build has no threads: each job runs here, in order.
let jobs: Vec<_> = self.pool.lock().queue.drain(..).collect();
for (i, job) in jobs {
// A job can't be stopped here, but one that took past its deadline fails as on
// the desktop.
let at = (self.clock)();
let r = run_job(job);
let took = (self.clock)().saturating_sub(at);
self.record((i, r, took));
}
} else {
for _ in 0..self.workers.min(self.outcomes.len()) {
self.spawn_worker();
}
}
}
#[cfg(test)]
fn start_with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
let mut loads = Self::with(jobs, workers, deadline, clock);
loads.begin();
loads
}
fn with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
let n = jobs.len();
let workers = workers.max(1);
let window = workers * 2;
let state = State {
queue: jobs.into_iter().enumerate().collect(),
started: vec![None; n],
finished: vec![false; n],
expired: vec![false; n],
limit: window,
workers: 0,
stuck: 0,
};
let (send, results) = mpsc::channel();
Loads {
pool: Arc::new(Pool { state: Mutex::new(state), wake: Condvar::new() }),
results: Mutex::new(results),
send,
outcomes: (0..n).map(|_| None).collect(),
next: 0,
released: 0,
window,
clock,
deadline,
workers,
begun: false,
stuck_threads: &STUCK_THREADS,
max_stuck: MAX_STUCK_THREADS,
#[cfg(test)]
refuse_threads: false,
}
}
/// Starts a thread that takes jobs until none are left → whether it started.
fn spawn_worker(&self) -> bool {
#[cfg(test)]
if self.refuse_threads {
return false;
}
if self.stuck_threads.load(Ordering::SeqCst) >= self.max_stuck {
log::warn!("not starting a thread to load plug-ins: {} loader threads are still running loads past their deadline", self.max_stuck);
return false;
}
let pool = self.pool.clone();
let send = self.send.clone();
let clock = self.clock.clone();
let target = self.workers;
let stuck_threads = self.stuck_threads;
self.pool.lock().workers += 1;
let spawned = std::thread::Builder::new().name("plug-in loader".into()).spawn(move || {
let alive = Alive(pool);
loop {
let (i, job, at) = {
let mut s = alive.0.lock();
loop {
match s.queue.front() {
None => return,
Some((i, _)) if *i < s.limit => break,
Some(_) => s = alive.0.wake.wait(s).unwrap_or_else(|e| e.into_inner()),
}
}
let Some((i, job)) = s.queue.pop_front() else { return };
let at = clock();
s.started[i] = Some(at);
(i, job, at)
};
let r = run_job(job);
// A worker whose job passed its deadline and was replaced ends once the job
// returns, unless the workers able to take jobs are fewer than started. The time
// the job took is read while the job is marked finished, so a deadline check that
// finds it unfinished counts a time that its own outcome reaches too.
let (took, retire) = {
let mut s = alive.0.lock();
let took = clock().saturating_sub(at);
s.finished[i] = true;
let retire = s.expired[i] && {
s.stuck -= 1;
stuck_threads.fetch_sub(1, Ordering::SeqCst);
s.workers - s.stuck > target
};
(took, retire)
};
let _ = send.send((i, r, took));
if retire {
return;
}
}
});
if let Err(e) = spawned {
self.pool.lock().workers -= 1;
log::warn!("can't start a thread to load plug-ins: {e}");
return false;
}
true
}
/// Takes the outcomes that came in and fails the jobs past their deadline → whether every job
/// has its outcome.
pub fn poll(&mut self) -> bool {
loop {
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv();
let Ok(done) = next else { break };
self.record(done);
}
self.expire();
self.outcomes.iter().all(Option::is_some)
}
/// The outcomes not taken yet that come in order from the last one taken, without waiting
/// ([`Loads::poll`] first). The jobs after them start as the caller releases them
/// ([`Loads::release`]).
pub fn ready(&mut self) -> Vec<Result<T>> {
self.poll();
let mut out = Vec::new();
while let Some(o) = self.outcomes.get_mut(self.next).and_then(Option::take) {
out.push(o);
self.next += 1;
}
out
}
/// The caller is done with `n` more of the outcomes it took (installed or dropped them): as
/// many more jobs may start, so the outcomes held, here and by the caller, stay at most twice
/// the workers' count.
pub fn release(&mut self, n: usize) {
let released = (self.released + n).min(self.next);
if released != self.released {
self.released = released;
self.pool.lock().limit = released + self.window;
self.pool.wake.notify_all();
}
}
/// Whether every outcome has been taken.
pub fn taken(&self) -> bool {
self.next == self.outcomes.len()
}
/// Whether the next outcome in order can be taken ([`Loads::ready`]).
pub fn next_ready(&mut self) -> bool {
self.poll();
self.outcomes.get(self.next).is_some_and(Option::is_some)
}
/// Waits until the next outcome in order can be taken, or every one has been. Jobs that have
/// not been started are started first ([`Loads::begin`]).
pub fn wait_next(&mut self) {
self.begin();
while !self.taken() && !self.next_ready() {
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
match next {
Ok(done) => self.record(done),
Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {}
}
}
}
/// Waits for every outcome → those not taken yet, in the order of the jobs. The outcomes taken
/// before ([`Loads::ready`]) count as released, so the jobs after them start.
pub fn wait(mut self) -> Vec<Result<T>> {
self.release(self.next - self.released);
let mut out = Vec::new();
while !self.taken() {
self.wait_next();
let ready = self.ready();
self.release(ready.len());
out.extend(ready);
}
out
}
fn record(&mut self, (i, r, took): Done<T>) {
let r = if took >= self.deadline { Err(self.too_long()) } else { r };
// An outcome that comes after the job failed past its deadline is dropped.
if let Some(slot @ None) = self.outcomes.get_mut(i) {
*slot = Some(r);
}
}
fn too_long(&self) -> Error {
let secs = self.deadline.as_secs();
Error::Failed(format!("did not finish loading within {secs} s"))
}
/// Fails the jobs still running past their deadline, starting a worker in place of each one's
/// while the threads alive are fewer than twice the workers started. When no worker is left to
/// take the jobs not started (none could be made, or every one is stuck), those fail too.
fn expire(&mut self) {
if !self.begun {
return;
}
let mut expired = Vec::new();
{
let mut s = self.pool.lock();
// Read while the workers can't mark a job finished ([`Loads::spawn_worker`]).
let now = (self.clock)();
for i in 0..self.outcomes.len() {
let late = s.started[i].is_some_and(|at| now.saturating_sub(at) >= self.deadline);
if late && !s.finished[i] && !s.expired[i] && self.outcomes[i].is_none() {
s.expired[i] = true;
s.stuck += 1;
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
expired.push(i);
}
}
}
for i in &expired {
self.outcomes[*i] = Some(Err(self.too_long()));
}
for _ in &expired {
let room = {
let s = self.pool.lock();
!s.queue.is_empty() && s.workers < 2 * self.workers
};
if !room || !self.spawn_worker() {
break;
}
}
// The jobs not started are taken from the queue under the lock that finds no worker able to
// take them, so a stuck worker that returns can't start one of them in between. Only those
// fail: a job already started reports its own outcome.
let stranded: Vec<usize> = {
let mut s = self.pool.lock();
if s.workers <= s.stuck { s.queue.drain(..).map(|(i, _)| i).collect() } else { Vec::new() }
};
for i in stranded {
if let Some(o @ None) = self.outcomes.get_mut(i) {
*o = Some(Err(Error::Failed(NO_THREAD.into())));
}
}
}
}
impl<T: Send + 'static> Drop for Loads<T> {
/// Jobs not started yet are dropped; the running ones are given until their deadline, so the
/// launch marker is not left naming a plug-in that was still loading when the app quit.
fn drop(&mut self) {
self.pool.lock().queue.clear();
self.pool.wake.notify_all();
loop {
let running = {
let s = self.pool.lock();
let now = (self.clock)();
(0..self.outcomes.len())
.any(|i| !s.finished[i] && !s.expired[i] && s.started[i].is_some_and(|at| now.saturating_sub(at) < self.deadline))
};
if !running {
break;
}
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
if let Ok(done) = next {
self.record(done);
}
}
// A job still running past its deadline leaves its thread stuck, and the thread counts
// against the process's stuck threads until the job returns.
let mut s = self.pool.lock();
for i in 0..self.outcomes.len() {
if s.started[i].is_some() && !s.finished[i] && !s.expired[i] {
s.expired[i] = true;
s.stuck += 1;
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
}
}
}
}
/// Runs `job` inside a panic boundary, with the launch marker naming its item while it runs.
fn run_job<T>(job: Job<T>) -> Result<T> {
let token = job.item.as_ref().map(safe_mode::loading);
let result = catch_unwind(AssertUnwindSafe(job.work));
if let Some(t) = token {
safe_mode::loaded(t);
}
match result {
Ok(r) => r,
Err(panic) => {
let what = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());
Err(match what {
Some(what) => Error::Failed(format!("panicked while loading: {what}")),
None => Error::Failed("panicked while loading".into()),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicU64;
use std::sync::mpsc::sync_channel;
/// A clock the test moves.
fn manual() -> (Arc<AtomicU64>, Clock) {
let ms = Arc::new(AtomicU64::new(0));
let read = ms.clone();
(ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst))))
}
/// A job that says it started on `started`, then waits for `go` and returns `v`.
fn held(v: u32, started: mpsc::SyncSender<u32>, go: Receiver<()>) -> Job<u32> {
Job::new(None, move || {
let _ = started.send(v);
let _ = go.recv();
Ok(v)
})
}
/// Polls `loads` until `done` says so, at most a million times.
fn poll_until(loads: &mut Loads<u32>, mut done: impl FnMut(&mut Loads<u32>) -> bool) -> bool {
(0..1_000_000).any(|_| {
std::thread::yield_now();
loads.poll();
done(loads)
})
}
/// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the
/// test instead of holding it. The test fails at once when every sender is gone.
fn recv_soon<V>(rx: &Receiver<V>) -> V {
for _ in 0..100_000_000 {
match rx.try_recv() {
Ok(v) => return v,
Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"),
Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(),
}
}
panic!("nothing was received");
}
/// The outcomes come back in the order of the jobs when they finish in the reverse order.
#[test]
fn outcomes_keep_the_order_of_the_jobs() {
let (started, starts) = sync_channel(3);
let mut go = Vec::new();
let mut jobs = Vec::new();
for v in 0..3 {
let (tx, rx) = mpsc::channel();
go.push(tx);
jobs.push(held(v, started.clone(), rx));
}
let (_, clock) = manual();
let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock);
// Bound after `loads`, so a failing assertion drops the senders first: the held jobs then
// return, and dropping `loads` does not wait on them while the test clock stands still.
let release = go;
for _ in 0..3 {
recv_soon(&starts);
}
// Each job is let go only once the one after it has finished.
let mut finished = Vec::new();
for v in (0..3).rev() {
release[v].send(()).unwrap();
let done = recv_soon(&loads.results.lock().unwrap());
finished.push(done.0);
loads.record(done);
}
assert_eq!(finished, vec![2, 1, 0], "they finished in reverse");
assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1, 2]);
}
/// A job that panics fails with the panic's message, and the others load.
#[test]
fn a_job_that_panics_fails_alone() {
let jobs: Vec<Job<u32>> = vec![Job::new(None, || Ok(1)), Job::new(None, || panic!("broken module")), Job::new(None, || Ok(3))];
let (_, clock) = manual();
let out = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
assert_eq!(out[0], Ok(1));
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("panicked") && m.contains("broken module")), "{:?}", out[1]);
assert_eq!(out[2], Ok(3));
}
/// With one worker, a job that never finishes fails at its deadline, and the job after it
/// still loads, on the worker that takes its place.
#[test]
fn a_job_that_hangs_fails_at_its_deadline_and_the_rest_load() {
let (started, starts) = sync_channel(2);
let (go, held_until) = mpsc::channel();
let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
assert_eq!(recv_soon(&starts), 0);
assert!(!loads.poll(), "the first job is still running and the second waits for a worker");
ms.store(10_000, Ordering::SeqCst);
let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some));
go.send(()).unwrap();
assert!(done, "the job after the one that hangs never got its outcome");
let out = loads.wait();
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
assert_eq!(out[1], Ok(1));
}
/// Workers that replace stuck ones stop at twice the workers started: with one worker and two
/// jobs that never finish, the third job fails instead of a third thread taking it.
#[test]
fn replacements_stop_at_twice_the_workers() {
let (started, starts) = sync_channel(3);
let (go0, held0) = mpsc::channel();
let (go1, held1) = mpsc::channel();
let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
assert_eq!(recv_soon(&starts), 0);
ms.store(10_000, Ordering::SeqCst);
loads.poll();
assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one");
ms.store(20_000, Ordering::SeqCst);
let done = loads.poll();
go0.send(()).unwrap();
go1.send(()).unwrap();
assert!(done, "every job has its outcome");
let out = loads.wait();
assert!(matches!(&out[2], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[2]);
}
/// A job that finished but took longer than the deadline fails, however soon it is looked at.
#[test]
fn a_job_that_took_too_long_fails_when_it_is_taken() {
let (ms, clock) = manual();
let moved = ms.clone();
let jobs = vec![Job::new(None, move || {
moved.store(10_000, Ordering::SeqCst);
Ok(1u32)
})];
let out = Loads::start_with(jobs, 1, Duration::from_secs(10), clock).wait();
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
}
/// Only twice the workers' count of jobs past the last outcome taken start: the next one waits
/// until an outcome is taken.
#[test]
fn jobs_past_the_window_wait_until_outcomes_are_taken() {
let ran = Arc::new(AtomicUsize::new(0));
let jobs: Vec<Job<u32>> = (0..5)
.map(|v| {
let ran = ran.clone();
Job::new(None, move || {
ran.fetch_add(1, Ordering::SeqCst);
Ok(v)
})
})
.collect();
let (_, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
let early = ran.load(Ordering::SeqCst);
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
assert_eq!(early, 2, "the third job waited for the first outcomes to be taken");
assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released");
assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes");
loads.release(2);
assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]);
}
/// `wait` after outcomes were taken and not released still gets the rest: it counts the outcomes
/// taken as released, so the job past the window starts.
#[test]
fn wait_after_outcomes_were_taken_gets_the_jobs_past_the_window() {
let jobs: Vec<Job<u32>> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect();
let (_, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
let (done, rest) = mpsc::channel();
std::thread::spawn(move || {
let _ = done.send(loads.wait());
});
assert_eq!(recv_soon(&rest), vec![Ok(2)]);
}
/// When no worker can take the jobs left, because the only one is stuck past its deadline and
/// no thread takes its place, those jobs fail instead of being waited for.
#[test]
fn jobs_no_worker_can_take_fail() {
let (started, starts) = sync_channel(1);
let (go, held_until) = mpsc::channel();
let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))];
let (ms, clock) = manual();
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
recv_soon(&starts);
loads.refuse_threads = true;
ms.store(10_000, Ordering::SeqCst);
let done = loads.poll();
go.send(()).unwrap();
assert!(done, "every job has its outcome");
let out = loads.wait();
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[1]);
}
/// A thread stuck past its deadline counts against later loads until its job returns: with
/// room for one stuck thread in the process, the load after one that left a thread stuck
/// starts no thread and fails its job, and once the stuck job returns a load runs again.
#[test]
fn stuck_threads_count_across_loads_until_they_end() {
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
let make = |jobs: Vec<Job<u32>>, clock: Clock| {
let mut loads = Loads::with(jobs, 1, Duration::from_secs(10), clock);
loads.stuck_threads = stuck;
loads.max_stuck = 1;
loads.begin();
loads
};
let (started, starts) = sync_channel(1);
let (go, held_until) = mpsc::channel();
let (ms, clock) = manual();
let mut first = make(vec![held(0, started, held_until)], clock);
recv_soon(&starts);
ms.store(10_000, Ordering::SeqCst);
assert!(first.poll(), "the stuck job failed at its deadline");
drop(first);
let (_, clock) = manual();
let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait();
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]);
go.send(()).unwrap();
assert!((0..1_000_000).any(|_| {
std::thread::yield_now();
stuck.load(Ordering::SeqCst) == 0
}));
assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]);
}
/// A load dropped while a job runs past its deadline, before anything looked at the job, still
/// counts the job's thread as stuck until the job returns.
#[test]
fn a_dropped_load_counts_a_job_past_its_deadline_as_stuck() {
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
let (started, starts) = sync_channel(1);
let (go, held_until) = mpsc::channel();
let (ms, clock) = manual();
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
loads.stuck_threads = stuck;
loads.begin();
recv_soon(&starts);
ms.store(10_000, Ordering::SeqCst);
drop(loads);
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
go.send(()).unwrap();
assert!((0..1_000_000).any(|_| {
std::thread::yield_now();
stuck.load(Ordering::SeqCst) == 0
}));
}
/// The launch marker names an item while its job runs, and stops naming it when the job
/// returns, a job that panicked included.
#[test]
fn a_job_names_its_item_until_it_returns_even_when_it_panics() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let ok = Item::file("test-loader-ok.wasm");
let bad = Item::file("test-loader-panics.wasm");
let named = |item: &Item| crate::safe_mode::still_loading().iter().any(|i| i.same(item));
let (ok2, bad2) = (ok.clone(), bad.clone());
let bad_named = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen = bad_named.clone();
let jobs: Vec<Job<bool>> = vec![
Job::new(Some(ok.clone()), move || Ok(named(&ok2))),
Job::new(Some(bad.clone()), move || {
seen.store(named(&bad2), Ordering::SeqCst);
panic!("x")
}),
];
let (_, clock) = manual();
let outcomes = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
assert!(matches!(outcomes.first(), Some(Ok(true))), "named while it runs");
assert!(bad_named.load(Ordering::SeqCst), "named while it runs, before it panics");
assert!(matches!(outcomes.get(1), Some(Err(Error::Failed(m))) if m.contains("panicked while loading")), "the panic is the job's failure");
let running = crate::safe_mode::still_loading();
assert!(!running.iter().any(|i| i.same(&bad) || i.same(&ok)), "{running:?}");
}
}
+323 -11
View File
@@ -5,11 +5,14 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::dialog::ParamUi;
use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission};
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission};
use crate::{Error, Result};
/// Longest manifest the host reads.
pub const MAX_MANIFEST_BYTES: usize = 64 * 1024;
/// The name of the custom section a module may carry its manifest in, so the host reads it
/// without running any of the module's code.
pub const MANIFEST_SECTION: &str = "vc_manifest";
/// Most parameters a plug-in may declare.
pub const MAX_PARAMS: usize = 256;
/// Most parameters outside groups (`group`): a dialog of more is sorted into sections.
@@ -31,6 +34,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256;
/// Longest command id a manifest's `commandAllowlist` names, in bytes.
pub const MAX_ALLOWED_ID: usize = 128;
/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window,
/// Help and the application menu are not among them, and neither are the submenus that list
/// files, fonts, panels or other plug-ins.
pub const MENU_PLACES: &[&[&str]] = &[
&["Edit"],
&["Edit", "Edit Colors"],
&["Object"],
&["Object", "Transform"],
&["Object", "Arrange"],
&["Object", "Path"],
&["Object", "Compound Path"],
&["Object", "Clipping Mask"],
&["Type"],
&["Select"],
&["Select", "Same"],
&["Select", "Object"],
&["Effect"],
&["View"],
];
/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the
/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when
/// `after` is left out or names no built-in item there.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MenuPlace {
pub path: &'static [&'static str],
#[serde(skip_serializing_if = "Option::is_none")]
pub after: Option<String>,
}
impl MenuPlace {
/// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`.
fn read(v: &Value) -> std::result::Result<MenuPlace, String> {
let wrong_path = || {
let k = "menu.path";
let places: Vec<String> =
MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::<Vec<_>>().join(", "))).collect();
format!("`{k}` must be one of {}", places.join(", "))
};
let Some(o) = v.as_object() else {
let key = "menu";
return Err(format!("`{key}` must be an object"));
};
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after"));
}
let path: Vec<&str> = match o.get("path").and_then(Value::as_array) {
Some(path) => path.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(wrong_path)?,
None => return Err(wrong_path()),
};
let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?;
let key = "menu.after";
let after = match o.get("after") {
None => None,
Some(Value::String(s)) => {
let trimmed = s.trim();
if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) {
return Err(format!("`{key}` must be 1-64 printable characters"));
}
Some(trimmed.to_string())
}
Some(_) => return Err(format!("`{key}` must be a string")),
};
Ok(MenuPlace { path, after })
}
}
/// What a plug-in is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -93,6 +164,45 @@ impl InputKind {
}
}
/// A part of the active document a filter or a plug-in command asks to be given in
/// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3):
/// plain values to read, never objects.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ContextSection {
/// The document's name (never its path), color mode, units, the active artboard's size, the
/// bleed and the raster effects resolution.
Settings,
/// Every artboard's id, name and rectangle, and which one is active.
Artboards,
/// Every layer and sublayer: name, visibility, lock, nesting, and which one is current.
Layers,
/// Every swatch, as `swatch.list` lists it.
Swatches,
}
impl ContextSection {
/// Every section, in the order the docs list them.
pub const ALL: [ContextSection; 4] = [ContextSection::Settings, ContextSection::Artboards, ContextSection::Layers, ContextSection::Swatches];
/// Its name in `context`, which is also its key in `_context.document`.
pub fn name(self) -> &'static str {
match self {
ContextSection::Settings => "settings",
ContextSection::Artboards => "artboards",
ContextSection::Layers => "layers",
ContextSection::Swatches => "swatches",
}
}
/// The section named `name`.
pub fn parse(name: &str) -> Option<ContextSection> {
ContextSection::ALL.into_iter().find(|s| s.name() == name)
}
}
/// The error of a `context` that is not a list of distinct section names.
const CONTEXT_LIST: &str = "`context` must list distinct sections: settings, artboards, layers or swatches";
/// How much one run of a plug-in may compute.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -220,9 +330,9 @@ pub struct Param {
}
/// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the
/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command
/// `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with `_context.command` set to
/// `id` and the parameters it declares.
/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it
/// as the command `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with
/// `_context.command` set to `id` and the parameters it declares.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Command {
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
@@ -233,6 +343,13 @@ pub struct Command {
/// Parameters in declaration (dialog) order, declared as the manifest's own are.
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
pub params: Vec<(String, Param)>,
/// The menu it is listed in instead of the plug-in's submenu (`menu`, read at
/// [`crate::permissions::MENU_API`] and later).
#[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")]
pub place: Option<MenuPlace>,
/// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them.
#[serde(skip)]
pub(crate) declared_menu: Vec<Value>,
}
impl Command {
@@ -241,6 +358,18 @@ impl Command {
pub fn shown_label(&self) -> String {
crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME)
}
/// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a
/// command placed in another menu, followed by the plug-in's name in parentheses.
pub fn menu_label(&self, plugin_name: &str) -> String {
match self.place {
None => self.shown_label(),
Some(_) => {
let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME);
format!("{} ({name})", self.shown_label())
}
}
}
}
impl From<ParamSpec> for Param {
@@ -299,7 +428,8 @@ impl ParamSpec {
}
}
/// The manifest a plug-in returns from `vc_manifest` (UTF-8 JSON).
/// The manifest a plug-in carries in its [`MANIFEST_SECTION`] custom section or returns from
/// `vc_manifest` (UTF-8 JSON).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
@@ -326,6 +456,12 @@ pub struct Manifest {
/// lists them. Left out or empty, it is given paths and compound paths alone.
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
pub inputs: Vec<String>,
/// The parts of the document a run is given in `_context.document`, by
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
/// a run is given none.
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "context_names")]
pub context: Vec<String>,
/// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest.
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
pub params: Vec<(String, Param)>,
@@ -365,8 +501,9 @@ impl Manifest {
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
return Err(Error::Manifest("`paintOutput` may only be true".into()));
}
let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
man.validate()?;
man.read_places()?;
Ok(man)
}
@@ -382,6 +519,7 @@ impl Manifest {
api: 1,
permissions: None,
inputs: Vec::new(),
context: Vec::new(),
params: Vec::new(),
extensions: Vec::new(),
place: false,
@@ -403,6 +541,31 @@ impl Manifest {
self.commands.iter().find(|c| c.id == id)
}
/// Reads each command's `menu` into its [`Command::place`] at
/// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is
/// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given
/// twice is refused, and the error names the command.
fn read_places(&mut self) -> Result<()> {
let reads = self.api >= permissions::MENU_API;
for (i, c) in self.commands.iter_mut().enumerate() {
let menus = std::mem::take(&mut c.declared_menu);
if !reads {
continue;
}
let name = command_name(i, &c.id);
let place = match menus.as_slice() {
[] => continue,
[menu] => MenuPlace::read(menu),
_ => {
let key = "menu";
Err(format!("duplicate field `{key}`"))
}
};
c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?);
}
Ok(())
}
/// Checks what the module declared: its id, name and text lengths, its extensions, a budget its
/// kind may have (only a filter may be heavy), and each parameter and its dialog layout.
fn validate(&self) -> Result<()> {
@@ -428,6 +591,7 @@ impl Manifest {
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
}
self.validate_inputs()?;
self.validate_context()?;
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
}
@@ -527,6 +691,33 @@ impl Manifest {
Ok(())
}
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
fn validate_context(&self) -> Result<()> {
if self.context.is_empty() {
return Ok(());
}
for (i, name) in self.context.iter().enumerate() {
if ContextSection::parse(name).is_none() || self.context.get(..i).is_some_and(|before| before.contains(name)) {
return Err(Error::Manifest(CONTEXT_LIST.into()));
}
}
let runs = self.kind == Kind::Filter || (self.kind == Kind::Effect && !self.commands.is_empty());
let reads = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::DocRead.name()));
if !runs || self.api < CONTEXT_API || !reads {
return Err(Error::Manifest(
"`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`".into(),
));
}
Ok(())
}
/// The parts of the document it asks to be given (`context`).
pub fn context_sections(&self) -> Vec<ContextSection> {
self.context.iter().filter_map(|n| ContextSection::parse(n)).collect()
}
/// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct
/// id, a printable label and parameters declared as the manifest's own are. A heavy filter
/// lists none. The error names the command: its id, or its place in the list.
@@ -742,6 +933,18 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
}
}
/// Reads `context`: a list of names (`null`: none). Anything else is the error
/// [`Manifest::validate_context`] gives a wrong entry.
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
match Value::deserialize(d)? {
Value::Null => Ok(Vec::new()),
Value::Array(names) => {
names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(serde::de::Error::custom(CONTEXT_LIST)) }).collect()
}
_ => Err(serde::de::Error::custom(CONTEXT_LIST)),
}
}
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
@@ -814,7 +1017,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
Err(A::Error::custom(self.wrong()))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
let (mut id, mut label, mut params, mut menu) = (None::<String>, None::<String>, None::<Params>, Vec::<Value>::new());
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
};
@@ -833,6 +1036,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
params = Some(map.next_value().map_err(|e| named(&id, &e))?);
false
}
// A repeated `menu` is refused only where the key is read ([`Manifest::parse`]).
"menu" => {
menu.push(map.next_value().map_err(|e| named(&id, &e))?);
false
}
"id" | "label" | "params" => true,
_ => {
map.next_value::<IgnoredAny>()?;
@@ -849,7 +1057,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
let Some(label) = label else {
return Err(named(&Some(id), &"missing field `label`"));
};
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() })
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu })
}
}
@@ -1155,7 +1363,7 @@ mod tests {
(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","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"),
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` 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":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"),
(r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"),
(r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"),
] {
@@ -1211,6 +1419,51 @@ mod tests {
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
}
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
/// refused naming `context`.
#[test]
fn a_level_3_plugin_lists_the_document_context_it_reads() {
let m = Manifest::parse(
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["settings","artboards","layers","swatches"]}"#,
)
.unwrap();
assert_eq!(m.context_sections(), ContextSection::ALL);
assert!(m.asks_permissions());
assert_eq!(serde_json::to_value(&m).unwrap()["context"], json!(["settings", "artboards", "layers", "swatches"]));
let effect = br#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"],"commands":[{"id":"c","label":"C"}]}"#;
assert_eq!(Manifest::parse(effect).unwrap().context_sections(), [ContextSection::Layers]);
for none in [r#"{"id":"a","name":"x","kind":"filter","context":[]}"#, r#"{"id":"a","name":"x","kind":"filter","api":3,"context":null}"#] {
let m = Manifest::parse(none.as_bytes()).unwrap();
assert!(m.context_sections().is_empty(), "{none}");
assert!(serde_json::to_value(&m).unwrap().get("context").is_none(), "{none}");
}
let list = "`context` must list distinct sections";
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
for (bad, says) in [
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["paths"]}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["Layers"]}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["layers","layers"]}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":"layers"}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":[1]}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":{"layers":true}}"#, list),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}"#, needs),
(r#"{"id":"a","name":"x","kind":"filter","permissions":["doc.read"],"context":["layers"]}"#, needs),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"context":["layers"]}"#, needs),
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}"#, needs),
(r#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"]}"#, needs),
(
r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"api":3,"permissions":["doc.read","export.write"],"context":["layers"]}"#,
needs,
),
(r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"api":3,"permissions":["import.read"],"context":["layers"]}"#, needs),
] {
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
/// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other
/// kind or level, and `false`, `null` or another type, is refused naming the key. Without the
/// key, at any level, the effect returns geometry only.
@@ -1252,7 +1505,7 @@ mod tests {
}
/// A filter or a live effect lists menu commands with their own parameters; a `menu` key is
/// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many
/// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many
/// commands are refused, and the error names the command.
#[test]
fn commands_are_checked_and_errors_name_them() {
@@ -1274,7 +1527,7 @@ mod tests {
assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none());
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap();
assert_eq!(effect.commands.len(), 1);
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label();
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label();
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
@@ -1330,6 +1583,65 @@ mod tests {
assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped");
}
/// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or
/// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the
/// wrong shape is refused and the error names the command. At level 1 the key is ignored.
#[test]
fn a_command_menu_names_an_allowed_place() {
let with = |api: u32, menu: &str| {
format!(
r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"#
)
};
let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap();
let c = &m.commands[0];
assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) }));
assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in");
assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"}));
let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap();
assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None }));
// API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu.
for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] {
let old = Manifest::parse(with(1, menu).as_bytes()).unwrap();
assert_eq!(old.commands[0].place, None, "{menu}");
assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths");
}
let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65));
let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64));
for (menu, says) in [
(r#"{"path":["File"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Help"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Window"]}"#, "`menu.path` must be one of"),
(r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"),
(r#"{"path":["select"]}"#, "`menu.path` must be one of"),
(r#"{"path":[]}"#, "`menu.path` must be one of"),
(r#"{"path":"Select"}"#, "`menu.path` must be one of"),
(r#"{"path":["Select",1]}"#, "`menu.path` must be one of"),
(r#"{"after":"Inverse"}"#, "`menu.path` must be one of"),
(r#""Select""#, "`menu` must be an object"),
(r#"["Select"]"#, "`menu` must be an object"),
(r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"),
(r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"),
(r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"),
(r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"),
(long.as_str(), "`menu.after` must be 1-64 printable characters"),
(padded.as_str(), "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"),
] {
let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string();
assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}");
}
let twice =
r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#;
assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`"));
}
#[test]
fn strings_and_number_lists_resolve_like_the_other_types() {
let m = Manifest::parse(
+29 -1
View File
@@ -1031,12 +1031,40 @@ fn members(doc: &mut Document, old: &[Arc<Node>], path: PathData) -> Vec<Arc<Nod
.collect()
}
/// Whether `returned`, a path from plug-in output, is `current` as it was: output has its empty
/// subpaths dropped, so `current`'s are left out of the comparison.
fn same_geometry(returned: &PathData, current: &PathData) -> bool {
returned.subpaths.iter().eq(current.subpaths.iter().filter(|sp| !sp.anchors.is_empty()))
}
/// Refuses an output that replaces the members of compound path `n` while one of them isn't a path
/// (plug-ins aren't given its geometry), or is hidden, locked or (unless the output sets `guide`) a
/// guide.
fn check_members_replaceable(n: &Node, children: &[Arc<Node>], sets_guide: bool, at: &str) -> Result<()> {
let id = n.id.0;
if children.iter().any(|c| c.path_data().is_none()) {
return Err(out_err(at, format!("compound path {id} has a member that isn't a path, so its members can't be replaced")));
}
if children.iter().any(|c| !c.visible || c.locked || (!sets_guide && is_guide(c))) {
return Err(out_err(at, format!("compound path {id} has a hidden, locked or guide member, so its members can't be replaced")));
}
Ok(())
}
/// Writes `o` into `n` (an input object, or a fresh node for a new one); its effect records once
/// `admit` lets them in.
fn write(doc: &mut Document, n: &mut Node, o: OutObject, at: &str, admit: AdmitEffects) -> Result<()> {
let (cur_path, cur_rule, cur_compound) = geometry(n).unwrap_or((PathData::default(), FillRule::NonZero, false));
let compound = o.compound.unwrap_or(cur_compound);
let rule = o.rule.unwrap_or(cur_rule);
// A compound path handed back with its path as it was keeps its members as they are.
let same_members = cur_compound && o.path.as_ref().is_none_or(|p| same_geometry(p, &cur_path));
if let NodeKind::Compound { children, .. } = &n.kind
&& (!same_members || !compound)
{
let at = if compound { format!("{at}.path") } else { format!("{at}.type") };
check_members_replaceable(n, children, o.guide.is_some(), &at)?;
}
match (&mut n.kind, compound) {
(NodeKind::Path { path, rule: r, live, .. }, false) => {
// A path handed back as it was stays the live shape it was.
@@ -1047,7 +1075,7 @@ fn write(doc: &mut Document, n: &mut Node, o: OutObject, at: &str, admit: AdmitE
*r = rule;
}
(NodeKind::Compound { children, rule: r }, true) => {
if let Some(p) = o.path {
if let Some(p) = o.path.filter(|_| !same_members) {
*children = members(doc, children, p);
}
*r = rule;
+12 -3
View File
@@ -15,8 +15,8 @@ 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. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
/// ([`crate::painted`]).
pub const API_LEVEL: u32 = 2;
/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]).
pub const API_LEVEL: u32 = 3;
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
/// `settings`, `cache` and `commands` permissions they need.
@@ -25,6 +25,14 @@ pub const PROGRESS_API: u32 = 2;
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
pub const INPUTS_API: u32 = 2;
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
/// is ignored.
pub const MENU_API: u32 = 2;
/// The API level that adds a manifest's `context` ([`crate::ContextSection`]): the document's
/// settings, artboards, layers and swatches, given to a run with or without a selection.
pub const CONTEXT_API: u32 = 3;
/// Most permissions a manifest may list.
pub const MAX_PERMISSIONS: usize = 16;
@@ -42,7 +50,8 @@ pub const RESERVED: &[&str] = &["ui.panel", "ui.tool"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Permission {
/// Read the objects the host hands it: a filter's selected paths, the object a live effect is
/// on, the document an exporter writes.
/// on, the document an exporter writes; and the document information a manifest's `context`
/// asks for ([`crate::ContextSection`]).
#[serde(rename = "doc.read")]
DocRead,
/// Change, add and delete objects (a filter's output), as one undo step.
+632 -47
View File
@@ -68,7 +68,7 @@ pub fn approved(plugin: &Plugin) -> bool {
/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists
/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and
/// the plug-in installed under its id, the grants and the revision stay as they were.
pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
pub fn install(plugin: Plugin) -> Result<Arc<Plugin>> {
// The revision moves while the write lock is held, so a cache that reads the new revision and
// then the plug-ins finds the new plug-in among them. The approval is checked while it is held
// too.
@@ -76,12 +76,112 @@ pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
if !approved(&plugin) {
return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", ")));
}
Ok(insert(&mut plugins, plugin))
}
/// Installs `plugin` in `plugins`, which the plug-ins' write lock holds, with the next revision.
fn insert(plugins: &mut BTreeMap<String, Arc<Plugin>>, mut plugin: Plugin) -> Arc<Plugin> {
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
note_change(plugin.id(), plugin.serial());
let p = Arc::new(plugin);
plugins.insert(p.id().to_string(), p.clone());
Ok(p)
p
}
/// [`install`] for a load that installs plug-ins one by one, recording `grant` first when it is
/// given: while the plug-ins' write lock is held, a plug-in whose id was installed or removed
/// elsewhere since the load started ([`LoadChanges::superseded`]) is not installed (`Ok(None)`), and
/// neither the plug-ins nor the grants change. A grant that doesn't give this very module every
/// permission it lists is refused ([`Error::NeedsApproval`]) and not recorded. Otherwise `attach`
/// runs, then the grant is recorded and the plug-in installed. `attach` runs while the plug-ins are
/// held, so it may call [`set_storage`] but no function that reads or changes the plug-ins or grants.
pub fn install_for_load(plugin: Plugin, changes: &LoadChanges, grant: Option<GrantToken>, attach: impl FnOnce()) -> Result<Option<Arc<Plugin>>> {
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
if changes.superseded(plugin.id()) {
return Ok(None);
}
let m = plugin.manifest();
let approved = match &grant {
Some(token) => !m.asks_permissions() || token.grant().covers(&m.id, plugin.hash(), &m.permissions()),
None => approved(&plugin),
};
if !approved {
return Err(Error::NeedsApproval(crate::permissions::names(&m.permissions()).join(", ")));
}
attach();
if let Some(token) = grant {
let g = token.grant().clone();
GRANTS.write().unwrap_or_else(|e| e.into_inner()).insert(g.id.clone(), g);
}
Ok(Some(insert(&mut plugins, plugin)))
}
/// Forgets the grant for `id` when the plug-in installed under it is the one that took the revision
/// `serial` ([`Plugin::serial`]), checked while the plug-ins are held, so a plug-in installed in its
/// place meanwhile keeps the grant recorded for it → whether a grant was forgotten.
pub fn revoke_if_installed(id: &str, serial: u64) -> bool {
// The same order as `install`, which reads the grants while it holds the plug-ins.
let plugins = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
plugins.get(id).is_some_and(|p| p.serial() == serial) && GRANTS.write().unwrap_or_else(|e| e.into_inner()).remove(id).is_some()
}
/// The [`revision`] of each id's last install or removal ([`changed_since`]).
static CHANGED: RwLock<BTreeMap<String, u64>> = RwLock::new(BTreeMap::new());
/// Records that `id` was installed or removed at revision `rev`; called while the plug-ins' write
/// lock is held.
fn note_change(id: &str, rev: u64) {
CHANGED.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), rev);
}
/// Whether plug-in `id` was installed or removed after [`revision`] gave `rev`.
pub fn changed_since(id: &str, rev: u64) -> bool {
CHANGED.read().unwrap_or_else(|e| e.into_inner()).get(id).is_some_and(|&r| r > rev)
}
/// What a load that installs plug-ins one by one has to check, so that a module it loaded before
/// another session installed or removed the same id doesn't undo that change: the [`revision`] when
/// the load listed its files, and the revision of each id it, or a load of the same session that
/// ended before it, installed.
#[derive(Debug, Default)]
pub struct LoadChanges {
since: Option<u64>,
own: BTreeMap<String, u64>,
}
impl LoadChanges {
/// Marks the load as started now, unless it started already. A load calls it as it lists its
/// files, so a change made between the listing and the loads counts as one made elsewhere.
pub fn start(&mut self) {
self.since.get_or_insert_with(revision);
}
/// Whether `id` was installed or removed since the load started, other than by the load itself
/// or a load it [adopted](LoadChanges::adopt).
pub fn superseded(&self, id: &str) -> bool {
self.since.is_some_and(|since| changed_since(id, since.max(self.own.get(id).copied().unwrap_or(0))))
}
/// Records that the load installed `plugin`.
pub fn installed(&mut self, plugin: &Plugin) {
self.own.insert(plugin.id().to_string(), plugin.serial());
}
/// Counts what `earlier`, a load of the same session queued before this one that has ended,
/// installed as this load's own: a module this load installs after it then replaces it, as it
/// would have with the loads run one after the other.
pub fn adopt(&mut self, earlier: &LoadChanges) {
for (id, &serial) in &earlier.own {
let own = self.own.entry(id.clone()).or_default();
*own = (*own).max(serial);
}
}
}
/// What a load reports for a module it skips because the plug-in under its id was installed or
/// removed elsewhere while it loaded ([`LoadChanges`]).
pub const SUPERSEDED: &str = "skipped: the plug-in with its id was installed or removed elsewhere while it loaded";
/// What [`install_checked`] does to the grant recorded for the plug-in's id.
pub enum GrantUpdate {
/// Records this grant, replacing an earlier one for the id ([`grant`]).
@@ -128,6 +228,7 @@ pub fn install_checked<E>(
}
}
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
note_change(&id, plugin.serial());
let p = Arc::new(plugin);
plugins.insert(id, p.clone());
Ok(p)
@@ -154,7 +255,7 @@ pub fn remove(id: &str) -> bool {
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
let gone = plugins.remove(id).is_some();
if gone {
REVISION.fetch_add(1, Ordering::Relaxed);
note_change(id, REVISION.fetch_add(1, Ordering::Relaxed) + 1);
}
gone
}
@@ -267,14 +368,19 @@ pub struct FolderReport {
/// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app
/// saves the list again.
pub disabled_changed: bool,
/// A file failed because no loader thread was left to load it ([`crate::loader::NO_THREAD`]):
/// loading the folder again may load it.
pub no_thread: bool,
}
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one
/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists
/// permissions the user has not granted this very module ([`approved`]).
/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name
/// order. A bad module is reported and skipped, the others still load; so is one whose load panics
/// or doesn't finish in time ([`crate::loader`]), a heavy one ([`crate::Budget::Heavy`]), which
/// installs only once the user agrees, and one that lists permissions the user has not granted this
/// very module ([`approved`]).
#[cfg(not(target_arch = "wasm32"))]
pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
load_folder_where(dir, |_| Ok(()), approved)
@@ -291,54 +397,255 @@ pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
#[cfg(not(target_arch = "wasm32"))]
pub fn load_folder_where(
dir: &std::path::Path,
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String>,
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
approve: impl Fn(&Plugin) -> bool,
) -> Result<FolderReport> {
use crate::safe_mode::{self, Item};
safe_mode::check()?;
let (files, left_out) = folder_files(dir)?;
let mut report = FolderReport { left_out, ..FolderReport::default() };
for f in files {
if let Err(why) = allow(&f) {
report.failed.push((f.display().to_string(), why));
continue;
let mut load = FolderLoad::begin(dir, allow)?;
while !load.done() {
load.wait();
load.install_ready(&approve);
}
Ok(load.finish())
}
/// Tests: what runs before a folder module loads, given its path.
#[cfg(all(test, not(target_arch = "wasm32")))]
type FileHook = std::sync::Arc<dyn Fn(&std::path::Path) + Send + Sync>;
/// Tests: runs on the worker thread before the module at the path it is given loads.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) static BEFORE_FOLDER_FILE: Mutex<Option<FileHook>> = Mutex::new(None);
/// A [`load_folder_where`] whose modules load on worker threads ([`crate::loader`]) while the
/// caller goes on: [`FolderLoad::begin`] lists the folder and starts the loads,
/// [`FolderLoad::install_ready`] installs what loaded so far in file-name order, whatever order the
/// loads finish in, and [`FolderLoad::finish`] ends the load once [`FolderLoad::done`]. A module
/// whose load panics or doesn't finish in time is reported as failed, and the others still install.
#[cfg(not(target_arch = "wasm32"))]
pub struct FolderLoad {
/// Each file in file-name order, with why it was refused before loading, if it was.
files: Vec<(std::path::PathBuf, Option<String>)>,
loads: crate::loader::Loads<Plugin>,
/// Outcomes taken from `loads` and not installed yet, in order.
loaded: std::collections::VecDeque<Result<Plugin>>,
/// The next file to install or report.
next: usize,
report: FolderReport,
/// Installs and removals elsewhere since the folder was listed, which a module loaded before
/// them doesn't undo.
changes: LoadChanges,
}
#[cfg(not(target_arch = "wasm32"))]
impl FolderLoad {
/// Lists `dir` and starts loading the files `allow` accepts and the user didn't disable. Each
/// file is checked with `allow` again on its worker thread, right before it is read. In Safe
/// Mode nothing loads ([`Error::SafeMode`]); an error listing the folder is returned.
pub fn begin(
dir: &std::path::Path,
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
) -> Result<FolderLoad> {
let mut load = Self::list_on(dir, allow, None)?;
load.start();
Ok(load)
}
/// [`FolderLoad::begin`] without starting the loads: [`FolderLoad::start`] starts them, and
/// so does waiting for them.
pub fn list(
dir: &std::path::Path,
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
) -> Result<FolderLoad> {
Self::list_on(dir, allow, None)
}
/// Starts the loads, unless they started already.
pub fn start(&mut self) {
self.changes.start();
self.loads.begin();
}
/// [`FolderLoad::list`] for `workers` threads (`None`: as many as [`crate::loader::Loads::start`]
/// starts).
fn list_on(
dir: &std::path::Path,
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
workers: Option<usize>,
) -> Result<FolderLoad> {
use crate::loader::{Job, Loads};
use crate::safe_mode::{self, Item};
safe_mode::check()?;
// A change made elsewhere once the folder starts being listed is one the load doesn't undo.
let mut changes = LoadChanges::default();
changes.start();
let (found, left_out) = folder_files(dir)?;
let allow = std::sync::Arc::new(allow);
let mut files = Vec::with_capacity(found.len());
let mut jobs = Vec::new();
for f in found {
let item = Item::file(f.display().to_string());
let refused = match allow(&f) {
Err(why) => Some(why),
Ok(()) if safe_mode::skipped(&item) => Some(DISABLED.to_string()),
Ok(()) => None,
};
if refused.is_none() {
let (path, allow) = (f.clone(), allow.clone());
jobs.push(Job::new(Some(item), move || {
allow(&path).map_err(Error::Io)?;
#[cfg(test)]
{
let hook = BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(hook) = hook {
hook(&path);
}
}
load_file(&path, Limits::default())
}));
}
files.push((f, refused));
}
let item = Item::file(f.display().to_string());
if safe_mode::skipped(&item) {
report.failed.push((f.display().to_string(), DISABLED.into()));
continue;
}
let token = safe_mode::loading(&item);
let loaded = load_file(&f, Limits::default());
safe_mode::loaded(token);
match loaded {
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
report.failed.push((f.display().to_string(), DISABLED.into()));
}
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
report.failed.push((f.display().to_string(), "asks for a heavy budget, which the user allows when installing it on its own".into()));
}
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string()));
}
// `approve` only narrows what installs: `install` still refuses a module that no
// recorded grant covers.
Ok(p) => match install(p) {
Ok(p) => report.loaded.push(p.id().to_string()),
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
},
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
let loads = match workers {
Some(n) => Loads::deferred_on(jobs, n),
None => Loads::deferred(jobs),
};
let report = FolderReport { left_out, ..FolderReport::default() };
Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes })
}
/// The installs and removals the load checks its modules against ([`LoadChanges`]).
pub fn changes(&self) -> &LoadChanges {
&self.changes
}
/// [`FolderLoad::changes`], to [adopt](LoadChanges::adopt) an earlier load's.
pub fn changes_mut(&mut self) -> &mut LoadChanges {
&mut self.changes
}
/// Whether every file has been installed or reported.
pub fn done(&self) -> bool {
self.next == self.files.len()
}
/// Whether [`FolderLoad::install_ready`] has something to install or report now, without
/// waiting (or nothing is left).
pub fn ready(&mut self) -> bool {
match self.files.get(self.next) {
None => true,
Some((_, Some(_))) => true,
Some((_, None)) => !self.loaded.is_empty() || self.loads.next_ready(),
}
}
for id in &report.loaded {
if get(id).is_some_and(|p| !p.manifest().asks_permissions()) {
revoke(id);
/// Waits until [`FolderLoad::ready`], starting the loads first ([`FolderLoad::start`]).
pub fn wait(&mut self) {
self.start();
while !self.ready() && !self.loads.taken() {
self.loads.wait_next();
}
}
Ok(report)
/// Installs the plug-ins that loaded, and reports the files that failed, in file-name order up
/// to the first file still loading, as [`load_folder_where`] does: those that list permissions
/// only when `approve` accepts them and a recorded grant covers them → the ids it installed.
pub fn install_ready(&mut self, approve: impl Fn(&Plugin) -> bool) -> Vec<String> {
use crate::safe_mode::{self, Item};
self.loaded.extend(self.loads.ready());
let mut installed = Vec::new();
while let Some((f, refused)) = self.files.get(self.next) {
let name = f.display().to_string();
if let Some(why) = refused {
self.report.failed.push((name, why.clone()));
self.next += 1;
continue;
}
let Some(loaded) = self.loaded.pop_front() else { break };
self.loads.release(1);
self.next += 1;
let report = &mut self.report;
match loaded {
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
report.failed.push((name, DISABLED.into()));
}
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
report.failed.push((name, "asks for a heavy budget, which the user allows when installing it on its own".into()));
}
// The very module installed elsewhere meanwhile (another session loading the same
// folder) counts as loaded. `approve` may record a grant, so it is asked only for
// that module: a module another session replaced or removed changes no grant.
Ok(p) if self.changes.superseded(p.id()) => match get(p.id()) {
Some(q) if q.hash() == p.hash() && (!p.manifest().asks_permissions() || approve(&p)) => report.loaded.push(p.id().to_string()),
Some(q) if q.hash() == p.hash() => {
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
}
_ => report.failed.push((name, SUPERSEDED.into())),
},
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
}
// `approve` only narrows what installs: `install_for_load` still refuses a module that
// no recorded grant covers, and one whose id changed elsewhere since the check above.
Ok(p) => match install_for_load(p, &self.changes, None, || {}) {
Ok(Some(p)) => {
self.changes.installed(&p);
report.loaded.push(p.id().to_string());
installed.push(p.id().to_string());
}
Ok(None) => report.failed.push((name, SUPERSEDED.into())),
Err(e) => report.failed.push((name, e.to_string())),
},
Err(e) => {
report.no_thread |= matches!(&e, Error::Failed(m) if m == crate::loader::NO_THREAD);
report.failed.push((name, e.to_string()));
}
}
}
installed
}
/// Whether [`FolderLoad::install_ready`] turned off the file of a disabled plug-in it matched by
/// id ([`crate::safe_mode::disable_file_of`]) since the list of disabled plug-ins was last saved
/// ([`FolderLoad::disabled_saved`]).
pub fn disabled_changed(&self) -> bool {
self.report.disabled_changed
}
/// The list of disabled plug-ins was saved: [`FolderLoad::disabled_changed`] is false until the
/// load changes it again.
pub fn disabled_saved(&mut self) {
self.report.disabled_changed = false;
}
/// Drops the loads not taken yet: jobs not started don't start, and running ones are given
/// until their deadline ([`crate::loader::Loads`]). What was installed stays, and the load is
/// [`FolderLoad::done`].
pub fn cancel(&mut self) {
self.loads = crate::loader::Loads::deferred(Vec::new());
self.loaded.clear();
self.next = self.files.len();
}
/// Ends the load → its report. When the module the load installed under an id lists no
/// permissions and is still installed, the process's grant for that id is forgotten. Files not
/// installed or reported yet ([`FolderLoad::done`] false) are left out.
pub fn finish(self) -> FolderReport {
let FolderLoad { report, changes, .. } = self;
for id in &report.loaded {
// The serial is checked again while the grant is removed, so a module installed in its
// place meanwhile keeps its grant.
if let Some(&serial) = changes.own.get(id)
&& get(id).is_some_and(|p| p.serial() == serial && !p.manifest().asks_permissions())
{
revoke_if_installed(id, serial);
}
}
report
}
}
#[cfg(test)]
@@ -618,4 +925,282 @@ mod tests {
let first: Vec<String> = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect();
assert_eq!(tried, first, "the first files by name, in that order");
}
/// Clears [`BEFORE_FOLDER_FILE`] when a test ends, failed or not.
#[cfg(not(target_arch = "wasm32"))]
struct Hooked;
#[cfg(not(target_arch = "wasm32"))]
impl Hooked {
fn set(hook: impl Fn(&std::path::Path) + Send + Sync + 'static) -> Hooked {
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(hook));
Hooked
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Hooked {
fn drop(&mut self) {
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
/// The plug-ins of a folder install in file-name order, and take their revisions in that order,
/// when the first file's load finishes after the others.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_installs_in_file_name_order_whatever_order_the_loads_finish_in() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("order");
let ids = ["test.registry.order.a", "test.registry.order.b", "test.registry.order.c"];
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 11)).unwrap();
}
let first = dir.join("a.wasm");
let (go, a_waits) = std::sync::mpsc::channel::<()>();
let a_waits = Mutex::new(a_waits);
let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
let held = first.clone();
let saw = seen.clone();
let _hook = Hooked::set(move |p| {
saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf());
if p == held {
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
}
});
// Two workers, so the other files load while the first one waits.
let loading = std::thread::spawn({
let dir = dir.clone();
move || {
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?;
load.start();
while !load.done() {
load.wait();
load.install_ready(|_| false);
}
Ok::<_, Error>(load.finish())
}
});
// The other two files load on the other worker while the first one waits: their loads have
// started (the hook saw them) and ended (the launch marker list no longer has them).
let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm")));
let finished = |p: &std::path::Path| {
let item = crate::safe_mode::Item::file(p.display().to_string());
seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
};
// Looked at a bounded number of times, and given up when the load ends first.
let reached = (0..10_000_000).any(|_| {
std::thread::yield_now();
loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2]))
});
assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited");
assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
go.send(()).unwrap();
let r = loading.join().unwrap();
std::fs::remove_dir_all(&dir).unwrap();
let r = r.unwrap();
assert_eq!(r.loaded, ids.to_vec(), "{r:?}");
let serials: Vec<u64> = ids.iter().map(|id| get(id).unwrap().serial()).collect();
assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}");
for id in ids {
assert!(remove(id));
}
}
/// A folder module that loaded before something else installed or removed the same id, while
/// an earlier file still loaded, doesn't undo that change: it is reported as skipped, and the
/// plug-in installed meanwhile stays, as does the removal.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_module_doesnt_undo_a_change_made_while_it_waited() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("superseded");
let ids = ["test.registry.superseded.a", "test.registry.superseded.b", "test.registry.superseded.c"];
// b's file asks for a permission: asking whether it may install could record a grant.
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
let asks = (*n == "b").then_some(r#"["doc.read"]"#);
std::fs::write(dir.join(format!("{n}.wasm")), module(id, asks, 13)).unwrap();
}
install_bytes(&module(ids[2], None, 14)).unwrap();
let first = dir.join("a.wasm");
let (go, a_waits) = std::sync::mpsc::channel::<()>();
let a_waits = Mutex::new(a_waits);
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
let held = first.clone();
let _hook = Hooked::set(move |p| {
if p == held {
let _ = reached.send(());
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
}
});
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
load.start();
a_reached.recv().unwrap();
// Elsewhere, while the first file still loads: `b` is installed and `c` removed.
let theirs = install_bytes(&module(ids[1], None, 15)).unwrap().serial();
assert!(remove(ids[2]));
go.send(()).unwrap();
let asked = Mutex::new(Vec::new());
while !load.done() {
load.wait();
load.install_ready(|p| {
asked.lock().unwrap_or_else(|e| e.into_inner()).push(p.id().to_string());
false
});
}
let r = load.finish();
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(r.loaded, vec![ids[0]], "{r:?}");
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 2, "{r:?}");
assert!(asked.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "no grant is asked for a superseded module");
assert_eq!(get(ids[1]).map(|p| p.serial()), Some(theirs), "the plug-in installed meanwhile stays");
assert!(get(ids[2]).is_none(), "the removal stays");
for id in &ids[..2] {
assert!(remove(id));
}
}
/// A plug-in installed elsewhere after the folder was listed and before its loads started
/// stays: the folder's module with its id is skipped. One a load of the same session installed
/// before it ([`LoadChanges::adopt`]) is replaced.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_module_doesnt_undo_a_change_made_before_its_loads_started() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("superseded-listed");
let ids = ["test.registry.listed.a", "test.registry.listed.b"];
for (n, id) in ["a", "b"].iter().zip(ids) {
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 13)).unwrap();
}
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
// Before the loads start: another session installs `a`, and an earlier load of this
// session installs `b`.
let theirs = install_bytes(&module(ids[0], None, 14)).unwrap().serial();
let mut earlier = LoadChanges::default();
earlier.start();
earlier.installed(&install_bytes(&module(ids[1], None, 15)).unwrap());
load.changes_mut().adopt(&earlier);
load.start();
while !load.done() {
load.wait();
load.install_ready(|_| false);
}
let r = load.finish();
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(r.loaded, vec![ids[1]], "{r:?}");
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 1, "{r:?}");
assert_eq!(get(ids[0]).map(|p| p.serial()), Some(theirs), "the plug-in installed elsewhere stays");
for id in ids {
assert!(remove(id));
}
}
/// A folder whose second module panics while it loads reports it as failed and installs the
/// others.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_module_that_panics_while_loading_fails_alone() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("panics");
let ids = ["test.registry.panics.a", "test.registry.panics.b", "test.registry.panics.c"];
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 12)).unwrap();
}
let broken = dir.join("b.wasm");
let hooked = broken.clone();
let hook = Hooked::set(move |p| {
if p == hooked {
panic!("a defect while loading");
}
});
let r = load_folder_where(&dir, |_| Ok(()), |_| false);
drop(hook);
std::fs::remove_dir_all(&dir).unwrap();
let item = crate::safe_mode::Item::file(broken.display().to_string());
let marked = crate::safe_mode::still_loading().iter().any(|i| i.same(&item));
let r = r.unwrap();
assert_eq!(r.loaded, vec![ids[0], ids[2]], "{r:?}");
assert_eq!(r.failed.len(), 1, "{r:?}");
assert!(r.failed[0].0 == broken.display().to_string() && r.failed[0].1.contains("panicked"), "{r:?}");
assert!(!marked, "the launch marker stops naming the module whose load failed");
for id in [ids[0], ids[2]] {
assert!(remove(id));
}
}
/// A folder module isn't installed over a plug-in installed elsewhere with its id while the load
/// asked whether it may install: that plug-in stays, and the module is reported as skipped.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_module_doesnt_replace_one_installed_while_it_was_approved() {
use crate::permissions::Permission::DocRead;
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("approving");
let id = "test.registry.approving";
let asking = module(id, Some(r#"["doc.read"]"#), 17);
std::fs::write(dir.join("a.wasm"), &asking).unwrap();
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
let theirs = std::cell::Cell::new(None);
let r = load_folder_where(
&dir,
|_| Ok(()),
|_| {
theirs.set(Some(install_bytes(&module(id, None, 18)).unwrap().serial()));
true
},
);
std::fs::remove_dir_all(&dir).unwrap();
let now = get(id).map(|p| p.serial());
assert!(remove(id));
revoke(id);
let r = r.unwrap();
assert_eq!(now, theirs.get(), "the plug-in installed meanwhile was replaced: {r:?}");
assert!(r.loaded.is_empty() && r.failed.len() == 1 && r.failed[0].1 == SUPERSEDED, "{r:?}");
}
/// A grant is forgotten only while the plug-in that took the given revision is installed under
/// its id: a plug-in installed in its place keeps the grant recorded for it.
#[test]
fn a_grant_is_revoked_only_for_the_plugin_still_installed() {
use crate::permissions::Permission::DocRead;
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let id = "test.registry.revokeinstalled";
let first = install_bytes(&module(id, None, 19)).unwrap().serial();
let asking = module(id, Some(r#"["doc.read"]"#), 20);
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
let second = install_bytes(&asking).unwrap().serial();
assert!(!revoke_if_installed(id, first), "the grant of the plug-in installed in its place was forgotten");
assert!(granted(id).is_some());
assert!(revoke_if_installed(id, second));
assert!(granted(id).is_none() && remove(id));
}
/// A folder file that no loader thread was left to load fails with that reason, and the report
/// says a file found no thread ([`FolderReport::no_thread`]).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_file_no_thread_was_left_to_load_is_reported() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("nothread");
let id = "test.registry.nothread";
std::fs::write(dir.join("a.wasm"), module(id, None, 16)).unwrap();
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(1)).unwrap();
load.loads.refuse_threads = true;
load.start();
while !load.done() {
load.wait();
load.install_ready(|_| false);
}
let r = load.finish();
std::fs::remove_dir_all(&dir).unwrap();
assert!(get(id).is_none(), "{r:?}");
assert_eq!(r.failed.len(), 1, "{r:?}");
assert!(r.no_thread && r.failed[0].1.contains(crate::loader::NO_THREAD), "{r:?}");
}
}
+170 -28
View File
@@ -1,13 +1,13 @@
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
use wasmi::{
Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val,
WasmParams, WasmResults,
Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall,
Val, ValType, WasmParams, WasmResults,
};
use wasmparser::{Validator, WasmFeatures};
use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures};
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest};
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest};
use crate::permissions::Permission;
use crate::{Error, Kind, Result};
@@ -42,12 +42,46 @@ const WASM_FEATURES: WasmFeatures = WasmFeatures::MUTABLE_GLOBAL
.union(WasmFeatures::EXTENDED_CONST)
.union(WasmFeatures::FLOATS);
/// The most parameters or results a function type may have: the limit `EnforcedLimits::strict()`
/// sets in wasmi 2.0.0.
const MAX_FUNC_TYPE_VALUES: usize = 32;
/// Validates `bytes` with only [`WASM_FEATURES`] on, before wasmi reads the module. A module that
/// uses any other proposal is refused with the validator's error, which names the proposal.
/// uses any other proposal is refused with the validator's error, which names the proposal. A
/// function type with more than [`MAX_FUNC_TYPE_VALUES`] parameters or results is refused before
/// any function body is validated.
fn check_features(bytes: &[u8]) -> Result<()> {
check_func_types(bytes)?;
Validator::new_with_features(WASM_FEATURES).validate_all(bytes).map(|_| ()).map_err(|e| Error::Module(e.to_string()))
}
/// Refuses a function type in the type section with more than [`MAX_FUNC_TYPE_VALUES`] parameters
/// or results, with wasmi's message. Reading stops at the code section. A section that doesn't
/// parse is left to the validator, which reports it.
fn check_func_types(bytes: &[u8]) -> Result<()> {
for payload in Parser::new(0).parse_all(bytes) {
let types = match payload {
Ok(Payload::TypeSection(types)) => types,
Ok(Payload::CodeSectionStart { .. }) | Err(_) => return Ok(()),
Ok(_) => continue,
};
for group in types {
let Ok(group) = group else { return Ok(()) };
for ty in group.types() {
if let CompositeInnerType::Func(f) = &ty.composite_type.inner {
if f.params().len() > MAX_FUNC_TYPE_VALUES {
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters")));
}
if f.results().len() > MAX_FUNC_TYPE_VALUES {
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results")));
}
}
}
}
}
Ok(())
}
/// Sets each WebAssembly proposal that wasmi's `Config` has a setter for in this build on or off,
/// to match [`WASM_FEATURES`].
fn set_features(config: &mut Config) -> &mut Config {
@@ -219,10 +253,96 @@ fn wasm_err(e: wasmi::Error) -> Error {
/// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error).
type RunArgs = (i32, i32, i32, i32);
/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none.
/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`],
/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must
/// give the ABI version as `abi`, in place of the `vc_abi_version` export.
fn section_manifest(module: &Module) -> Result<Option<Manifest>> {
let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION);
let Some(section) = sections.next() else {
return Ok(None);
};
if sections.next().is_some() {
return Err(Error::Manifest(format!("the module has more than one `{MANIFEST_SECTION}` custom section")));
}
let manifest = Manifest::parse(section.data())?;
// `Manifest::parse` has checked that the section is UTF-8 JSON of at most `MAX_MANIFEST_BYTES`.
let abi = serde_json::from_slice::<serde_json::Value>(section.data()).ok().and_then(|v| v.get("abi").and_then(serde_json::Value::as_i64));
if abi != Some(i64::from(ABI_VERSION)) {
return Err(Error::Abi(format!(
"the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements"
)));
}
Ok(Some(manifest))
}
/// Most tables a module may define: the store an instance runs in holds no more.
const MAX_TABLES: u64 = 4;
/// Most elements a table may hold: the store an instance runs in holds no more.
const MAX_TABLE_ELEMENTS: u64 = 100_000;
/// The number of tables the module in `bytes` defines and the largest initial size among them,
/// from its table section, or `None` when its sections can't be read. `bytes` is a module
/// [`check_features`] has validated.
fn table_sizes(bytes: &[u8]) -> Option<(u64, u64)> {
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
if let wasmparser::Payload::TableSection(reader) = payload.ok()? {
let count = u64::from(reader.count());
let mut largest = 0;
for table in reader {
largest = largest.max(table.ok()?.ty.initial);
}
return Some((count, largest));
}
}
Some((0, 0))
}
/// Checks the tables the module in `bytes` defines against the store's limits ([`MAX_TABLES`]
/// tables of at most [`MAX_TABLE_ELEMENTS`] elements), which instantiating it checks. The host
/// offers no tables to import, so the module defines every table it has.
fn check_tables(bytes: &[u8]) -> Result<()> {
let Some((count, largest)) = table_sizes(bytes) else {
return Err(Error::Module("the module's table section could not be read".into()));
};
if count > MAX_TABLES || largest > MAX_TABLE_ELEMENTS {
return Err(Error::Limit(format!(
"table budget (the module defines {count} tables, the largest with {largest} elements; limit {MAX_TABLES} tables of {MAX_TABLE_ELEMENTS} elements)"
)));
}
Ok(())
}
/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types.
fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
use ValType::{I32, I64};
let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone());
let Some(ExternType::Memory(memory)) = export("memory") else {
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
};
// Pages are 64 KiB: the engine's configuration leaves custom page sizes off.
let initial = memory.minimum().saturating_mul(1 << 16);
if initial > max_memory_bytes as u64 {
return Err(Error::Limit(format!("memory budget (the module's initial memory is {initial} bytes, limit {max_memory_bytes})")));
}
let wanted: [(&str, &[ValType], &[ValType], &str); 2] =
[("vc_alloc", &[I32], &[I32], "(param i32) (result i32)"), ("vc_run", &[I32, I32, I32, I32], &[I64], "(param i32 i32 i32 i32) (result i64)")];
for (name, params, results, signature) in wanted {
if !matches!(export(name), Some(ExternType::Func(f)) if f.params() == params && f.results() == results) {
return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}")));
}
}
Ok(())
}
impl Plugin {
/// 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. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
/// Validates and loads a module: reads the manifest, checks that each host import it asks for
/// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the
/// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is
/// checked without being instantiated, so none of its code runs; one without that section is
/// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded
/// ([`Error::SafeMode`]).
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
crate::safe_mode::check()?;
if bytes.len() > limits.max_module_bytes {
@@ -243,22 +363,31 @@ impl Plugin {
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.wall_time_ms);
// The manifest isn't read yet: every host import is linked, what it reports is dropped and
// there is no storage to reach.
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &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 {
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
}
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
e => e,
})?;
p.manifest = Manifest::parse(&text)?;
let live = match section_manifest(&p.module)? {
Some(manifest) => {
p.manifest = manifest;
None
}
None => {
let deadline = Deadline::new(p.limits.wall_time_ms);
// The manifest isn't read yet: every host import is linked, what it reports is
// dropped and there is no storage to reach.
let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &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 {
return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}")));
}
let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?;
let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?;
let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e {
Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")),
e => e,
})?;
p.manifest = Manifest::parse(&text)?;
Some(live)
}
};
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.
@@ -267,8 +396,16 @@ impl Plugin {
p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms);
}
// The other exports must exist with the right types.
live.func::<i32, i32>("vc_alloc")?;
live.func::<RunArgs, i64>("vc_run")?;
match live {
Some(live) => {
live.func::<i32, i32>("vc_alloc")?;
live.func::<RunArgs, i64>("vc_run")?;
}
None => {
check_exports(&p.module, p.limits.max_memory_bytes)?;
check_tables(bytes)?;
}
}
Ok(p)
}
@@ -315,8 +452,13 @@ impl Plugin {
/// A new instance for `run`, with the host imports of the permissions `granted` linked. When the
/// module's start function fails, what it reported through the host imports goes to `report`.
fn instantiate(&self, run: Run, granted: &[Permission], 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 limits = StoreLimitsBuilder::new()
.memory_size(self.limits.max_memory_bytes)
.memories(1)
.tables(MAX_TABLES as usize)
.table_elements(MAX_TABLE_ELEMENTS as usize)
.instances(1)
.build();
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
+177 -84
View File
@@ -14,16 +14,16 @@
//!
//! **Launch marker** (native builds): a small file in a folder the app picks, written before the
//! stored plug-ins load, updated before and after each module load and each live effect's first
//! evaluation (and each evaluation that starts while one of those is running) to name the oldest
//! item still loading (several threads can load at once), and removed
//! when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A launch that
//! ends while an item is still loading (a panic the app caught while a plug-in loaded) keeps its
//! marker naming that item. A marker left behind by a
//! launch that is no longer running names the item that was loading when it stopped, which may or
//! may not be what stopped it. Until the user
//! chooses what to do about that item ([`forget_previous`]), the next launch's marker names it too
//! and stays when that launch quits, so a launch that asks nothing (`--safe-mode`) or one closed in
//! Safe Mode leaves the choice to the launch after it. Each launch has
//! evaluation (and each evaluation that starts while one of those is running) to name every item
//! still loading, oldest first (several threads can load at once; at most [`MAX_MARKER_ITEMS`]),
//! and removed when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A
//! launch that ends while an item is still loading (a panic the app caught outside a load job
//! while a plug-in loaded) keeps its marker naming that item. A marker left behind by a launch
//! that is no longer running names the items that were loading when it stopped; any one of them,
//! or none, may be what stopped it. Until the user chooses what to do about those items
//! ([`forget_previous`]), the next launch's marker names them too and stays when that launch
//! quits, so a launch that asks nothing (`--safe-mode`) or one closed in Safe Mode leaves the
//! choice to the launch after it. Each launch has
//! its own marker and holds a lock on a file beside it, so a launch that is still running (a second
//! window) is never taken for one that stopped. A marker that is missing, empty, unreadable,
//! malformed, larger than [`MAX_MARKER_BYTES`] or of another version names nothing.
@@ -41,8 +41,11 @@ const MAX_FIELD_CHARS: usize = 1024;
/// The most bytes one stored item takes in JSON: three fields of [`MAX_FIELD_CHARS`] characters,
/// each written in at most 6 bytes (`\u001f`), plus keys, quotes and indentation.
const MAX_ITEM_JSON_BYTES: usize = 3 * MAX_FIELD_CHARS * 6 + 256;
/// The largest launch marker read, in bytes: room for one stored item.
pub const MAX_MARKER_BYTES: u64 = (MAX_ITEM_JSON_BYTES + 256) as u64;
/// The most items a launch marker names.
pub const MAX_MARKER_ITEMS: usize = 16;
/// The largest launch marker read, in bytes: room for [`MAX_MARKER_ITEMS`] stored items, and the
/// first of them again as `item`.
pub const MAX_MARKER_BYTES: u64 = ((MAX_MARKER_ITEMS + 1) * MAX_ITEM_JSON_BYTES + 256) as u64;
/// The longest name an item is shown with, in characters (longer ones end with "…").
pub const MAX_NAME_CHARS: usize = 64;
/// The most disabled items kept.
@@ -413,18 +416,19 @@ pub fn read_disabled_file(bytes: &[u8]) -> Option<Vec<Item>> {
)
}
/// The item the launch before this one was loading when it stopped, once [`begin_launch`] read it.
static PREVIOUS: Mutex<Option<Item>> = Mutex::new(None);
/// The items the launch before this one was loading when it stopped, once [`begin_launch`] read
/// them.
static PREVIOUS: Mutex<Vec<Item>> = Mutex::new(Vec::new());
/// The item the launch before this one was loading when it stopped ([`begin_launch`]); `None` once
/// the user chose what to do about it ([`forget_previous`]).
pub fn previous() -> Option<Item> {
/// The items the launch before this one was loading when it stopped, oldest first
/// ([`begin_launch`]); none once the user chose what to do about them ([`forget_previous`]).
pub fn previous() -> Vec<Item> {
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// The user chose what to do about [`previous`]: this launch's marker stops naming it.
/// The user chose what to do about [`previous`]: this launch's marker stops naming them.
pub fn forget_previous() {
*PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()) = None;
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clear();
refresh();
}
@@ -437,9 +441,19 @@ struct Running {
#[cfg(not(target_arch = "wasm32"))]
impl Running {
/// The item this launch's marker names: the oldest item still loading, else [`previous`].
fn pending(&self) -> Option<Item> {
self.items.first().map(|(_, i)| i.clone()).or_else(previous)
/// The items this launch's marker names: the items still loading, oldest first, each plug-in
/// once, at most [`MAX_MARKER_ITEMS`]; with none loading, [`previous`].
fn pending(&self) -> Vec<Item> {
let mut items: Vec<Item> = Vec::new();
for (_, item) in &self.items {
if items.len() == MAX_MARKER_ITEMS {
break;
}
if !items.iter().any(|i| i.same(item)) {
items.push(item.clone());
}
}
if items.is_empty() { previous() } else { items }
}
}
@@ -450,22 +464,33 @@ static LOADING: Mutex<Running> = Mutex::new(Running { next: 0, items: Vec::new()
#[derive(Debug)]
pub struct Loading(u64);
/// Writes this launch's marker naming the item [`Running::pending`] gives, while holding the lock
/// Writes this launch's marker naming the items [`Running::pending`] gives, while holding the lock
/// on the items still loading, so two threads' writes land in the order of their changes.
fn refresh() {
#[cfg(not(target_arch = "wasm32"))]
marker::write(LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending().as_ref());
marker::write(&LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending());
}
/// The marker's content naming `item`, cut as a stored item is (none: nothing is loading).
/// The marker's content naming `items` (none: nothing is loading), each cut as a stored item is,
/// at most [`MAX_MARKER_ITEMS`]: the first as `item`, and all of them as `items` when there are
/// several.
#[cfg(not(target_arch = "wasm32"))]
fn marker_bytes(item: Option<&Item>) -> Vec<u8> {
let item = item.cloned().and_then(Item::bounded);
serde_json::to_vec(&json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": item})).unwrap_or_default()
fn marker_bytes(items: &[Item]) -> Vec<u8> {
let items: Vec<Item> = items.iter().cloned().filter_map(Item::bounded).take(MAX_MARKER_ITEMS).collect();
let mut v = json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": items.first()});
if items.len() > 1 {
v["items"] = json!(items);
}
serde_json::to_vec(&v).unwrap_or_default()
}
/// The item a marker's content names; `None` when it names none or isn't a marker of this version.
pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
/// The items a marker's content names, oldest first: its `items` when it has them, else its
/// `item`; none when it names none or isn't a marker of this version.
pub fn parse_marker(bytes: &[u8]) -> Vec<Item> {
read_marker(bytes).unwrap_or_default()
}
fn read_marker(bytes: &[u8]) -> Option<Vec<Item>> {
if bytes.len() as u64 > MAX_MARKER_BYTES {
return None;
}
@@ -473,31 +498,44 @@ pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
if v["format"] != MARKER_FORMAT || v["version"] != MARKER_VERSION {
return None;
}
serde_json::from_value::<Item>(v.get("item").filter(|i| i.is_object())?.clone()).ok()?.bounded()
let item = |i: &Value| serde_json::from_value::<Item>(i.clone()).ok()?.bounded();
let mut items: Vec<Item> = Vec::new();
for i in v["items"].as_array().into_iter().flatten().filter(|i| i.is_object()) {
if items.len() == MAX_MARKER_ITEMS {
break;
}
if let Some(i) = item(i).filter(|i| !items.iter().any(|e| e.same(i))) {
items.push(i);
}
}
if items.is_empty() {
items.extend(v.get("item").filter(|i| i.is_object()).and_then(item));
}
Some(items)
}
#[cfg(not(target_arch = "wasm32"))]
pub use marker::{begin_launch, end_launch};
/// Adds `item` to the items still loading and writes this launch's marker naming the oldest of
/// them (no marker: only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
/// Adds `item` to the items still loading and writes this launch's marker naming them (no marker:
/// only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
pub fn loading(item: &Item) -> Loading {
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
let token = running.next;
running.next = running.next.wrapping_add(1);
running.items.push((token, item.clone()));
#[cfg(not(target_arch = "wasm32"))]
marker::write(running.pending().as_ref());
marker::write(&running.pending());
Loading(token)
}
/// Removes the item `token` names from the items still loading and writes this launch's marker
/// naming the oldest one left; with none left, the item of [`previous`] or nothing.
/// naming the ones left; with none left, the items of [`previous`] or nothing.
pub fn loaded(token: Loading) {
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
running.items.retain(|(t, _)| *t != token.0);
#[cfg(not(target_arch = "wasm32"))]
marker::write(running.pending().as_ref());
marker::write(&running.pending());
}
#[cfg(not(target_arch = "wasm32"))]
@@ -551,12 +589,12 @@ mod marker {
(bytes.len() as u64 <= MAX_MARKER_BYTES).then_some(bytes)
}
/// Starts this launch's marker in `dir` → the item a launch that is no longer running was
/// loading when it stopped, if one was (its marker is then removed, and this launch's marker
/// names the item until [`super::forget_previous`]). A folder that can't be written leaves this
/// launch without a marker; it still starts.
pub fn begin_launch(dir: &Path) -> Option<Item> {
let mut previous = None;
/// Starts this launch's marker in `dir` → the items a launch that is no longer running was
/// loading when it stopped, if it was loading any (its marker is then removed, and this
/// launch's marker names the items until [`super::forget_previous`]). A folder that can't be
/// written leaves this launch without a marker; it still starts.
pub fn begin_launch(dir: &Path) -> Vec<Item> {
let mut previous = Vec::new();
let mut tokens: Vec<String> = std::fs::read_dir(dir)
.into_iter()
.flatten()
@@ -569,8 +607,8 @@ mod marker {
if running(dir, &token) {
continue;
}
if previous.is_none() {
previous = read(&json_path(dir, &token)).as_deref().and_then(parse_marker);
if previous.is_empty() {
previous = read(&json_path(dir, &token)).as_deref().map(parse_marker).unwrap_or_default();
}
for path in [json_path(dir, &token), tmp_path(dir, &token), lock_path(dir, &token)] {
let _ = std::fs::remove_file(path);
@@ -588,32 +626,32 @@ mod marker {
previous
}
/// Replaces this launch's marker with one naming `item`: written to a temporary file first,
/// Replaces this launch's marker with one naming `items`: written to a temporary file first,
/// then renamed over the marker, so a reader finds the old marker or the new one. A write that
/// fails leaves the marker as it was.
pub(super) fn write(item: Option<&Item>) {
pub(super) fn write(items: &[Item]) {
let current = CURRENT.lock().unwrap_or_else(|e| e.into_inner());
let Some(c) = current.as_ref() else { return };
let tmp = tmp_path(&c.dir, &c.token);
let _ = File::create(&tmp)
.and_then(|mut f| f.write_all(&marker_bytes(item)).and_then(|()| f.sync_all()))
.and_then(|mut f| f.write_all(&marker_bytes(items)).and_then(|()| f.sync_all()))
.and_then(|()| std::fs::rename(&tmp, json_path(&c.dir, &c.token)));
}
/// Removes this launch's marker: the app is quitting normally. While an item is still loading
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the oldest one;
/// otherwise, while the user has not chosen what to do about [`super::previous`], the marker
/// stays, naming that, so the next launch asks.
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the items still
/// loading; otherwise, while the user has not chosen what to do about [`super::previous`], the
/// marker stays, naming those, so the next launch asks.
pub fn end_launch() {
let running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
let pending = running.pending();
if pending.is_some() {
write(pending.as_ref());
if !pending.is_empty() {
write(&pending);
}
let Some(c) = CURRENT.lock().unwrap_or_else(|e| e.into_inner()).take() else { return };
let Current { dir, token, _lock } = c;
drop(_lock);
let marker = pending.is_none().then(|| json_path(&dir, &token));
let marker = pending.is_empty().then(|| json_path(&dir, &token));
for path in marker.into_iter().chain([tmp_path(&dir, &token), lock_path(&dir, &token)]) {
let _ = std::fs::remove_file(path);
}
@@ -629,6 +667,12 @@ mod marker {
#[cfg(test)]
pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
/// Tests: the items still loading, oldest first.
#[cfg(test)]
pub(crate) fn still_loading() -> Vec<Item> {
LOADING.lock().unwrap_or_else(|e| e.into_inner()).items.iter().map(|(_, i)| i.clone()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -683,11 +727,18 @@ mod tests {
assert_eq!(Item::file("C:\\Plug-ins\\x.wasm").label(), "x.wasm");
}
/// The items the marker at `path` names.
fn marker_at(path: &std::path::Path) -> Vec<Item> {
std::fs::read(path).ok().as_deref().map(parse_marker).unwrap_or_default()
}
#[test]
fn only_a_marker_of_this_version_names_an_item() {
let item = Item { id: Some("org.example.x".into()), file: Some("/p/x.wasm".into()), name: None };
assert_eq!(parse_marker(&marker_bytes(Some(&item))), Some(item));
assert_eq!(parse_marker(&marker_bytes(None)), None, "nothing was loading");
assert_eq!(parse_marker(&marker_bytes(std::slice::from_ref(&item))), std::slice::from_ref(&item));
assert_eq!(parse_marker(&marker_bytes(&[])), [], "nothing was loading");
// A marker naming one item has no `items`, as before markers named several.
assert!(!String::from_utf8(marker_bytes(std::slice::from_ref(&item))).unwrap().contains("\"items\""));
for bad in [
&b""[..],
b"{",
@@ -698,13 +749,28 @@ mod tests {
br#"{"format":"vectorcraft-launch","version":1,"item":{}}"#,
br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x""#,
] {
assert_eq!(parse_marker(bad), None, "{}", String::from_utf8_lossy(bad));
assert_eq!(parse_marker(bad), [], "{}", String::from_utf8_lossy(bad));
}
let mut big =
format!(r#"{{"format":"vectorcraft-launch","version":1,"item":{{"id":"{}"}}}}"#, "y".repeat(MAX_MARKER_BYTES as usize)).into_bytes();
assert_eq!(parse_marker(&big), None, "larger than the limit");
assert_eq!(parse_marker(&big), [], "larger than the limit");
big.truncate(10);
assert_eq!(parse_marker(&big), None, "cut short");
assert_eq!(parse_marker(&big), [], "cut short");
}
#[test]
fn a_marker_names_every_item_up_to_its_limit() {
let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(MAX_FIELD_CHARS));
let items: Vec<Item> =
(0..MAX_MARKER_ITEMS + 3).map(|i| Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }).collect();
let bytes = marker_bytes(&items);
assert!(bytes.len() as u64 <= MAX_MARKER_BYTES, "{} bytes", bytes.len());
let read = parse_marker(&bytes);
assert_eq!(read.len(), MAX_MARKER_ITEMS);
assert!(read.iter().zip(&items).all(|(r, i)| r.same(i)), "oldest first");
// A marker whose `items` names nothing readable falls back to its `item`.
let x = br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x"},"items":[{},"y"]}"#;
assert_eq!(parse_marker(x), [Item { id: Some("x".into()), ..Item::default() }]);
}
#[test]
@@ -714,23 +780,23 @@ mod tests {
// A launch that stopped while loading x: its marker without a held lock, and a stray
// temporary file from a write it didn't finish.
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
std::fs::write(dir.join("launch-1-a.json.tmp"), b"{\"format\":\"vectorcr").unwrap();
assert_eq!(begin_launch(&dir), Some(x.clone()));
assert_eq!(previous(), Some(x.clone()));
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
assert_eq!(previous(), std::slice::from_ref(&x));
assert!(!dir.join("launch-1-a.json").exists() && !dir.join("launch-1-a.json.tmp").exists(), "read once");
let mine = marker::path_of_current().unwrap();
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()), "named until the user chooses");
assert_eq!(marker_at(&mine), std::slice::from_ref(&x), "named until the user chooses");
forget_previous();
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
assert_eq!(marker_at(&mine), []);
let token = loading(&x);
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()));
assert_eq!(marker_at(&mine), std::slice::from_ref(&x));
assert!(!mine.with_extension("json.tmp").exists(), "the temporary file is renamed over the marker");
loaded(token);
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
assert_eq!(marker_at(&mine), []);
end_launch();
assert!(!mine.exists(), "a normal quit removes the marker");
assert_eq!(begin_launch(&dir), None, "nothing left behind");
assert_eq!(begin_launch(&dir), [], "nothing left behind");
end_launch();
forget_previous();
let _ = std::fs::remove_dir_all(&dir);
@@ -741,13 +807,13 @@ mod tests {
let _f = fresh();
let dir = temp_dir("pending");
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
assert_eq!(begin_launch(&dir), Some(x.clone()));
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
end_launch();
assert_eq!(begin_launch(&dir), Some(x.clone()), "asked again");
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "asked again");
forget_previous();
end_launch();
assert_eq!(begin_launch(&dir), None, "once the user chose");
assert_eq!(begin_launch(&dir), [], "once the user chose");
end_launch();
let _ = std::fs::remove_dir_all(&dir);
}
@@ -757,15 +823,15 @@ mod tests {
let _f = fresh();
let dir = temp_dir("ends-loading");
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
assert_eq!(begin_launch(&dir), None);
assert_eq!(begin_launch(&dir), []);
let token = loading(&x);
// A panic the app caught while x loaded: the app quits without `loaded`.
end_launch();
loaded(token);
assert_eq!(begin_launch(&dir), Some(x.clone()), "the next launch asks");
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "the next launch asks");
forget_previous();
end_launch();
assert_eq!(begin_launch(&dir), None);
assert_eq!(begin_launch(&dir), []);
end_launch();
let _ = std::fs::remove_dir_all(&dir);
}
@@ -776,22 +842,49 @@ mod tests {
let dir = temp_dir("two-loading");
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
assert_eq!(begin_launch(&dir), None);
assert_eq!(begin_launch(&dir), []);
let mine = marker::path_of_current().unwrap();
let marker = || std::fs::read(&mine).ok().as_deref().and_then(parse_marker);
// Two threads run their plug-ins' first evaluations at once.
let ta = loading(&a);
let tb = loading(&b);
assert_eq!(marker(), Some(a.clone()), "the oldest item still loading");
assert_eq!(marker_at(&mine), [a.clone(), b.clone()], "both items still loading, oldest first");
loaded(ta);
assert_eq!(marker(), Some(b.clone()), "b is still loading");
assert_eq!(marker_at(&mine), std::slice::from_ref(&b), "b is still loading");
// The app stops while b loads.
end_launch();
loaded(tb);
assert_eq!(begin_launch(&dir), Some(b.clone()), "the next launch offers b");
assert_eq!(begin_launch(&dir), std::slice::from_ref(&b), "the next launch offers b");
forget_previous();
end_launch();
assert_eq!(begin_launch(&dir), None);
assert_eq!(begin_launch(&dir), []);
end_launch();
let _ = std::fs::remove_dir_all(&dir);
}
/// A launch that stops while two plug-ins load offers both at the next launch, until the user
/// chooses, however many launches that takes.
#[test]
fn a_launch_that_stops_while_two_plug_ins_load_offers_both() {
let _f = fresh();
let dir = temp_dir("two-stopped");
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
assert_eq!(begin_launch(&dir), []);
let ta = loading(&a);
let tb = loading(&b);
// The same plug-in loading twice is named once.
let ta2 = loading(&a);
end_launch();
for t in [ta, tb, ta2] {
loaded(t);
}
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "the next launch offers both");
assert_eq!(previous(), [a.clone(), b.clone()]);
end_launch();
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "asked again");
forget_previous();
end_launch();
assert_eq!(begin_launch(&dir), []);
end_launch();
let _ = std::fs::remove_dir_all(&dir);
}
@@ -802,11 +895,11 @@ mod tests {
let dir = temp_dir("long-path");
// Each character written as 6 or 2 bytes, so the item is far larger in JSON than in characters.
let long = format!("C:\\{}\\x.wasm", "\u{1}é".repeat(700));
assert_eq!(begin_launch(&dir), None);
assert_eq!(begin_launch(&dir), []);
let token = loading(&Item::file(long.clone()));
end_launch();
loaded(token);
let stopped = begin_launch(&dir).expect("the marker names the module");
let stopped = begin_launch(&dir).into_iter().next().expect("the marker names the module");
assert!(stopped.same(&Item::file(long.clone())), "the stored item matches the full path");
disable(stopped);
assert!(skipped(&Item::file(long.clone())), "Disable and Continue skips it");
@@ -891,14 +984,14 @@ mod tests {
let _f = fresh();
let dir = temp_dir("running");
let x = Item { id: Some("org.example.x".into()), file: None, name: None };
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(Some(&x))).unwrap();
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
let lock = std::fs::File::create(dir.join("launch-9-b.lock")).unwrap();
lock.try_lock().unwrap();
assert_eq!(begin_launch(&dir), None, "that launch is still running");
assert_eq!(begin_launch(&dir), [], "that launch is still running");
assert!(dir.join("launch-9-b.json").exists());
end_launch();
drop(lock);
assert_eq!(begin_launch(&dir), Some(x), "once it stopped");
assert_eq!(begin_launch(&dir), [x], "once it stopped");
end_launch();
forget_previous();
let _ = std::fs::remove_dir_all(&dir);
+54 -6
View File
@@ -7,12 +7,26 @@ const OUTPUT_AT: usize = 0x1_0000;
/// `s` as the body of a WAT string literal (every byte that isn't a letter, digit or space
/// escaped).
pub fn string(s: &str) -> String {
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
bytes(s.as_bytes())
}
/// `data` as the body of a WAT string literal, every byte that isn't an ASCII letter, digit or
/// space escaped (so it may hold any bytes, UTF-8 or not).
pub fn bytes(data: &[u8]) -> String {
data.iter().map(|&b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
}
/// `vc_alloc`, which grows memory by whole pages, so its blocks never overlap data segments.
const ALLOC: &str = r#"(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))"#;
/// A plug-in module: `manifest` (JSON), a `vc_run` whose body is `run` (parameters `$in $il $pp
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory. `vc_alloc` grows
/// memory by whole pages, so its blocks never overlap data segments.
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory (at least 1: with
/// none, the first `vc_alloc` block would start at 0, which the host refuses). `vc_alloc` grows
/// memory by whole pages, so its blocks never overlap data segments. The manifest comes from the
/// `vc_manifest` export, which the host calls when it loads the module ([`sectioned`] carries it in
/// a custom section instead).
pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
format!(
r#"(module
@@ -21,16 +35,50 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
(data (i32.const 16) "{data}")
(func (export "vc_abi_version") (result i32) (i32.const 1))
(func (export "vc_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 16)))
(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))
{ALLOC}
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
{run}))"#,
pages = pages.max(1),
data = string(manifest),
len = manifest.len(),
)
}
/// A custom section named `name` holding `data`, as a module field.
pub fn custom_section(name: &str, data: &[u8]) -> String {
format!(r#"(@custom "{}" "{}")"#, string(name), bytes(data))
}
/// A plug-in module like [`module`] that carries `manifest` in its `vc_manifest` custom section
/// ([`crate::manifest::MANIFEST_SECTION`]) and exports only `memory`, `vc_alloc` and `vc_run`: the
/// host reads the manifest without running any of its code. The host loads it only when `manifest`
/// gives `"abi": 1`. It has `pages` of initial memory, at least 1, as [`module`] has.
pub fn sectioned(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
format!(
r#"(module
{section}
{extra}
(memory (export "memory") {pages})
{ALLOC}
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
{run}))"#,
section = custom_section(crate::manifest::MANIFEST_SECTION, manifest.as_bytes()),
pages = pages.max(1),
)
}
/// `module` (a module in WebAssembly text that starts with `(module`, after any white space) with
/// the module field `field` added first, after the module's `$name` when it has one, such as a
/// [`custom_section`]; `None` when `module` does not start with `(module`.
pub fn with_field(module: &str, field: &str) -> Option<String> {
let rest = module.trim_start().strip_prefix("(module")?;
let Some(id) = rest.trim_start().strip_prefix('$') else {
return Some(format!("(module\n {field}{rest}"));
};
let (name, rest) = id.split_at(id.find(|c: char| c.is_whitespace() || c == '(' || c == ')').unwrap_or(id.len()));
Some(format!("(module ${name}\n {field}{rest}"))
}
/// A `vc_run` body returning the input unchanged.
pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))";