diff --git a/ASSETS.md b/ASSETS.md index f143870cf2..76a3d41962 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -143,12 +143,14 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | | `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-artboards.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-blend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-blend-align-page.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-blend-align-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-bloat.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-blob-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -227,6 +229,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-live-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-mask-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-measure.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-measure-inspect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-mesh.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-mirror-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -245,6 +248,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-para-numbers.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: the digits 1, 2 and 3, each before a line | MIT OR Apache-2.0 | | | `assets/icons/dc-para-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-parametric-shape.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pathfinder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-perspective-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -262,32 +266,38 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-place-symbol.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-polar-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-print-tiling.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | | | `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-recolor-arrow.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a right arrow, a Recolor Artwork row that is recolored) | MIT OR Apache-2.0 | | | `assets/icons/dc-recolor-arrow-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dashed line without a head, a Recolor Artwork row that is excluded) | MIT OR Apache-2.0 | | +| `assets/icons/dc-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-reference-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-remove-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-reshape.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-reverse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-rotate.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rotate-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rounded-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rule-evenodd.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rule-nonzero.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-scale.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-scallop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shape-builder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-shaper.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shared-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-slice-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-slice.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-slide-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-spiral.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-outside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -305,6 +315,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-symbol-stainer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-symbol-styler.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-tangent-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -315,6 +326,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-type-vertical.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-type-vertical-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-type-vertical-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-warp.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-width-profile.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-width.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-wrinkle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 5e827cfc41..c8b4f370ad 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -104,6 +104,9 @@ impl eframe::App for App { // screen first (`quit_windows`). #[cfg(not(any(target_os = "macos", windows)))] super::quit_windows::before_teardown(self.winit_window.as_deref()); + // Plug-ins still loading end before the launch marker does (the macOS exit below skips + // dropping the app). + self.app.session.cancel_plugin_loads(); end_before_teardown(self.frames); } } @@ -164,8 +167,9 @@ impl App { // dialog is open: what asked for it runs again on its document when it answers. They also // wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as // do the command line's files held back for it. Files later launches handed over before the - // choice ended in Safe Mode open in a new app with plug-ins. - if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) { + // choice ended in Safe Mode open in a new app with plug-ins. They wait while plug-ins load + // as well, since a plug-in may be what reads them. + if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) && !self.app.session.plugins_loading() { let held = std::mem::take(&mut self.held_files); #[cfg(target_os = "macos")] let files = open_documents::take(); @@ -215,9 +219,10 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) { } /// Open the command line's `files` now, or, while the choice about a stopped plug-in is up -/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads. +/// ([`safe_mode::choosing`]) or plug-ins are still loading (a plug-in may be what reads one), +/// return them to open once it is made and they have loaded. pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec) -> Vec { - if safe_mode::choosing(app) { + if safe_mode::choosing(app) || app.session.plugins_loading() { return files; } open_files(app, files); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 10bd58b371..9bfb5ea3d2 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -811,6 +811,9 @@ fn main() -> std::process::ExitCode { let launch_dir = prefs_dir::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch")); let folder = |name: &str| prefs_dir::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string()); let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag); + // The launch's loads of the stored plug-ins and the plug-ins folder go on on worker + // threads while the window shows; the frames install them as they finish. + session.load_plugins_in_background(true); prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); @@ -826,6 +829,9 @@ fn main() -> std::process::ExitCode { app.set_startup_update_check(!nightly); load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); + // Loads started later (a preference change, the end of Safe Mode) are waited for, + // after the launch's own. + app.session.load_plugins_in_background(false); // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. prefs_dir::attach_pdf_preset_store(&mut app.session); diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 4f6d7c6e7c..838d96845a 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -50,7 +50,8 @@ fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() { ..Default::default() }; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services); - app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"})); + let held = serde_json::json!({"id": "test.held", "name": "Held"}); + app.ui.stopped_plugin = Some(serde_json::json!({"item": held, "items": [held]})); assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up"); assert!(read.borrow().is_empty(), "nothing opened before the choice"); app.ui.stopped_plugin = None; diff --git a/assets/icons/dc-artboard.svg b/assets/icons/dc-artboard.svg new file mode 100644 index 0000000000..8f8eb56d8a --- /dev/null +++ b/assets/icons/dc-artboard.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-blob-brush.svg b/assets/icons/dc-blob-brush.svg new file mode 100644 index 0000000000..4ab1eb3746 --- /dev/null +++ b/assets/icons/dc-blob-brush.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-measure-inspect.svg b/assets/icons/dc-measure-inspect.svg new file mode 100644 index 0000000000..e900ef8cd6 --- /dev/null +++ b/assets/icons/dc-measure-inspect.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-parametric-shape.svg b/assets/icons/dc-parametric-shape.svg new file mode 100644 index 0000000000..eab483cf68 --- /dev/null +++ b/assets/icons/dc-parametric-shape.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-print-tiling.svg b/assets/icons/dc-print-tiling.svg new file mode 100644 index 0000000000..b28289a0bc --- /dev/null +++ b/assets/icons/dc-print-tiling.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-rect.svg b/assets/icons/dc-rect.svg new file mode 100644 index 0000000000..00df3388bd --- /dev/null +++ b/assets/icons/dc-rect.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-rotate.svg b/assets/icons/dc-rotate.svg new file mode 100644 index 0000000000..5df9456e0e --- /dev/null +++ b/assets/icons/dc-rotate.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-scale.svg b/assets/icons/dc-scale.svg new file mode 100644 index 0000000000..477077b16b --- /dev/null +++ b/assets/icons/dc-scale.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-shaper.svg b/assets/icons/dc-shaper.svg new file mode 100644 index 0000000000..798c87c97b --- /dev/null +++ b/assets/icons/dc-shaper.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-spiral.svg b/assets/icons/dc-spiral.svg new file mode 100644 index 0000000000..ff798b2b29 --- /dev/null +++ b/assets/icons/dc-spiral.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-tangent-circle.svg b/assets/icons/dc-tangent-circle.svg new file mode 100644 index 0000000000..1893b21329 --- /dev/null +++ b/assets/icons/dc-tangent-circle.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-warp.svg b/assets/icons/dc-warp.svg new file mode 100644 index 0000000000..b21afb1da8 --- /dev/null +++ b/assets/icons/dc-warp.svg @@ -0,0 +1 @@ + diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 0418477194..2770471f70 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2192,6 +2192,13 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Most steps the blends in `n` and its subtree make in all when drawn: a step that copies a +/// blend counts that blend's steps again, and each instance of a repeat counts its source's +/// steps again. Objects that are not blend steps count 0. +pub fn blend_steps_made(n: &Node) -> usize { + StepCount::default().node(n, false) +} + /// Does each pair of `keys` blended with `spec` ask for the same number of steps /// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, /// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ce2db1fa0b..250fc98f9b 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -849,6 +849,13 @@ impl ReadFile { r } + /// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a + /// file that stopped for its profile question, or the linked files and the type of an answered + /// one? + pub fn read_left(&self) -> bool { + self.rest.is_some() || self.links_left.is_some() + } + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile /// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked /// files and the type. The app runs it off the UI thread once the question is answered. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 7ae81b5bf6..7b87f7ffef 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -43,6 +43,11 @@ //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +//! +//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is +//! also given the parts of the active document it names in `_context.document`, whether or not +//! anything is selected: the settings, artboards, layers and swatches, as plain values +//! ([`context`]). use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; @@ -52,10 +57,13 @@ use vectorcraft_doc::{Document, Effect, Node}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; -use crate::store::StoreTurn; +use crate::store::{PluginLoad, StoreTurn}; use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; +mod context; +pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS}; + /// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. fn err(e: vectorcraft_plugins::Error) -> EngineError { match e { @@ -102,6 +110,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.context.is_empty() { + v["context"] = json!(m.context); + } if m.paint_output { v["paintOutput"] = json!(true); } @@ -257,15 +268,25 @@ impl FilterRun { params["_context"]["mode"] = json!("command"); params["_context"]["command"] = json!(cmd.id); } + // The parts of the document its manifest asks for (`context`), selection or not. Each row + // costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions. + let sections = m.context_sections(); + let mut charged = 0; + if !sections.is_empty() && may.contains(&Permission::DocRead) { + let given = context::document_context(st, §ions, c)?; + params["_context"]["document"] = given.value; + charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM); + } let params = serde_json::to_vec(¶ms).map_err(|e| bad(c, e.to_string()))?; // The input and the parameters may use half the plug-in's memory together. let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - let limits = match s.prefs.plugin_instruction_budget { + let mut limits = match s.prefs.plugin_instruction_budget { crate::PluginBudget::Normal => plugin.limits().clone(), crate::PluginBudget::Large => plugin.large_limits(), }; + limits.fuel_base = limits.fuel_base.saturating_sub(charged); Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } @@ -299,11 +320,17 @@ impl FilterRun { } /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when - /// it was made. + /// it was made, less what its document context costs. pub fn limits(&self) -> &vectorcraft_plugins::Limits { &self.limits } + /// The parameters it hands the plug-in, `_context` included. + #[cfg(test)] + pub(crate) fn params_json(&self) -> Value { + serde_json::from_slice(&self.params).unwrap_or(Value::Null) + } + /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the /// session ([`FilterRun::run_with_calls`]). pub fn calls(&self) -> bool { @@ -1013,12 +1040,16 @@ thread_local! { pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; /// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits. pub(crate) static WHILE_WAITING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// Tests: runs once in the next `plugin.reload` on this thread after its load started and before + /// it installs, as another session loading a folder in between would. + pub(crate) static BEFORE_RELOAD_INSTALLS: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Held by `plugin.install` from its first read of the grant until the store holds what it -/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins -/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the -/// other across sessions. +/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins +/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run +/// one after the other across sessions. It is not held while the modules load, so a session's +/// plug-in commands don't wait for another session's loads. static PLUGIN_CHANGES: Mutex<()> = Mutex::new(()); /// Takes [`PLUGIN_CHANGES`], waiting while another session holds it. @@ -1036,6 +1067,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> { } } +/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting. +pub(crate) fn try_hold_plugin_changes() -> Option> { + match PLUGIN_CHANGES.try_lock() { + Ok(held) => Some(held), + Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => None, + } +} + +/// Tests: whether [`PLUGIN_CHANGES`] could be taken now. +#[cfg(test)] +pub(crate) fn plugin_changes_free() -> bool { + !matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock)) +} + /// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an /// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget /// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this @@ -1285,31 +1331,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec)> { Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into())) } -/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what -/// happened. -static FOLDER: Mutex, Value)>> = Mutex::new(None); +/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what +/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no +/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next +/// [`sync_prefs`] loads the folder again. +type FolderRecord = (String, Option, Value, u64, bool); + +/// The [`FolderRecord`] of the plug-in folder last loaded. +static FOLDER: Mutex> = Mutex::new(None); + +/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`] +/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and +/// a `plugin.reload` keeps its report only when no load started after it. +static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the /// session's plug-in store, has changed since the last load. Runs whenever preferences are applied -/// (startup, `prefs.set`). Native only. -pub(crate) fn sync_prefs(s: &Session) { - let folder = s.prefs.plugins_folder.trim(); +/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the +/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it +/// returns once the folder's plug-ins are installed, also while another session is still loading +/// the same folder. Native only. +pub(crate) fn sync_prefs(s: &mut Session) { + let folder = s.prefs.plugins_folder.trim().to_string(); // In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]). if folder.is_empty() || safe_mode::active() { return; } - let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); - if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) { + // This session's own load of the folder, still running, is waited for unless loads go on in the + // background. + if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) { + if !s.plugin_loads_in_background { + s.finish_plugin_loads(); + } return; } - *last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder))); + let token = { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // A folder another session is still loading is loaded here too: that load may end with its + // session, and this one returns once its own plug-ins are installed. + // A load in which a file found no thread to load it is tried again. + if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) { + return; + } + let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + *last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false)); + token + }; + let load = start_folder(s, &folder, Some(token)); + s.queue_plugin_load(PluginLoad::Folder(load)); } /// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last /// loaded, it is forgotten, so setting the preference to it again loads it again. pub(crate) fn forget_prefs_folder(old: &str) { let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); - if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) { + if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) { *last = None; } } @@ -1329,42 +1405,232 @@ pub fn load_prefs_folder(s: &mut Session) { sync_prefs(s); } -/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted -/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the -/// disabled list when loading changed it. +/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none. #[cfg(not(target_arch = "wasm32"))] -fn load_folder(s: &Session, folder: &str) -> Value { - if let Err(e) = crate::file_access::check_read(folder) { - return json!({"folder": folder, "error": e}); - } - // A file in it may be a link to one elsewhere. - let allow = |f: &std::path::Path| match f.to_str() { - Some(f) => crate::file_access::check_read(f), - // A lossy name would check another file than the one loaded. - None if crate::file_access::current().is_none() => Ok(()), - None => Err(format!("automation path rejected: {} isn't valid text", f.display())), - }; - // A `plugin.install` in another session or process finishes writing the store first. When the - // store can't be locked, the folder still loads, and the store isn't written. - let _held = hold_plugin_changes(); - let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()); - match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { - Ok(r) => { - for id in &r.loaded { - s.attach_plugin_storage(&turn, id); - } - if r.disabled_changed { - s.store_disabled_plugins_in(&turn); - } - json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>(), "leftOut": r.left_out}) +type FolderModules = registry::FolderLoad; +#[cfg(target_arch = "wasm32")] +type FolderModules = std::convert::Infallible; + +/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the +/// modules load and [`end_folder`] ends. +pub(crate) struct FolderPending { + folder: String, + /// The plug-in store whose grants it loads with. + store: Option, + /// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last + /// loaded ([`sync_prefs`]). + record: Option, + /// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a + /// load started after it. + reload: bool, + /// The modules loading, or the report of a folder that can't be loaded; `None` once ended. + load: Option>, + /// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]). + canceled: bool, +} + +impl FolderPending { + /// Whether every module has been installed or reported. + pub(crate) fn done(&self) -> bool { + match &self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => load.done(), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => true, } - Err(e) => json!({"folder": folder, "error": e.to_string()}), + } + + /// Starts the modules loading, unless they started already. + pub(crate) fn start(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.start(); + } + } + + /// The installs and removals its modules are checked against (`None`: the folder couldn't be + /// listed, or the load ended). + pub(crate) fn changes(&self) -> Option<®istry::LoadChanges> { + match &self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => Some(load.changes()), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => None, + } + } + + /// [`FolderPending::changes`], to adopt an earlier load's. + pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> { + match &mut self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => Some(load.changes_mut()), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => None, + } + } + + /// Whether something can be installed or reported now, without waiting. + pub(crate) fn ready(&mut self) -> bool { + match &mut self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => load.ready(), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => true, + } + } + + /// Waits until the next module in file-name order has loaded or failed. + pub(crate) fn wait(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.wait(); + } + } + + /// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`] + /// then keeps no report as the folder last loaded. + pub(crate) fn cancel(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.cancel(); + } + self.canceled = true; + } + + /// Whether it is a load of `folder` with the plug-in store `store`. + pub(crate) fn loads(&self, folder: &str, store: &Option) -> bool { + self.folder == folder && self.store == *store } } +impl Drop for FolderPending { + /// A load dropped before it ended (its session closed) leaves no folder reported as loading, so + /// the next session that applies the preference loads it. + fn drop(&mut self) { + if let Some(token) = self.record.filter(|_| self.load.is_some()) { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) { + *last = None; + } + } + } +} + +/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`: +/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report. +#[cfg(not(target_arch = "wasm32"))] +fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + let pending = + |load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }; + if let Err(e) = crate::file_access::check_read(folder) { + return pending(Err(json!({"folder": folder, "error": e}))); + } + // A file in it may be a link to one elsewhere. Each file is checked again on its worker + // thread, in the scope in force here (the automation roots and the script gate), as the + // folder itself was. + let scope = crate::file_access::ScopeHandle::capture_now(); + let allow = move |f: &std::path::Path| { + scope.clone().run(|| match f.to_str() { + Some(f) => crate::file_access::check_read(f), + // A lossy name would check another file than the one loaded. + None if crate::file_access::current().is_none() => Ok(()), + None => Err(format!("automation path rejected: {} isn't valid text", f.display())), + }) + }; + // The modules start loading once the loads queued before them are done. + pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()}))) +} + #[cfg(target_arch = "wasm32")] -fn load_folder(_: &Session, folder: &str) -> Value { - json!({"folder": folder, "error": "plug-in folders are not available on the web"}) +fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"})); + FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false } +} + +/// Installs what `load` has loaded so far, in file-name order up to the first module still +/// loading, without waiting: those that list permissions only when `s` has them granted +/// ([`Session::plugin_approved`], with the store's grants read once). Runs while +/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process +/// finishes writing the store first; when the store can't be locked, the folder still installs, +/// and the store isn't written. +pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut load.load + && !load.done() + { + for id in load.install_ready(s.plugin_folder_approver()) { + s.attach_plugin_storage(turn, &id); + } + // A disabled plug-in's file matched by its id is saved in the same turn. + if load.disabled_changed() && s.store_disabled_plugins_in(turn) { + load.disabled_saved(); + } + } + #[cfg(target_arch = "wasm32")] + let _ = (s, load, turn); +} + +/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so +/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can +/// record one for another module → its report; saves the disabled list when loading changed it. +pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value { + let (report, retry) = match load.load.take() { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(modules)) => { + let r = modules.finish(); + if r.disabled_changed { + s.store_disabled_plugins_in(turn); + } + let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>(); + (json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread) + } + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match never {}, + Some(Err(report)) => (report, false), + None => (Value::Null, false), + }; + if let Some(token) = load.record { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no + // folder reported, so the next session that applies the preference loads it. A + // `plugin.reload`'s report replaces the record unless a load started after it, or the + // folder couldn't be loaded. + let current = if load.reload { + FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none() + } else { + last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) + }; + if current { + *last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) }; + } + } + report +} + +/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is +/// kept as the folder last loaded unless a load started after this one. +fn load_folder_now(s: &mut Session, folder: &str) -> Value { + let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let mut load = start_folder(s, folder, Some(token)); + load.reload = true; + #[cfg(test)] + if let Some(between) = BEFORE_RELOAD_INSTALLS.take() { + between(); + } + s.finish_plugin_load(PluginLoad::Folder(load)) +} + +/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no +/// loader thread to load it. +#[cfg(test)] +pub(crate) fn folder_found_no_thread() { + if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + record.4 = true; + } } fn reload(s: &mut Session, p: &Value) -> Result { @@ -1376,11 +1642,12 @@ fn reload(s: &mut Session, p: &Value) -> Result { if folder.is_empty() { return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder")); } - let report = load_folder(s, &folder); + // Loads started earlier install first, so this one's plug-ins replace theirs. + s.finish_plugin_loads(); + let report = load_folder_now(s, &folder); if let Some(e) = report.get("error").and_then(Value::as_str) { return Err(EngineError::Other(e.to_string())); } - *FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone())); Ok(report) } @@ -1429,7 +1696,7 @@ fn shown_report(mut report: Value) -> Value { } fn list(_: &mut Session, _: &Value) -> Result { - let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone())); + let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone())); let disabled: Vec = safe_mode::disabled().iter().map(shown_item).collect(); Ok( json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), @@ -1437,13 +1704,15 @@ fn list(_: &mut Session, _: &Value) -> Result { } /// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch, -/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet. +/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet. fn safe_mode_state(_: &mut Session, _: &Value) -> Result { + let pending: Vec = safe_mode::previous().iter().map(shown_item).collect(); Ok(json!({ "active": safe_mode::active(), "source": safe_mode::source().map(safe_mode::Source::name), "disabled": safe_mode::disabled().iter().map(shown_item).collect::>(), - "pendingItem": safe_mode::previous().map(|i| shown_item(&i)), + "pendingItem": pending.first(), + "pendingItems": pending, })) } @@ -1582,7 +1851,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1654,7 +1923,7 @@ pub fn specs() -> Vec { "Safe Mode", [], None, - "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command", + "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command", always, safe_mode_state ), diff --git a/crates/engine/src/cmd/plugin/context.rs b/crates/engine/src/cmd/plugin/context.rs new file mode 100644 index 0000000000..2078828eba --- /dev/null +++ b/crates/engine/src/cmd/plugin/context.rs @@ -0,0 +1,147 @@ +//! A plug-in run's document context (`_context.document`): the parts of the active document its +//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or +//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an +//! object, a file path or a link target. + +use serde_json::{Value, json}; +use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind}; +use vectorcraft_plugins::ContextSection; + +use super::super::{Result, bad}; +use crate::DocState; + +/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds. +pub const MAX_CONTEXT_ITEMS: usize = 10_000; + +/// Most bytes the rows of a document context take as JSON. +pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024; + +/// Instructions each row costs: they come off the run's instruction budget. +pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000; + +/// A document context, and the rows it holds. +pub(super) struct DocumentContext { + pub value: Value, + pub items: usize, +} + +/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key +/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or +/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case. +pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result { + let d = &st.doc; + let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() }; + let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect()); + let mut items = 0; + for s in sections { + items += match s { + ContextSection::Settings => 0, + ContextSection::Artboards => d.artboards.len(), + ContextSection::Layers => layers.len(), + ContextSection::Swatches => swatches().count(), + }; + } + let too_large = || { + bad( + c, + format!( + "the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes" + ), + ) + }; + if items > MAX_CONTEXT_ITEMS { + return Err(too_large()); + } + let mut bytes = 0usize; + let mut row = |v: Value| -> Result { + bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1)); + if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) } + }; + let active = active_artboard(st); + let mut out = json!({"revision": st.revision}); + for s in sections { + let value = match s { + ContextSection::Settings => { + let board = active.and_then(|i| d.artboards.get(i)); + row(json!({ + "name": st.title(), + "colorMode": match d.color_mode { + ColorMode::Rgb => "rgb", + ColorMode::Cmyk => "cmyk", + }, + "units": d.units.label(), + "width": board.map(|a| a.rect.width()), + "height": board.map(|a| a.rect.height()), + "bleed": d.setup.bleed, + "rasterEffectsPpi": d.raster_ppi(), + "activeArtboard": board.map(|a| a.id), + }))? + } + ContextSection::Artboards => { + let rows = d.artboards.iter().enumerate().map(|(i, a)| { + let r = a.rect; + row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)})) + }); + Value::Array(rows.collect::>()?) + } + ContextSection::Layers => { + let rows = layers.iter().map(|l| { + let n = l.node; + row(json!({ + "id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(), + "visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(), + "sublayers": l.sublayers, "current": st.active_layer == Some(n.id), + })) + }); + Value::Array(rows.collect::>()?) + } + ContextSection::Swatches => { + let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g))); + Value::Array(rows.collect::>()?) + } + }; + out[s.name()] = value; + } + Ok(DocumentContext { value: out, items }) +} + +/// Is `n` a layer or sublayer? +fn is_layer(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { .. }) +} + +/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the +/// node's own name and flags. +struct LayerRow<'a> { + node: &'a Node, + /// Its parent layer's id; `None` for a top-level layer. + parent: Option, + /// 0 for a top-level layer, 1 for its sublayers, and so on. + depth: usize, + color: LayerColor, + template: bool, + /// The sublayers it holds directly. + sublayers: usize, +} + +/// Every layer and sublayer of `d`, depth first in document order (bottom first within each +/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's. +fn layer_rows(d: &vectorcraft_doc::Document) -> Vec> { + let mut out = Vec::new(); + let mut stack: Vec<(&Node, Option, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect(); + while let Some((node, parent, depth)) = stack.pop() { + let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue }; + let sublayers = children.iter().filter(|c| is_layer(c)).count(); + stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1))); + out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers }); + } + out +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first; `None` with no artboards. +fn active_artboard(st: &DocState) -> Option { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0)) +} diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 8137e561cf..9916ba569c 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result { Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?], None => d.swatch_groups.iter().collect(), }; - // The built-in Registration swatch lists after None, as the panel shows it. - let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count(); - let (specials, rest) = d.swatches.split_at(none); - let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest); - let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None)); - let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name)))); - let swatches: Vec = ungrouped.chain(grouped).collect(); + let swatches: Vec = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect(); let groups: Vec = groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::>()})).collect(); Ok(json!({"swatches": swatches, "groups": groups})) } +/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is +/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None, +/// as the panel shows it), then those of `groups`. +pub(super) fn listed_swatches<'a>( + d: &'a Document, + ungrouped: bool, + groups: Vec<&'a SwatchGroup>, +) -> impl Iterator)> + 'a { + let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count(); + let (specials, rest) = d.swatches.split_at(none); + let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest); + let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None)); + let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str())))); + ungrouped.chain(grouped) +} + fn swatch_sort(s: &mut Session, _: &Value) -> Result { s.edit("Sort Swatches", |d, _| { // [None] and other bracketed specials stay first, like the reference app. diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 69194eba00..1346dc40c5 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool { find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id)) } +/// Does command `id` first install the plug-ins still loading on other threads +/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands +/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]); +/// queries that only read, and view commands, go ahead while the plug-ins load. +pub fn waits_for_plugin_loads(id: &str) -> bool { + id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id) +} + /// Journaled commands that write a file and change nothing in the document: with an object of a /// dynamic symbol instance's art selected, they read the instance as queries do /// ([`crate::Session::execute`]). diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c96bf81084..8f67677684 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -227,6 +227,14 @@ fn with_gate_reads_exempt(exempt: bool, f: impl FnOnce() -> T) -> T { f() } +/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined). +fn resolved(scope: Option, process: Option<&Arc>) -> Scope { + scope.unwrap_or_else(|| match process { + Some(r) => Scope::Confined(r.clone()), + None => Scope::Unconfined, + }) +} + /// This thread's scope, with the gate of the script command it runs, to carry to work it hands to /// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] @@ -238,6 +246,15 @@ impl ScopeHandle { Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } + /// [`ScopeHandle::capture`], except that a thread with no scope of its own takes the process's + /// roots as they are now ([`confine_process`]): work captured before the process is confined + /// stays unconfined on the thread that runs it, as it would have been had it run on the calling + /// thread at once. + pub fn capture_now() -> Self { + let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get()); + Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; @@ -1327,6 +1344,24 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// Work captured with [`ScopeHandle::capture_now`] before the process is confined stays + /// unconfined when it runs after; work captured with [`ScopeHandle::capture`] is confined then. + #[test] + fn a_scope_captured_now_stays_unconfined_after_the_process_is_confined() { + if !crate::tests::in_own_process("file_access::tests::a_scope_captured_now_stays_unconfined_after_the_process_is_confined") { + return; + } + let (base, roots) = folders("captured-process"); + let outside = s(base.join("outside/secret.svg")); + let (now, plain) = std::thread::spawn(|| (ScopeHandle::capture_now(), ScopeHandle::capture())).join().unwrap(); + assert!(confine_process(roots)); + assert_eq!(now.run(|| check_read(&outside)), Ok(()), "captured now, before the process was confined"); + assert!(plain.run(|| check_read(&outside)).is_err(), "captured plainly, run after the process was confined"); + let later = std::thread::spawn(ScopeHandle::capture_now).join().unwrap(); + assert!(later.run(|| check_read(&outside)).is_err(), "captured now, after the process was confined"); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn device_names() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9863cf7b76..5560c26fcc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -203,6 +203,11 @@ pub struct Session { /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, + /// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]). + plugin_loads: std::collections::VecDeque, + /// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call + /// that starts them ([`Session::load_plugins_in_background`]). + plugin_loads_in_background: bool, /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, @@ -453,7 +458,7 @@ mod session; pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; -pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; +pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1ed2654d51..770cfd2bea 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -106,6 +106,8 @@ impl Session { profile_dir: None, color_settings_file: None, plugin_dir: None, + plugin_loads: Default::default(), + plugin_loads_in_background: false, scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index f87d37691f..1a130d5cbc 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -59,6 +59,13 @@ impl Session { /// Execute a command by id. This is THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + // Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are + // installed before a plug-in command, its own commands included, and before a command that + // may edit, as they would have been before the window showed; a step of a batch waits for + // the plug-ins an earlier step started loading. + if self.plugins_loading() && crate::waits_for_plugin_loads(id) { + self.finish_plugin_loads(); + } self.revealing(|s| s.execute_unwatched(id, params)) } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 7afab7426d..a48795b910 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -35,14 +35,16 @@ //! The files are untrusted input like any other: sizes and counts are capped, a file that does not //! parse is skipped with a log record, and every write is atomic. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::SystemTime; +use serde_json::Value; use vectorcraft_pdf::{APP, PdfPreset, builtin_preset}; +use vectorcraft_plugins::loader::{Job, Loads}; use vectorcraft_plugins::permissions::GrantToken; use vectorcraft_plugins::safe_mode; use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; @@ -170,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec { files } +/// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it. +fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> { + let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; + let mut files: Vec<_> = entries + .filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext))) + .filter_map(|p| { + let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?; + match m.modified() { + Ok(t) => Some((p, (m.len(), t))), + Err(e) => { + log::warn!("skipping the stored plug-in {}: {e}", p.display()); + None + } + } + }) + .collect(); + files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase())); + files.truncate(MAX_STORE_FILES); + files +} + /// The content of `path` when it is at most `max` bytes; the file is never read past `max`. pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; @@ -187,11 +212,243 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { Ok(bytes) } +/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and +/// [`Session::finish_plugin_loads`] install. +pub(crate) enum PluginLoad { + /// The plug-in store's ([`Session::load_stored_plugins`]). + Stored(StoredLoad), + /// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]). + Folder(crate::cmd::plugin::FolderPending), +} + +impl PluginLoad { + /// Starts the modules loading, unless they started already. + fn start(&mut self) { + match self { + PluginLoad::Stored(load) => load.loads.begin(), + PluginLoad::Folder(load) => load.start(), + } + } + + /// The installs and removals it checks its modules against (`None`: a folder that couldn't be + /// listed, or one ended already). + fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> { + match self { + PluginLoad::Stored(load) => Some(&load.changes), + PluginLoad::Folder(load) => load.changes(), + } + } + + /// [`PluginLoad::changes`], to adopt an earlier load's. + fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> { + match self { + PluginLoad::Stored(load) => Some(&mut load.changes), + PluginLoad::Folder(load) => load.changes_mut(), + } + } + + /// Whether every module has been installed or skipped. + fn done(&self) -> bool { + match self { + PluginLoad::Stored(load) => load.next == load.files.len() && load.rest.is_empty(), + PluginLoad::Folder(load) => load.done(), + } + } + + /// Whether something can be installed or ended now, without waiting. + pub(crate) fn ready(&mut self) -> bool { + match self { + PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(), + PluginLoad::Folder(load) => load.ready(), + } + } + + /// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]). + fn wait(&mut self) { + self.start(); + match self { + PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(), + PluginLoad::Stored(_) => {} + PluginLoad::Folder(load) => load.wait(), + } + } + + /// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it + /// [`PluginLoad::done`] with what it installed. + fn cancel(&mut self) { + match self { + PluginLoad::Stored(load) => { + load.loads = Loads::deferred(Vec::new()); + load.loaded.clear(); + load.next = load.files.len(); + load.rest.clear(); + } + PluginLoad::Folder(load) => load.cancel(), + } + } + + /// Whether installing it takes the plug-in store's own turn, making the store folder (a + /// folder's plug-ins keep their settings and cache there), rather than one that goes ahead + /// without a store folder. + fn creates_store(&self) -> bool { + matches!(self, PluginLoad::Folder(_)) + } +} + +/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be +/// read). +type StoredFile = (PathBuf, Option); + +/// The stored plug-ins loading from the plug-in store `dir`. +pub(crate) struct StoredLoad { + dir: PathBuf, + /// The files listed, in file-name order. + files: Vec, + loads: Loads, + /// Outcomes taken from `loads` and not installed yet, in order. + loaded: VecDeque>, + /// The next file to install. + next: usize, + /// The store's grants this load removed, by id, because the module stored for the id lists no + /// permissions: a later file holding a module with that id that the grant covers still loads, + /// and the grant goes back to the store. + retired: BTreeMap, + /// Installs and removals elsewhere since the store was listed, which a module loaded before + /// them doesn't undo. + changes: vectorcraft_plugins::registry::LoadChanges, + /// The files listed after `files`, in file-name order, with their stamps from when the store was + /// listed, that wait for `files` to load because what is left of [`MAX_PLUGIN_STORE`] may not + /// cover them until the reads that fail give back what they didn't read + /// ([`list_stored_plugins`]). + rest: VecDeque, + /// What is left of [`MAX_PLUGIN_STORE`]: the listed length of each file in `files` is taken + /// from it, and what a failed read didn't read of it is given back. + left: u64, +} + +/// What a stored plug-in's load read of its file, at most its listed length, and the module. +pub(crate) struct StoredRead { + read: u64, + plugin: vectorcraft_plugins::Result, +} + +/// Tests: what runs before a stored module is read, given its path. +#[cfg(test)] +type StoredHook = Arc; + +/// Tests: runs on the worker thread before the stored module at the path it is given is read. +#[cfg(test)] +pub(crate) static BEFORE_STORED_LOAD: Mutex> = Mutex::new(None); + +#[cfg(test)] +fn before_stored_load(path: &Path) { + let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(path); + } +} + +/// Tests: runs on the worker thread once the stored module at the path it is given has loaded, and +/// before its file is read again to check that it still holds the module. +#[cfg(test)] +pub(crate) static AFTER_STORED_LOAD: Mutex> = Mutex::new(None); + +#[cfg(test)] +fn after_stored_load(path: &Path) { + let hook = AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(path); + } +} + +/// Why a stored plug-in whose file changed between its listing and its install is skipped. +const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded"; + +#[cfg(test)] +thread_local! { + /// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]). + pub(crate) static PLUGIN_STORE_BUDGET: std::cell::Cell = const { std::cell::Cell::new(MAX_PLUGIN_STORE) }; +} + +/// The stored plug-in bytes one store's load reads, all files together ([`MAX_PLUGIN_STORE`]). +#[cfg(not(test))] +fn plugin_store_budget() -> u64 { + MAX_PLUGIN_STORE +} + +#[cfg(test)] +fn plugin_store_budget() -> u64 { + PLUGIN_STORE_BUDGET.with(std::cell::Cell::get) +} + /// What a file over its cap is told (a detail after the file's name, in the log or an error). fn too_large(max: u64) -> String { format!("larger than {max} bytes") } +/// Takes the stored plug-in files at the front of `rest`, in order, each one's listed length taken +/// from `left` → those files, and the jobs that load them, each reading no more than that length. +/// It stops at the first file that `left` doesn't cover but would if files taken before it failed to +/// read and gave back what they took; that file and the ones after it stay in `rest`. A file that +/// `left` wouldn't cover even then is skipped with a log record, and once nothing can be given back +/// to a used-up `left` the rest are, as when the files were read one after the other. +fn list_stored_plugins(rest: &mut VecDeque, left: &mut u64) -> (Vec, Vec>) { + let limits = vectorcraft_plugins::Limits::default(); + let mut files = Vec::new(); + let mut jobs = Vec::new(); + // What the files taken so far took of `left`. + let mut taken = 0; + while let Some((path, stamp)) = rest.pop_front() { + let len = stamp.flatten().map_or(0, |(len, _)| len); + let most = *left + taken; + if most == 0 { + log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); + rest.clear(); + break; + } + if len > most { + log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most)); + continue; + } + // An empty file too waits once `left` is used up. + if len > *left || *left == 0 { + rest.push_front((path, stamp)); + break; + } + *left -= len; + taken += len; + let item = safe_mode::Item::file(path.display().to_string()); + let (read, limits) = (path.clone(), limits.clone()); + jobs.push(Job::new(Some(item), move || { + #[cfg(test)] + before_stored_load(&read); + let mut bytes = vec![]; + let got = std::fs::File::open(&read).and_then(|f| f.take(len + 1).read_to_end(&mut bytes)); + let plugin = match got { + Err(e) => Err(vectorcraft_plugins::Error::Io(e.to_string())), + Ok(_) if bytes.len() as u64 > len => Err(vectorcraft_plugins::Error::Io(too_large(len))), + Ok(_) => vectorcraft_plugins::Plugin::load(&bytes, limits), + }; + #[cfg(test)] + after_stored_load(&read); + // A file replaced while its module loaded, by one that kept its length and modified time, + // is told apart by its content: it is read again here, within the load's deadline. The + // install then skips a file whose stamp changed since. + let plugin = plugin.and_then(|p| { + if std::fs::File::open(&read).is_ok_and(|f| holds(f, &bytes)) { + Ok(p) + } else { + Err(vectorcraft_plugins::Error::Io(CHANGED_WHILE_LOADING.into())) + } + }); + // A read that failed part way read what `bytes` holds. + Ok(StoredRead { read: (bytes.len() as u64).min(len), plugin }) + })); + files.push((path, stamp)); + } + (files, jobs) +} + /// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a /// large file is not read into memory. pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool { @@ -230,8 +487,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> { /// replaced or removed, so that every window locks the same file. #[cfg(not(target_arch = "wasm32"))] fn lock_store(dir: &Path) -> std::io::Result { - std::fs::create_dir_all(dir)?; - let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?; + let file = open_store_lock(dir)?; match file.try_lock() { Ok(()) => return Ok(file), Err(std::fs::TryLockError::WouldBlock) => {} @@ -245,6 +501,30 @@ fn lock_store(dir: &Path) -> std::io::Result { Ok(file) } +/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked. +#[cfg(not(target_arch = "wasm32"))] +fn open_store_lock(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK)) +} + +/// [`lock_store`] without waiting: `None` while another window or process holds the lock. +#[cfg(not(target_arch = "wasm32"))] +fn try_lock_store(dir: &Path) -> std::io::Result> { + let file = open_store_lock(dir)?; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(e)) => Err(e), + } +} + +/// The browser has no folders to keep anything in. +#[cfg(target_arch = "wasm32")] +fn try_lock_store(_: &Path) -> std::io::Result> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { @@ -445,78 +725,188 @@ impl Session { } /// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there - /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). + /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads + /// still running from an earlier call are finished first. pub fn attach_plugin_store(&mut self, dir: PathBuf) { - let path = dir.join(DISABLED_FILE); + self.finish_plugin_loads(); self.plugin_dir = Some(dir); - // A `plugin.install` in another session or process writes the store before this reads it. - let _held = crate::cmd::plugin::hold_plugin_changes(); - let turn = self.plugin_store_turn_for_load(); - let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); - safe_mode::set_disabled(disabled); - self.load_stored_plugins_in(&turn); + self.start_stored_plugins(true); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user - /// disabled (matched by file name, which is made from the id). The launch marker names each - /// file while it loads. A module that doesn't load, and one that lists permissions the grants - /// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and - /// stays in the folder with its grant. A grant for an id whose stored module lists no - /// permissions is forgotten; one that can't be removed from the grants file doesn't count for - /// any session in the process attached to the folder until the file can be written for the id - /// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it - /// ([`Session::plugin_store_turn_for_load`]). + /// disabled (matched by file name, which is made from the id). The modules load on worker + /// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order + /// their loads finish in; the launch marker names each file while it loads. A module that + /// doesn't load (its load panicked or didn't finish in time included), one that changed or + /// went away while it loaded, and one that lists permissions the grants there don't grant that + /// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with + /// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that + /// can't be removed from the grants file doesn't count for any session in the process attached + /// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]). + /// The folder is listed, and what loaded is installed and the folder changed, in turns on it + /// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With + /// [`Session::load_plugins_in_background`] on, this returns while the modules load. pub fn load_stored_plugins(&mut self) { - if self.plugin_dir.is_none() || safe_mode::active() { - return; - } - // A `plugin.install` in another session or process writes the store before this reads it. - let _held = crate::cmd::plugin::hold_plugin_changes(); - let turn = self.plugin_store_turn_for_load(); - self.load_stored_plugins_in(&turn); + self.start_stored_plugins(false); } - /// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`] - /// is held. - fn load_stored_plugins_in(&mut self, turn: &StoreTurn) { + /// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the + /// folder ([`DISABLED_FILE`]). + fn start_stored_plugins(&mut self, disabled: bool) { let Some(dir) = self.plugin_dir.clone() else { return }; + // A `plugin.install` in another session or process writes the store before this lists it. + let held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_store_turn_for_load(); + if disabled { + let path = dir.join(DISABLED_FILE); + let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); + safe_mode::set_disabled(saved); + } if safe_mode::active() { return; } - let grants = self.counted_grants(&dir); - let limits = vectorcraft_plugins::Limits::default(); - let mut left = MAX_PLUGIN_STORE; - let mut asks_nothing = BTreeSet::new(); - for path in list_files(&dir, PLUGIN_EXT) { - if left == 0 { - log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); - break; - } + let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64; + let mut rest = VecDeque::new(); + let disabled: BTreeSet = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect(); + for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) { let item = safe_mode::Item::file(path.display().to_string()); - let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()); - let by_id = safe_mode::skipped_ids().iter().any(|id| stem.as_deref() == Some(file_stem(id).as_str())); + let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref())); if safe_mode::skipped(&item) || by_id { log::info!("skipping the stored plug-in {}: disabled", path.display()); + } else if stamp.0 > module { + log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module)); + } else { + rest.push_back((path, Some(Some(stamp)))); + } + } + let mut left = plugin_store_budget(); + let (files, jobs) = list_stored_plugins(&mut rest, &mut left); + // A change made after the listing, while `held` no longer stops one, is made elsewhere. + let mut changes = vectorcraft_plugins::registry::LoadChanges::default(); + changes.start(); + // The modules load after the turn, once the loads queued before them are done. + drop((turn, held)); + let load = + StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left }; + self.queue_plugin_load(PluginLoad::Stored(load)); + } + + /// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the + /// first module still loading, without waiting ([`Session::load_stored_plugins`]), while + /// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held. + fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) { + if load.next == load.files.len() && !load.rest.is_empty() { + // Every file listed so far is installed or skipped, and the reads that failed gave + // back their length: the files waiting for them are listed now. + let (files, jobs) = list_stored_plugins(&mut load.rest, &mut load.left); + load.files = files; + load.next = 0; + load.loads = Loads::start(jobs); + return; + } + load.loaded.extend(load.loads.ready()); + if load.loaded.is_empty() { + return; + } + let dir = load.dir.clone(); + // The grants file is read once for this turn. `written` holds whether it names each id + // whose grant this turn removed or put back. + let file = read_grants(&dir); + let mut grants = self.counted( + &dir, + match &file { + Ok(file) => file.grants.clone(), + Err(e) => { + log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); + BTreeMap::new() + } + }, + ); + let mut written: BTreeMap = BTreeMap::new(); + let named = |written: &BTreeMap, id: &str| { + written.get(id).copied().unwrap_or_else(|| match &file { + Ok(file) => file.names(id), + Err(e) => e.unread, + }) + }; + while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) { + load.next += 1; + load.loads.release(1); + // What a read that failed didn't read takes nothing from the total. A load that panicked + // or passed its deadline gives nothing back. + let loaded = loaded.and_then(|r| { + load.left += stamp.flatten().map_or(0, |(len, _)| len).saturating_sub(r.read); + r.plugin + }); + // The worker read the file again once its module loaded ([`list_stored_plugins`]); one + // whose stamp changed since then is skipped too. + if file_stamp(path).ok() != *stamp { + log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display()); continue; } - let token = safe_mode::loading(&item); - let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| { - left -= bytes.len() as u64; - vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string()) - }); - safe_mode::loaded(token); match loaded { + Ok(plugin) if load.changes.superseded(plugin.id()) => { + log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED); + } // Only this store's grants count: one given elsewhere in the process doesn't let a // module stored here load. Ok(plugin) if plugin.manifest().asks_permissions() => { let m = plugin.manifest(); - match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) { + let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned(); + // A grant given for the id since this load removed one, in another window or + // process, is kept. + let back = (!grants.contains_key(&m.id) && !named(&written, &m.id)) + .then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned()) + .flatten(); + match stored.or(back.clone()) { Some(g) => { - asks_nothing.remove(&m.id); - vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); - vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn)); - if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + // A grant this load removed for an earlier file with the id goes back. When + // it can't be written back, the module isn't installed: the store doesn't + // grant it, so it wouldn't load at the next launch either. + if back.is_some() { + if !self.store_grant_in(turn, &m.id, Some(g.clone())) { + log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display()); + continue; + } + load.retired.remove(&m.id); + written.insert(m.id.clone(), true); + grants.insert(m.id.clone(), g.clone()); + } + let id = m.id.clone(); + let token = GrantToken::from_engine_grants_file(g.clone()); + // The storage is made before the plug-ins are held: making it reads the store. + let storage = plugin_storage(Some(&dir), &id, turn); + let attach = || vectorcraft_plugins::registry::set_storage(&id, storage); + // The id is checked for a change elsewhere again while the plug-ins are held. + let installed = match vectorcraft_plugins::registry::install_for_load( + plugin.with_source(path.display().to_string()), + &load.changes, + Some(token), + attach, + ) { + Ok(Some(p)) => { + load.changes.installed(&p); + true + } + Ok(None) => { + log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED); + false + } + Err(e) => { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + false + } + }; + // A grant put back for a module that didn't install is removed again, so the + // store doesn't grant those bytes at the next launch. + if back.is_some() && !installed { + if self.store_grant_in(turn, &id, None) { + written.insert(id.clone(), false); + grants.remove(&id); + load.retired.insert(id, g); + } else { + log::warn!("couldn't remove the grant put back for the stored plug-in {}", path.display()); + } } } None => { @@ -525,29 +915,213 @@ impl Session { } } Ok(plugin) => { - asks_nothing.insert(plugin.id().to_string()); - vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn)); - if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + let id = plugin.id().to_string(); + // The storage is made before the plug-ins are held: making it reads the store. + let storage = plugin_storage(Some(&dir), &id, turn); + let attach = || vectorcraft_plugins::registry::set_storage(&id, storage); + // The id is checked for a change elsewhere again while the plug-ins are held. + let p = match vectorcraft_plugins::registry::install_for_load( + plugin.with_source(path.display().to_string()), + &load.changes, + None, + attach, + ) { + Ok(Some(p)) => p, + Ok(None) => { + log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED); + continue; + } + Err(e) => { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + continue; + } + }; + load.changes.installed(&p); + // In the same turn: the grants for the id stop counting, the process's and the + // store's, so no session sees the earlier module as approved. A module installed + // in its place meanwhile keeps the process's grant recorded for it. + vectorcraft_plugins::registry::revoke_if_installed(&id, p.serial()); + if let Some(g) = grants.remove(&id) { + load.retired.insert(id.clone(), g); + } + if named(&written, &id) { + let writes = self.grant_writes(); + if self.store_grant_in(turn, &id, None) { + written.insert(id.clone(), false); + } else if self.holds_plugin_grant(&id) { + self.ignore_stored_grant(&id, writes); + } } } Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } } - let kept = read_grants(&dir); - for id in &asks_nothing { - vectorcraft_plugins::registry::revoke(id); - let named = match &kept { - Ok(file) => file.names(id), - Err(e) => e.unread, + } + + /// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after + /// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`], + /// preferences that set the folder): the app turns it on for its launch so that its window + /// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its + /// frames go by, and turns it off once the launch's loads have started. Off (the default), + /// those calls return once what loaded is installed, the loads still running from before + /// included. + pub fn load_plugins_in_background(&mut self, on: bool) { + self.plugin_loads_in_background = on; + } + + /// Installs what the plug-in loads have loaded so far, in the order the loads started and each + /// load's file-name order, up to the first module still loading, without waiting → whether + /// some are still loading. A load starts once the loads before it are done. When another + /// session or process is changing the plug-ins or the store, nothing installs until a later + /// call. + pub fn poll_plugin_loads(&mut self) -> bool { + while let Some(mut next) = self.plugin_loads.pop_front() { + next.start(); + if !next.ready() { + self.plugin_loads.push_front(next); + return true; + } + let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else { + self.plugin_loads.push_front(next); + return true; }; - if named { - let writes = self.grant_writes(); - if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) { - self.ignore_stored_grant(id, writes); + self.install_plugin_load(&mut next, &turn); + if !next.done() { + self.plugin_loads.push_front(next); + return true; + } + self.end_plugin_load(next, &turn); + drop((turn, held)); + } + false + } + + /// Waits for every plug-in load still running and installs what they loaded, in the order the + /// loads started. Plug-in commands, and commands that may edit, call it first + /// ([`Session::execute`]). + pub fn finish_plugin_loads(&mut self) { + while let Some(next) = self.plugin_loads.pop_front() { + self.finish_plugin_load(next); + } + } + + /// Ends the plug-in loads still running without installing more of what they load: the app + /// calls it as it quits. Modules not started are dropped, and the ones running are given until + /// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load + /// then ends as one that finished does for what it installed; a folder's end saves the disabled + /// list only when the store's turn can be taken without waiting. + pub fn cancel_plugin_loads(&mut self) { + while let Some(mut load) = self.plugin_loads.pop_front() { + load.cancel(); + // A stored load's grants were settled as each module installed: its end writes nothing. + if !load.creates_store() { + self.end_plugin_load(load, &StoreTurn::unheld()); + continue; + } + // Another session changing the plug-ins isn't waited for either: the folder's load then + // ends without the store's turn, so the grants of what it installed are still forgotten + // and the store isn't written. + let Some(held) = crate::cmd::plugin::try_hold_plugin_changes() else { + self.end_plugin_load(load, &StoreTurn::unheld()); + continue; + }; + // A store another window or process is using isn't waited for: the turn then isn't + // held, and the folder's end writes nothing to the store. + let turn = match self.plugin_dir.as_deref().map(try_lock_store) { + Some(Ok(Some(file))) => StoreTurn { lock: Some(file) }, + _ => StoreTurn::unheld(), + }; + self.end_plugin_load(load, &turn); + drop((turn, held)); + } + } + + /// Waits for `load`'s modules and installs them as they load, in turns on the store, then + /// ends it → its report (a folder's; `null` for the stored plug-ins). + pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value { + load.start(); + loop { + load.wait(); + let held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_install_turn(load.creates_store()); + self.install_plugin_load(&mut load, &turn); + if load.done() { + let report = self.end_plugin_load(load, &turn); + drop((turn, held)); + return report; + } + } + } + + /// A turn on the store for installing what a load loaded, taken after + /// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn + /// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store + /// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead + /// unheld. + fn plugin_install_turn(&self, create: bool) -> StoreTurn { + if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() } + } + + /// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without + /// waiting: `None` while another session holds the one or another window or process the other. + fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> { + let held = crate::cmd::plugin::try_hold_plugin_changes()?; + let turn = match self.plugin_dir.as_deref() { + Some(dir) if create || dir.is_dir() => match try_lock_store(dir) { + Ok(Some(file)) => StoreTurn { lock: Some(file) }, + Ok(None) => return None, + Err(e) => { + log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display()); + StoreTurn::unheld() + } + }, + _ => StoreTurn::unheld(), + }; + Some((held, turn)) + } + + /// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]). + pub fn plugins_loading(&self) -> bool { + !self.plugin_loads.is_empty() + } + + /// Keeps `load` to install after the loads started before it; without + /// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded. + pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) { + self.plugin_loads.push_back(load); + // The first load starts now; one queued after it starts once those before it are done. + if let [only] = self.plugin_loads.make_contiguous() { + only.start(); + } + if !self.plugin_loads_in_background { + self.finish_plugin_loads(); + } + } + + /// Installs what `load` has loaded so far, without waiting, in `turn`. + fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) { + match load { + PluginLoad::Stored(load) => self.install_stored_plugins(load, turn), + PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn), + } + } + + /// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's). + fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value { + // The loads queued after it count what it installed as their own: one of theirs replaces + // it, as it would have with the loads run one after the other. + if let Some(ended) = load.changes() { + for later in &mut self.plugin_loads { + if let Some(changes) = later.changes_mut() { + changes.adopt(ended); } } } + match load { + // A stored load's grants were settled as each module installed. + PluginLoad::Stored(_) => Value::Null, + PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn), + } } /// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or @@ -659,8 +1233,17 @@ impl Session { /// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked /// out on each call, so a path whose link now leads elsewhere is matched with where it leads. fn counted_grants(&self, dir: &Path) -> BTreeMap { + self.counted(dir, stored_grants(dir)) + } + + /// `grants`, read from the plug-in store `dir`, without those the process doesn't count for + /// that folder ([`Session::counted_grants`]). + fn counted( + &self, + dir: &Path, + mut grants: BTreeMap, + ) -> BTreeMap { let key = plugin_store_key(dir); - let mut grants = stored_grants(dir); let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()); for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) { grants.remove(id); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 4ef15c4b98..a2868201ce 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2241,6 +2241,550 @@ fn installed_plugins_are_kept_in_the_store() { assert!(vectorcraft_plugins::registry::get(id).is_none()); } +/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`]. +static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// A stored module's load waits on its worker thread until the test lets it go +/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped. +struct HeldLoad { + _lock: std::sync::MutexGuard<'static, ()>, + entered: std::sync::Arc, + go: std::sync::Arc, + gave_up: std::sync::Arc, +} + +impl HeldLoad { + /// Holds the load of the file at `path`. A load the test never lets go gives up after a + /// million yields (so a test of code that waits for it ends) and says so in `gave_up`. + fn new(path: std::path::PathBuf) -> HeldLoad { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone()); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| { + if p != path { + return; + } + e.store(true, Ordering::SeqCst); + if !(0..1_000_000).any(|_| { + std::thread::yield_now(); + g.load(Ordering::SeqCst) + }) { + q.store(true, Ordering::SeqCst); + } + })); + HeldLoad { _lock: lock, entered, go, gave_up } + } + + fn entered(&self) -> bool { + self.entered.load(std::sync::atomic::Ordering::SeqCst) + } + + fn release(&self) { + self.go.store(true, std::sync::atomic::Ordering::SeqCst); + } + + fn gave_up(&self) -> bool { + self.gave_up.load(std::sync::atomic::Ordering::SeqCst) + } +} + +impl Drop for HeldLoad { + fn drop(&mut self) { + self.release(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } +} + +/// A store holding the module of a filter `id` in `.wasm`. +fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) { + let folder = crate::tests_links::Folder::new(name); + let path = folder.0.join(format!("{id}.wasm")); + std::fs::create_dir_all(&folder.0).unwrap(); + std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + (folder, path) +} + +/// With loads in the background, attaching a plug-in store returns while a stored module is +/// still loading: the plug-in installs once its load is done, at the next plug-in command. +#[test] +fn a_store_attached_with_background_loads_returns_before_its_plugins_load() { + let id = "test.engine.background"; + let (folder, path) = store_with("plugin-background", id); + let held = HeldLoad::new(path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + let returned_while_loading = !held.gave_up(); + while !held.entered() { + std::thread::yield_now(); + } + assert!(returned_while_loading, "attaching the store waited for the module to load"); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done"); + assert!(s.poll_plugin_loads(), "still loading"); + held.release(); + let listed = run(&mut s, "plugin.list", json!({})); + assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}"); + assert!(!s.poll_plugin_loads()); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read +/// together: a module after 512 MiB of them still installs. +#[cfg(unix)] +#[test] +fn unreadable_stored_files_leave_the_store_budget_to_the_others() { + use std::os::unix::fs::PermissionsExt; + let id = "test.engine.budget.after"; + let (folder, _) = store_with("plugin-budget-unreadable", id); + let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64; + let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file)) + .map(|n| { + // Sparse files sorted before the module, each as long as a module may be. + let path = folder.0.join(format!("a{n:03}.wasm")); + std::fs::File::create(&path).unwrap().set_len(per_file).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + path + }) + .collect(); + // A process that may read any file (root) opens them all: nothing to check. + if std::fs::File::open(&locked[0]).is_ok() { + return; + } + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).is_some(); + for path in &locked { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + assert!(installed, "the files that couldn't be opened used up the store's bytes"); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// A stored file whose read fails on the worker thread gives back what it took of the bytes the +/// stored plug-ins may read together, so a module after files that use them all up still installs. +#[test] +fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() { + struct Unhook { + _lock: std::sync::MutexGuard<'static, ()>, + } + impl Drop for Unhook { + fn drop(&mut self) { + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + } + let id = "test.engine.budget.failed"; + let (folder, module) = store_with("plugin-budget-failed", id); + let len = std::fs::metadata(&module).unwrap().len(); + // Files sorted before the module, as long as it, that use up the bytes this test's store may read. + for n in 0..4 { + std::fs::write(folder.0.join(format!("a{n:03}.wasm")), vec![0; len as usize]).unwrap(); + } + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(4 * len)); + let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) }; + // Each of those files goes away as its load starts, so its read fails. + let dir = folder.0.clone(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| { + if p.parent() == Some(dir.as_path()) && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('a')) { + let _ = std::fs::remove_file(p); + } + })); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).is_some(); + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE)); + assert!(installed, "the files whose reads failed used up the store's bytes"); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// A stored file replaced after its module loaded, by one of the same length with the same modified +/// time, is skipped: its content no longer holds the module. That holds for a file modified moments +/// ago and for one modified an hour ago. +#[test] +fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() { + struct Unhook { + _lock: std::sync::MutexGuard<'static, ()>, + } + impl Drop for Unhook { + fn drop(&mut self) { + *crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + } + let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) }; + let hour = std::time::Duration::from_secs(3600); + // A modified time ahead of the clock counts as moments ago however long the test takes. + for (n, modified) in [std::time::SystemTime::now() + hour, std::time::SystemTime::now() - hour].into_iter().enumerate() { + let id = format!("test.engine.background.replaced{n}"); + let (folder, path) = store_with(&format!("plugin-background-replaced{n}"), &id); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap(); + let replaced = path.clone(); + // Set once the file holds other bytes with the old stamp, so the case reaches the check. + let rewritten = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let done = rewritten.clone(); + *crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| { + if p == replaced { + let mut bytes = std::fs::read(p).unwrap(); + bytes.reverse(); + std::fs::write(p, &bytes).unwrap(); + std::fs::File::options().write(true).open(p).unwrap().set_modified(modified).unwrap(); + done.store(true, std::sync::atomic::Ordering::SeqCst); + } + })); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let installed = vectorcraft_plugins::registry::remove(&id); + assert!(rewritten.load(std::sync::atomic::Ordering::SeqCst), "the file was not replaced while it loaded ({n})"); + assert!(!installed, "the module installed from a file that no longer holds it ({n})"); + } +} + +/// While a session loads the plug-ins folder in the background, another session's `plugin.list` +/// reports the folder as loading; once the load installs, it reports what loaded. +#[test] +fn another_session_lists_a_folder_still_loading_as_loading() { + // Other tests' `prefs.set` replaces the folder last loaded, which the process keeps. + if !in_own_process("another_session_lists_a_folder_still_loading_as_loading") { + return; + } + let id = "test.engine.listedloading"; + let (folder, _) = store_with("plugin-listed-loading", id); + let mut background = session(); + background.load_plugins_in_background(true); + run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}})); + let mut other = session(); + let listed = run(&mut other, "plugin.list", json!({})); + assert_eq!(listed["folder"]["loading"], true, "{listed}"); + background.finish_plugin_loads(); + let listed = run(&mut other, "plugin.list", json!({})); + assert!(vectorcraft_plugins::registry::remove(id)); + assert_eq!(listed["folder"]["loaded"], json!([id]), "{listed}"); + assert!(listed["folder"].get("loading").is_none(), "{listed}"); +} + +/// A `plugin.reload` doesn't replace the record of a folder load that started after it: once that +/// load installs, `plugin.list` reports its folder. +#[test] +fn a_reload_keeps_the_record_of_a_folder_load_started_after_it() { + // Other tests' `prefs.set` replaces the folder last loaded, which the process keeps. + if !in_own_process("a_reload_keeps_the_record_of_a_folder_load_started_after_it") { + return; + } + let (reloaded, later) = ("test.engine.reloadorder.reloaded", "test.engine.reloadorder.later"); + let (reload_folder, _) = store_with("plugin-reload-order-reloaded", reloaded); + let (later_folder, _) = store_with("plugin-reload-order-later", later); + let other = std::rc::Rc::new(std::cell::RefCell::new(None)); + let started = other.clone(); + let path = later_folder.0.display().to_string(); + // Another session sets the plug-ins folder while the reload loads. + crate::cmd::plugin::BEFORE_RELOAD_INSTALLS.set(Some(Box::new(move || { + let mut background = session(); + background.load_plugins_in_background(true); + run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}})); + *started.borrow_mut() = Some(background); + }))); + let mut s = session(); + run(&mut s, "plugin.reload", json!({"path": reload_folder.0.display().to_string()})); + let mut background = other.borrow_mut().take().expect("the other session's load started while the reload loaded"); + background.finish_plugin_loads(); + let listed = run(&mut s, "plugin.list", json!({})); + assert!(vectorcraft_plugins::registry::remove(reloaded) && vectorcraft_plugins::registry::remove(later)); + assert_eq!(listed["folder"]["loaded"], json!([later]), "{listed}"); +} + +/// The plug-ins folder already loaded isn't loaded again when the preferences are applied, unless +/// a file in it found no loader thread to load it: then it is. +#[test] +fn a_folder_in_which_a_file_found_no_thread_is_loaded_again() { + if !in_own_process("a_folder_in_which_a_file_found_no_thread_is_loaded_again") { + return; + } + let id = "test.engine.nothread"; + let (folder, _) = store_with("plugin-no-thread", id); + let mut s = session(); + run(&mut s, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}})); + assert!(vectorcraft_plugins::registry::remove(id), "installed from the folder"); + crate::cmd::plugin::sync_prefs(&mut s); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "a folder already loaded was loaded again"); + crate::cmd::plugin::folder_found_no_thread(); + crate::cmd::plugin::sync_prefs(&mut s); + assert!(vectorcraft_plugins::registry::remove(id), "the folder wasn't loaded again"); +} + +/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored +/// plug-in with a module of the same id once it loads, as it does when the loads run one after the +/// other: what an earlier load of the session installed doesn't count as a change made elsewhere. +#[test] +fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.queued.same"; + let (store, stored) = store_with("plugin-queued-store", id); + let (folder, from_folder) = store_with("plugin-queued-folder", id); + let held = HeldLoad::new(stored); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(store.0.clone()); + while !held.entered() { + std::thread::yield_now(); + } + s.prefs.plugins_folder = folder.0.display().to_string(); + crate::cmd::plugin::sync_prefs(&mut s); + held.release(); + s.finish_plugin_loads(); + let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); + assert!(vectorcraft_plugins::registry::remove(id)); + assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one"); +} + +/// A query that only reads runs while the stored plug-ins load in the background, and doesn't +/// wait for them; a plug-in command does. +#[test] +fn a_query_runs_while_the_plugins_load() { + let id = "test.engine.background.query"; + let (folder, path) = store_with("plugin-background-query", id); + let held = HeldLoad::new(path); + let mut s = session(); + run(&mut s, "file.new", json!({})); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while !held.entered() { + std::thread::yield_now(); + } + run(&mut s, "document.info", json!({})); + let waited = held.gave_up() || !s.plugins_loading(); + held.release(); + assert!(!waited, "document.info waited for the plug-ins to load"); + assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove` +/// take, so another session's plug-in changes don't wait for them. +#[test] +fn stored_plugins_load_without_holding_the_plugin_changes_lock() { + let id = "test.engine.unlocked"; + let (folder, path) = store_with("plugin-unlocked", id); + let held = HeldLoad::new(path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while !held.entered() && !held.gave_up() { + std::thread::yield_now(); + } + // Other tests take the lock for a moment; the load holding it would hold it throughout (a + // tenth of the yields the held load waits before it gives up). + let free = (0..100_000).any(|_| { + std::thread::yield_now(); + crate::cmd::plugin::plugin_changes_free() + }); + // A load that gave up waiting no longer holds anything, so a free lock then shows nothing. + let gave_up = held.gave_up(); + held.release(); + s.finish_plugin_loads(); + assert!(!gave_up, "the held load gave up before the lock was looked at"); + assert!(free, "the lock was held while the module loaded"); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// Loads canceled as the app quits still end for what they installed: a stored module listing no +/// permissions that installed before a later one finished loading has its id's grant forgotten, +/// in the process and in `grants.json`, and the module still loading doesn't install. +#[test] +fn canceled_loads_forget_the_grants_of_what_they_installed() { + use vectorcraft_plugins::permissions::sha256_hex; + let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b"); + let (folder, _) = store_with("plugin-cancel", first); + let held_path = folder.0.join(format!("{later}.wasm")); + std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let empty = json!({"objects": []}); + let approved = asking(first, r#"["doc.read"]"#, &empty); + let grants = folder.0.join("grants.json"); + let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]); + std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap(); + let held = HeldLoad::new(held_path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() { + s.poll_plugin_loads(); + std::thread::yield_now(); + } + assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + s.cancel_plugin_loads(); + // The file goes once it holds no grant. + let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); + assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}"); + assert!(vectorcraft_plugins::registry::granted(first).is_none()); + assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install"); + assert!(!s.plugins_loading()); + drop(held); + assert!(vectorcraft_plugins::registry::remove(first)); +} + +/// The grants for a stored module that lists no permissions stop counting when it installs, in the +/// same turn, while a later module of the load is still loading. +#[test] +fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() { + use vectorcraft_plugins::permissions::sha256_hex; + let (first, later) = ("test.engine.retire.a", "test.engine.retire.b"); + let (folder, _) = store_with("plugin-retire", first); + let held_path = folder.0.join(format!("{later}.wasm")); + std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let empty = json!({"objects": []}); + let approved = asking(first, r#"["doc.read"]"#, &empty); + let grants = folder.0.join("grants.json"); + let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]); + std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap(); + let held = HeldLoad::new(held_path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() { + s.poll_plugin_loads(); + std::thread::yield_now(); + } + assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + assert!(s.plugins_loading(), "the second module is still loading"); + let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); + assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}"); + assert!(vectorcraft_plugins::registry::granted(first).is_none()); + drop(held); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::remove(first)); + assert!(vectorcraft_plugins::registry::remove(later)); +} + +/// A grant the load removed for a stored module without permissions doesn't go back for a later +/// file with the same id when another window or process granted the id since: that grant stays, and +/// the later module, which it doesn't cover, is skipped. +#[test] +fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { + use vectorcraft_plugins::permissions::sha256_hex; + let id = "test.engine.retire.kept"; + let folder = crate::tests_links::Folder::new("plugin-retire-kept"); + std::fs::create_dir_all(&folder.0).unwrap(); + let empty = json!({"objects": []}); + let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm")); + std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let approved = asking(id, r#"["doc.read"]"#, &empty); + std::fs::write(&later, &approved).unwrap(); + let grants = folder.0.join("grants.json"); + let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap(); + std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap(); + let held = HeldLoad::new(later.clone()); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while vectorcraft_plugins::registry::get(id).is_none() && !held.gave_up() { + s.poll_plugin_loads(); + std::thread::yield_now(); + } + // Another process grants the id for another module while the later file loads. + let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"path": triangle()}]})); + std::fs::write(&grants, entry(sha256_hex(&other))).unwrap(); + drop(held); + s.finish_plugin_loads(); + let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); + assert!(vectorcraft_plugins::registry::remove(id)); + let listed: Vec = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap(); + assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed"); + assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::>(), [json!(sha256_hex(&other))], "{listed:?}"); +} + +/// A grant the load removed for a stored module without permissions that can't be written back for +/// a later file with the same id leaves that file's module uninstalled: the store doesn't grant it. +#[test] +fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() { + use vectorcraft_plugins::permissions::sha256_hex; + let id = "test.engine.retire.unwritten"; + let folder = crate::tests_links::Folder::new("plugin-retire-unwritten"); + std::fs::create_dir_all(&folder.0).unwrap(); + let empty = json!({"objects": []}); + let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm")); + std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let approved = asking(id, r#"["doc.read"]"#, &empty); + std::fs::write(&later, &approved).unwrap(); + let grants = folder.0.join("grants.json"); + std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + // The first write removes the grant; the second, which puts it back, finds a folder where the + // file goes and fails. + let blocked = grants.clone(); + crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { + crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { + let _ = std::fs::remove_file(&blocked); + std::fs::create_dir_all(&blocked).unwrap(); + }))); + }))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + crate::store::AFTER_GRANTS_READ.set(None); + let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); + let _ = std::fs::remove_dir(&grants); + assert!(vectorcraft_plugins::registry::remove(id)); + assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed without its grant in the store"); +} + +/// A grant the load put back for a later stored file with the same id is removed again when that +/// file's module doesn't install because the id was installed elsewhere meanwhile: the store doesn't +/// grant bytes that weren't installed. +#[test] +fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { + use vectorcraft_plugins::permissions::sha256_hex; + let id = "test.engine.retire.superseded"; + let folder = crate::tests_links::Folder::new("plugin-retire-superseded"); + std::fs::create_dir_all(&folder.0).unwrap(); + let empty = json!({"objects": []}); + let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm")); + let plain = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + std::fs::write(&first, &plain).unwrap(); + let approved = asking(id, r#"["doc.read"]"#, &empty); + std::fs::write(&later, &approved).unwrap(); + let grants = folder.0.join("grants.json"); + std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + // The first write removes the grant; while the second puts it back, the id is installed + // elsewhere. + crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { + crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { + vectorcraft_plugins::registry::install_bytes(&plain).unwrap(); + }))); + }))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + crate::store::AFTER_GRANTS_READ.set(None); + let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); + assert!(vectorcraft_plugins::registry::remove(id)); + // A grants file that went away holds no grant; one still there must read as a list. + let listed: Vec = match std::fs::read(&grants) { + Ok(b) => serde_json::from_slice(&b).unwrap(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![], + Err(e) => panic!("the grants file could not be read: {e}"), + }; + assert_eq!(source, None, "the later module replaced the one installed elsewhere"); + assert!(listed.iter().all(|e| e["id"] != id), "the grant put back stayed in the store: {listed:?}"); +} + +/// A session that waits for its loads and sets the plug-ins folder another session is still +/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set` +/// returns, and the other session's load, when it installs, counts the same module as loaded. +#[test] +fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.sharedfolder"; + let (folder, _) = store_with("plugin-shared-folder", id); + let path = folder.0.display().to_string(); + let mut background = session(); + background.load_plugins_in_background(true); + run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}})); + assert!(background.plugins_loading(), "the folder loads in the background"); + let mut waits = session(); + run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}})); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed"); + let report = run(&mut background, "plugin.list", json!({})); + assert!(!background.plugins_loading()); + assert!(vectorcraft_plugins::registry::remove(id), "{report}"); +} + /// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in". fn heavy(id: &str, steps: u64) -> Vec { let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#); @@ -4130,6 +4674,168 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// The manifest of a filter at `api` 3 with id `id` that asks for the document information +/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or +/// nothing). +fn context_manifest(id: &str, context: &str, rest: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"context":{context}{rest}}}"#) +} + +/// Installs `src` granted `doc.read` and `doc.write`, in place of any module with its id. +fn install_reading(s: &mut Session, src: &str) -> Value { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) +} + +/// A filter at `api` 3 whose manifest lists `context` is given the document's settings, artboards, +/// layers and swatches in `_context.document` with nothing selected: plain values, hidden and +/// locked layers with their flags, the active artboard and the current layer marked, and the +/// document's name without its folder. A filter that doesn't list `context` is given none, and one +/// that lists it without `doc.read` or below `api` 3 doesn't install. +#[test] +fn an_unselected_filter_reads_the_document_context_it_asks_for() { + use cmd::plugin::FilterRun; + let mut s = session(); + run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 100, "height": 50})); + let hidden = run(&mut s, "layer.new", json!({"name": "Hidden", "visible": false}))["id"].as_u64().unwrap(); + let locked = run(&mut s, "layer.newSublayer", json!({"parent": hidden, "name": "Locked", "locked": true}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": locked})); + run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true})); + run(&mut s, "select.none", json!({})); + s.doc_mut().unwrap().path = Some("/private/folder/Poster.vectorcraft".into()); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let id = "test.engine.context"; + let all = r#"["settings","artboards","layers","swatches"]"#; + let installed = install_reading(&mut s, &tpl::returning(&context_manifest(id, all, ""), r#"{"objects":[]}"#)); + assert_eq!(installed["context"], json!(["settings", "artboards", "layers", "swatches"])); + let swatches = run(&mut s, "swatch.list", json!({}))["swatches"].clone(); + assert!(s.doc().unwrap().selection.objects.is_empty()); + let given = FilterRun::prepare(&s, &json!({"id": id})).unwrap().params_json()["_context"]["document"].clone(); + let st = s.doc().unwrap(); + let d = &st.doc; + assert_eq!(given["revision"], json!(st.revision)); + let board = &d.artboards[1]; + let settings = json!({ + "name": "Poster.vectorcraft", "colorMode": "rgb", "units": d.units.label(), "width": board.rect.width(), + "height": board.rect.height(), "bleed": d.setup.bleed, "rasterEffectsPpi": d.raster_ppi(), "activeArtboard": second, + }); + assert_eq!(given["settings"], settings); + let boards: Vec = d + .artboards + .iter() + .enumerate() + .map(|(i, a)| json!({"id": a.id, "index": i, "name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1], "active": i == 1})) + .collect(); + assert_eq!((boards.len(), &given["artboards"]), (2, &json!(boards))); + let layers = given["layers"].as_array().unwrap(); + let rows: Vec<(String, u64, bool, bool, bool)> = layers + .iter() + .map(|l| { + (l["name"].as_str().unwrap().to_string(), l["depth"].as_u64().unwrap(), l["visible"] == true, l["locked"] == true, l["current"] == true) + }) + .collect(); + let bottom = d.layers[0].display_name(); + assert_eq!(rows, [(bottom, 0, true, false, false), ("Hidden".into(), 0, false, false, false), ("Locked".into(), 1, true, true, true)]); + assert_eq!((&layers[0]["parentId"], &layers[1]["sublayers"], &layers[2]["parentId"]), (&Value::Null, &json!(1), &json!(hidden))); + assert_eq!((&layers[1]["id"], &layers[2]["id"]), (&json!(hidden), &json!(locked))); + assert_eq!(given["swatches"], swatches, "as swatch.list lists them"); + assert!(given["swatches"].as_array().unwrap().iter().any(|w| w["name"] == "Tone" && w["global"] == true)); + assert!(!given.to_string().contains("/private/folder"), "no path: {given}"); + // Only the sections asked for. + let some = "test.engine.context.some"; + install_reading(&mut s, &tpl::returning(&context_manifest(some, r#"["layers"]"#, ""), r#"{"objects":[]}"#)); + let given = FilterRun::prepare(&s, &json!({"id": some})).unwrap().params_json()["_context"]["document"].clone(); + let keys: Vec<&String> = given.as_object().unwrap().keys().collect(); + assert_eq!(keys.len(), 2, "{keys:?}"); + assert!(given.get("layers").is_some() && given.get("revision").is_some()); + // A filter without `context` is given none. + let legacy = "test.engine.context.legacy"; + install_reading(&mut s, &tpl::returning(&tpl::manifest(legacy, "filter", "{}"), r#"{"objects":[]}"#)); + assert!(FilterRun::prepare(&s, &json!({"id": legacy})).unwrap().params_json()["_context"].get("document").is_none()); + // Without `doc.read`, or below `api` 3, it doesn't install. + let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`"; + for manifest in [ + format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}}"#), + format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}}"#), + ] { + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})).unwrap_err(); + assert!(e.to_string().contains(needs), "{manifest}: {e}"); + } +} + +/// A plug-in command, of a filter or of a live effect, whose manifest lists `context` is given it +/// too, with nothing selected. +#[test] +fn a_plugin_command_reads_the_document_context_without_a_selection() { + let mut s = session(); + let made = json!({"objects": [{"path": triangle(), "name": "Saw layers"}]}).to_string(); + for (id, kind, permissions) in [ + ("test.engine.context.command", "filter", r#"["doc.read","doc.write"]"#), + ("test.engine.context.effectcommand", "effect", r#"["doc.read","doc.write","effect.render"]"#), + ] { + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"{kind}","api":3,"permissions":{permissions},"context":["layers"],"commands":[{{"id":"look","label":"Look"}}]}}"# + ); + let src = tpl::when_given_else(&manifest, tpl::Given::Params, r#""layers":["#, &made, r#"{"objects":[]}"#); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + let grant: Vec = serde_json::from_str(permissions).unwrap(); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true})); + run(&mut s, "select.none", json!({})); + let ids = run(&mut s, &format!("plugin.{id}.look"), json!({}))["ids"].clone(); + assert_eq!(ids.as_array().map(Vec::len), Some(1), "{kind}: {ids}"); + assert_eq!(node(&s, NodeId(ids[0].as_u64().unwrap())).name.as_deref(), Some("Saw layers"), "{kind}"); + } +} + +/// A document context holds at most [`cmd::plugin::MAX_CONTEXT_ITEMS`] rows in +/// [`cmd::plugin::MAX_CONTEXT_BYTES`] bytes: past either, the run fails before the plug-in starts, +/// with the document and undo history as they were. Each row comes off the run's instruction +/// budget. +#[test] +fn the_document_context_is_capped_and_its_rows_cost_instructions() { + use cmd::plugin::{CONTEXT_FUEL_PER_ITEM, FilterRun, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS}; + let mut s = session(); + let id = "test.engine.context.cap"; + install_reading(&mut s, &tpl::returning(&context_manifest(id, r#"["swatches"]"#, ""), r#"{"objects":[]}"#)); + let p = json!({"id": id}); + let listed = run(&mut s, "swatch.list", json!({}))["swatches"].as_array().unwrap().len(); + let add = |s: &mut Session, n: usize| { + s.edit("Set up", |d, _| { + let base = d.swatches.last().unwrap().clone(); + let at = d.swatches.len(); + d.swatches.extend((at..at + n).map(|i| vectorcraft_color::Swatch { name: format!("Many {i}"), ..base.clone() })); + Ok(()) + }) + .unwrap(); + }; + add(&mut s, MAX_CONTEXT_ITEMS - listed); + let full = FilterRun::prepare(&s, &p).unwrap(); + assert_eq!(full.params_json()["_context"]["document"]["swatches"].as_array().map(Vec::len), Some(MAX_CONTEXT_ITEMS)); + assert_eq!(full.limits().fuel_base, full.plugin().limits().fuel_base - MAX_CONTEXT_ITEMS as u64 * CONTEXT_FUEL_PER_ITEM); + let too_large = "the document information the plug-in asks for is too large to hand over"; + add(&mut s, 1); + let refused = |s: &mut Session| { + let Err(e) = FilterRun::prepare(s, &p) else { panic!("prepared past the cap") }; + assert!(e.to_string().contains(too_large), "{e}"); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains(too_large), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo)); + }; + refused(&mut s); + // A few rows past the byte cap are refused as well. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + s.edit("Set up", |d, _| { + d.swatches.last_mut().unwrap().name = "n".repeat(MAX_CONTEXT_BYTES); + Ok(()) + }) + .unwrap(); + refused(&mut s); +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 3cb7dc96af..fa0c2e35cc 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -326,8 +326,45 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert_eq!(modern["log"], json!([2]), "{modern}"); let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); - let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); - assert_eq!(legacy["log"], json!([3]), "{legacy}"); + let fourth = "#targetengine kept\nvc.log(k2 + kept);\ntry { eval('let x = 1'); } catch (e) { vc.log(e.name); }"; + let legacy = s.execute("script.run", &path(&write("fourth.jsx", fourth))).unwrap(); + assert_eq!(legacy["log"], json!([3, "SyntaxError"]), "{legacy}"); + // `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made. + let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);"; + let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap(); + assert_eq!(r["log"], json!([7, 9, "function"]), "{r}"); + let kept = s + .execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));"))) + .unwrap(); + assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); + let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015-objects"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "var k = 'b';\nvar a = 1;\nvar o = { a, [k + 1]: 2, m() { return 3; }, f: () => 4 };\n\ + vc.log(o.a + o.b1 + o.m() + o.f());\nvc.log(o.m.name + ',' + o.f.name + ',' + o.f.bind().name + ',' + Math.max.name);\n"; + let r = s.execute("script.run", &path(&write("objects.js", modern))).unwrap(); + assert_eq!(r["log"], json!([10, "m,f,bound f,max"]), "{r}"); + for (name, text) in [("short.jsx", "var a = 1; var o = { a };"), ("computed.jsx", "var o = { ['b']: 1 };"), ("method.jsx", "var o = { m() {} };")] + { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + let legacy = s.execute("script.run", &path(&write("names.jsx", "var f = function () {};\nvc.log(f.hasOwnProperty('name'));"))).unwrap(); + assert_eq!(legacy["log"], json!([false]), "{legacy}"); + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 653ed92752..446d441fc4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1463,6 +1463,16 @@ impl Session { } } + /// The object a click of the active tool at `p` with `mods` would act on + /// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None + /// while Cmd lends a selection tool to the press ([`Self::lent_tool_at`]). + pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option { + if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool_at(p, &mods, view).is_some() { + return None; + } + self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods)) + } + pub fn tool_options(&self) -> Value { self.tool.options() } diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index e2ff510468..437c5f904e 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -988,6 +988,77 @@ proptest! { vectorcraft_plugins::registry::revoke("fuzz.inputs"); } + /// Manifests with a hostile `context` (unknown, repeated and oddly cased sections, long lists, + /// junk of every type) with any `api`, kind and permissions parse to an error or to a filter, or + /// a live effect with commands, at `api` 3 or later asking for each section once, whose + /// `permissions` list `doc.read` so that installing it asks for approval. One that installs and + /// echoes its input, with or without a selection, leaves the document as it was, and it still + /// renders. + #[test] + fn hostile_manifest_context_never_crash( + kind in prop::sample::select(vec!["filter", "effect", "exporter"]), + commands in any::(), + names in prop::collection::vec(prop::sample::select(vec!["settings", "artboards", "layers", "swatches", "Layers", "document", ""]), 0..6), + long in prop::option::weighted(0.1, 5usize..300), + context in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]), + api in prop_oneof![2 => Just(json!(3)), 1 => Just(json!(2)), 1 => Just(json!(4)), 1 => arb_junk()], + permissions in prop_oneof![Just(Value::Null), Just(json!([])), Just(json!(["doc.read", "doc.write"])), Just(json!(["doc.read", "effect.render"])), Just(json!(["doc.write"]))], + select in any::(), + ) { + let mut m = json!({"id": "fuzz.context", "name": "Context", "kind": kind, "api": api}); + if kind == "exporter" { + m["extensions"] = json!(["fz"]); + } + if commands { + m["commands"] = json!([{"id": "c", "label": "C"}]); + } + if !permissions.is_null() { + m["permissions"] = permissions; + } + m["context"] = match (context, long) { + (_, Some(n)) => json!(vec!["layers"; n]), + (Some(Value::Null) | None, None) => json!(names), + (Some(junk), None) => junk, + }; + let text = m.to_string(); + let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes())); + let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?; + if let Ok(man) = &parsed { + let sections = man.context_sections(); + prop_assert_eq!(sections.len(), man.context.len(), "{}", text); + prop_assert!(sections.iter().enumerate().all(|(i, k)| !sections[..i].contains(k)), "{}", text); + let kind_ok = man.kind == Kind::Filter || (man.kind == Kind::Effect && !man.commands.is_empty()); + prop_assert!(sections.is_empty() || (kind_ok && man.api >= 3), "{}", text); + let reads = man.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == "doc.read")); + prop_assert!(sections.is_empty() || (man.asks_permissions() && reads), "{}", text); + } + let mut s = rich_session(); + s.allow_plugin_grants_from_requests(); + let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap(); + let data = vectorcraft_format::base64_encode(&module); + let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]); + let before = s.doc().unwrap().doc.clone(); + let r = catch_quiet(|| { + let installed = s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok(); + let _ = s.execute(if select { "select.all" } else { "select.none" }, &json!({})); + let ran = installed && s.execute("plugin.run", &json!({"id": "fuzz.context"})).is_ok(); + if installed { + for c in s.commands().into_iter().filter(|c| c.id.starts_with("plugin.fuzz.context.")) { + let _ = s.execute(c.id, &json!({})); + } + } + (installed, ran) + }); + let (installed, ran) = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; + prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); + if ran { + prop_assert!(s.doc().unwrap().doc.layers == before.layers, "an echo changed the document: {}", text); + } + renders(&s, &text)?; + vectorcraft_plugins::registry::remove("fuzz.context"); + vectorcraft_plugins::registry::revoke("fuzz.context"); + } + /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, /// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of /// its memory runs to an output, or on a small budget to its instruction budget, never a panic; diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 6cb261dd0f..9e23624a31 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -90,7 +90,7 @@ fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_l let list = s.execute("plugin.list", &json!({})).unwrap(); assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x"))); let state = s.execute("plugin.safeMode", &json!({})).unwrap(); - assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()})); + assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "pendingItems": [], "disabled": state["disabled"].clone()})); assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1)); s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap(); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 92cf258da2..e255258f34 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -82,15 +82,19 @@ pub enum PropertyKey { Ident(String), String(Vec), Number(f64), + /// `[expression]` with [`crate::Options::es2015`]: the key is the expression's value. + Computed(ExprId), } impl PropertyKey { - /// The key as the string a property is stored under (a number through ToString). + /// The key as the string a property is stored under (a number through ToString); empty for + /// a computed key, whose string is known only at run time. pub fn to_utf16(&self) -> Vec { match self { PropertyKey::Ident(name) => name.encode_utf16().collect(), PropertyKey::String(s) => s.clone(), PropertyKey::Number(n) => crate::number::to_string(*n).encode_utf16().collect(), + PropertyKey::Computed(_) => Vec::new(), } } } @@ -100,6 +104,8 @@ pub enum PropertyValue { Init(ExprId), Get(FunctionId), Set(FunctionId), + /// A method (`m() {…}`, ECMA-262 2015 section 14.3). + Method(FunctionId), } #[derive(Clone, Debug, PartialEq)] @@ -109,6 +115,18 @@ pub struct Property { pub span: Span, } +impl Property { + /// The property is `__proto__: value`, which sets the new object's prototype (ECMA-262 2015 + /// section B.3.1): a data property with a name written out, not computed and not shorthand + /// (`{__proto__}`, whose value starts where the property does). + pub fn is_proto_setter(&self, ast: &Ast) -> bool { + let PropertyValue::Init(value) = self.value else { return false }; + ast.expr_span(value).start != self.span.start + && matches!(self.key, PropertyKey::Ident(_) | PropertyKey::String(_)) + && self.key.to_utf16().into_iter().eq("__proto__".encode_utf16()) + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Expr { This, @@ -277,20 +295,33 @@ pub enum XmlNamePart { Computed(ExprId), } +/// What a declaration, a parameter or a catch clause binds: a name, or with +/// [`crate::Options::es2015`] a destructuring pattern (ECMA-262 11th edition, section 13.3.3). +/// +/// A pattern is an [`Expr::Array`] or an [`Expr::Object`] whose targets are [`Expr::Ident`] +/// names or nested patterns; an [`Expr::Assign`] with no operator gives a target its default +/// value, and an [`Expr::Spread`] as the last element of an array pattern is its rest element. +#[derive(Clone, Debug, PartialEq)] +pub enum Binding { + Name(Name), + Pattern(ExprId), +} + #[derive(Clone, Debug, PartialEq)] pub struct VarDecl { - pub name: Name, + pub target: Binding, pub init: Option, } -/// What a `for (… in …)` statement assigns each property name to. +/// What a `for (… in …)` or `for (… of …)` statement assigns each property name or value to. #[derive(Clone, Debug, PartialEq)] pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), + /// An assignment target, or with [`crate::Options::es2015`] an assignment pattern. Expr(ExprId), /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. - Lexical(LexKind, Name), + Lexical(LexKind, Binding), } #[derive(Clone, Debug, PartialEq)] @@ -312,7 +343,7 @@ pub struct SwitchCase { #[derive(Clone, Debug, PartialEq)] pub struct CatchClause { - pub param: Name, + pub param: Binding, pub body: Vec, } @@ -351,6 +382,12 @@ pub enum Stmt { body: StmtId, each: bool, }, + /// `for (… of …)` with [`crate::Options::es2015`] (ECMA-262 11th edition, section 13.7.5). + ForOf { + target: ForInTarget, + iterable: ExprId, + body: StmtId, + }, /// `default xml namespace = expression;`. DefaultXmlNamespace(ExprId), Continue(Option), @@ -385,6 +422,8 @@ pub enum FunctionKind { Setter, /// An arrow function; one with an expression body has a body of one `return` statement. Arrow, + /// A method in an object literal. + Method, } #[derive(Clone, Debug, PartialEq)] @@ -392,11 +431,11 @@ pub struct Function { pub kind: FunctionKind, pub name: Option, /// The parameters before a rest parameter. - pub params: Vec, + pub params: Vec, /// Each parameter's default value, in the order of `params` (empty when none has one). pub defaults: Vec>, - /// The rest parameter (`...name`). - pub rest: Option, + /// The rest parameter (`...name` or `...[pattern]`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -405,9 +444,9 @@ pub struct Function { } impl Function { - /// The parameters are plain names: no default value and no rest parameter. + /// The parameters are plain names: no pattern, no default value and no rest parameter. pub fn simple_params(&self) -> bool { - self.rest.is_none() && self.defaults.iter().all(Option::is_none) + self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_))) } } @@ -440,6 +479,34 @@ impl Ast { self.functions.get(id.0 as usize) } + /// The names a binding binds, in source order. + pub fn bound_names(&self, binding: &Binding) -> Vec { + match binding { + Binding::Name(n) => vec![n.clone()], + Binding::Pattern(p) => self.pattern_names(*p), + } + } + + /// The names a destructuring pattern binds, in source order, walked without recursion. + pub fn pattern_names(&self, pattern: ExprId) -> Vec { + let mut out = Vec::new(); + let mut work = vec![pattern]; + while let Some(id) = work.pop() { + match self.expr(id) { + Some(Expr::Ident(n)) => out.push(Name { name: n.clone(), span: self.expr_span(id) }), + Some(Expr::Array(elements)) => work.extend(elements.iter().rev().flatten().copied()), + Some(Expr::Object(props)) => work.extend(props.iter().rev().filter_map(|p| match p.value { + PropertyValue::Init(e) => Some(e), + _ => None, + })), + Some(Expr::Assign { target, .. }) => work.push(*target), + Some(Expr::Spread(arg)) => work.push(*arg), + _ => {} + } + } + out + } + /// The expression with any parentheses around it removed. pub fn unparenthesized(&self, mut id: ExprId) -> ExprId { while let Some(Expr::Paren(inner)) = self.expr(id) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..49eeebf9f4 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,7 +3,8 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and +//! the iterators of arrays, strings and `arguments` objects (in `iterator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,16 +13,19 @@ mod array; pub(crate) mod extensions; mod global; +pub(crate) mod iterator; mod json; mod math; mod object; +mod symbol; use std::rc::Rc; use crate::bytecode::{CodeKind, Source}; use crate::compiler::{CompileFail, compile_constructed_function}; use crate::heap::{ - BOUND_ARG_BYTES, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes, + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, + string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; use crate::value::{Str, Value, index_key, number_to_str, to_uint32}; @@ -32,9 +36,30 @@ fn alloc(interp: &mut Interp, class: Class, proto: Option) -> ObjId { /// A built-in function object. pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult { + native_with_prefix(interp, "", name, f, length, kind, constructor) +} + +/// The function of a built-in accessor `name`: `prefix` is `get ` for its getter and `set ` for +/// its setter. +pub(crate) fn accessor_native(interp: &mut Interp, prefix: &'static str, name: &'static str, f: NativeFn, length: u32) -> JsResult { + native_with_prefix(interp, prefix, name, f, length, NativeKind::Plain, false) +} + +fn native_with_prefix( + interp: &mut Interp, + prefix: &'static str, + name: &'static str, + f: NativeFn, + length: u32, + kind: NativeKind, + constructor: bool, +) -> JsResult { let proto = interp.intrinsics.function_proto; - let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name }), Some(proto)); + let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name, prefix }), Some(proto)); interp.define(o, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + if interp.builtin_names { + es2015_native(interp, o, Some(&format!("{prefix}{name}")))?; + } Ok(o) } @@ -44,9 +69,97 @@ pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str let proto = interp.intrinsics.function_proto; let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto)); interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + if interp.builtin_names { + es2015_native(interp, m, Some(name))?; + } interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) } +/// Gives the built-in functions the `name` and `length` of ECMA-262 2015 section 17: each one's +/// `length` becomes configurable, and it gets a `name` that is not writable, not enumerable and +/// configurable: the name it is installed under, with `get ` or `set ` before it for an accessor's +/// function, and `""` for `Function.prototype`. A realm does this once, at the start of its first +/// run with [`crate::Options::es2015`], under the limits set for that run; [`native`] and +/// [`pausable_method`] do it for the functions made after that. The bytes of the new properties +/// are checked against the heap limit first: when they do not fit, nothing changes and the error +/// is returned, and the next run with the option tries again. +pub(crate) fn es2015_names(interp: &mut Interp) -> JsResult<()> { + if interp.builtin_names { + return Ok(()); + } + // Functions no script can reach any more are collected first, so the plan names only the + // ones that stay. + interp.collect_garbage(); + let plan = es2015_name_plan(interp); + let bytes = plan + .iter() + .filter_map(|(_, name)| name.as_ref()) + .map(|name| PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())) + .sum::(); + interp.reserve_heap(bytes)?; + let thrower = interp.intrinsics.throw_type_error; + for (id, name) in plan { + // A function the reservation's collection freed needs no name. + if interp.heap.object(id).is_none() { + continue; + } + if id == thrower { + // %ThrowTypeError% keeps its fixed `length`, and its `name` is fixed too (ECMA-262 + // 2020 section 9.2.9.1). + if name.is_some() { + interp.define(id, key("name"), Prop::Data { value: Value::str(""), flags: 0 })?; + } + } else { + es2015_native(interp, id, name.as_deref())?; + } + } + interp.builtin_names = true; + Ok(()) +} + +/// The built-in functions, each with the `name` [`es2015_names`] gives it, or `None` when it has +/// one already (a script may have defined it). +fn es2015_name_plan(interp: &Interp) -> Vec<(ObjId, Option)> { + let thrower = interp.intrinsics.throw_type_error; + let mut plan = Vec::new(); + for id in interp.heap.object_ids() { + let Some(o) = interp.heap.object(id) else { continue }; + // A function a script made non-extensible (frozen, sealed or locked) keeps its properties + // as they are. + if !o.extensible && id != thrower { + continue; + } + let name = match &o.class { + _ if id == thrower => String::new(), + Class::Function(Func::Native { name, prefix, .. }) => format!("{prefix}{name}"), + Class::Function(Func::Pausable { name, .. }) => (*name).to_string(), + _ => continue, + }; + plan.push((id, (!o.props.contains(&key("name"))).then_some(name))); + } + plan +} + +/// Makes built-in function `f`'s `length` configurable and gives it the `name` `name`, when there +/// is one, unless it has a `name` already. A function that is not extensible keeps its properties +/// as they are. The new property's bytes are checked against the heap limit first, with `f` held +/// as a root. +fn es2015_native(interp: &mut Interp, f: ObjId, name: Option<&str>) -> JsResult<()> { + if !interp.object_mut(f)?.extensible { + return Ok(()); + } + if let Some(Prop::Data { flags, .. }) = interp.object_mut(f)?.props.get_mut(&key("length")) { + *flags |= CONFIGURABLE; + } + let Some(name) = name.filter(|_| !interp.heap.object(f).is_some_and(|o| o.props.contains(&key("name")))) else { return Ok(()) }; + interp.rooted(&[Value::Object(f)], |i| i.reserve_heap(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())))?; + let o = interp.object_mut(f)?; + // `name` comes right after `length`, as the built-ins list them. + o.props.insert_after(&key("length"), key("name"), Prop::Data { value: Value::str(name), flags: CONFIGURABLE }); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())); + Ok(()) +} + pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> { let m = native(interp, name, f, length, NativeKind::Plain, false)?; interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) @@ -83,7 +196,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { interp.intrinsics.object_proto = object_proto; let function_proto = alloc( interp, - Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "" }), + Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "", prefix: "" }), Some(object_proto), ); interp.intrinsics.function_proto = function_proto; @@ -142,6 +255,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::number_builtins::install(interp)?; crate::regexp_builtins::install(interp)?; crate::date_builtins::install(interp)?; + if interp.options.es2015 { + symbol::install(interp, object)?; + iterator::install(interp)?; + } if interp.options.e4x { crate::xml_builtins::install(interp)?; } @@ -370,7 +487,9 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu interp.to_object(&v).map(Value::Object) } -/// `Object.prototype.toString` (section 15.2.4.2). +/// `Object.prototype.toString` (section 15.2.4.2). In a run with [`crate::Options::es2015`], a +/// string `@@toStringTag` takes the place of the class name (ECMA-262 11th edition, section +/// 19.1.3.6). fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { // With `$.localize` on, a localization object gives its text for the current locale. if interp.localization.enabled() @@ -384,6 +503,13 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Value::Null => "Null", _ => { let o = interp.to_object(&this)?; + // The tag's getter can run script that collects, and the object of a primitive is + // reachable from nowhere else. + let tag = interp.rooted(&[Value::Object(o)], |i| i.string_tag_of(o))?; + if let Some(tag) = tag { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); + } interp.heap.object(o).map_or("Object", |o| o.class.name()) } }; @@ -431,9 +557,9 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js } fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -450,9 +576,9 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- @@ -538,15 +664,21 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); // A host function's `length` is an ordinary property a script can set, so it is converted - // to an integer first, as later editions specify. - let target_length = match interp.get_from(target, &key("length"), &this)? { + // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is + // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. + let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some(); + let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined }; + let target_length = match length_value { Value::Number(n) if n.is_nan() => 0.0, Value::Number(n) => n.trunc(), _ => 0.0, }; // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; - interp.reserve_heap(OBJECT_BYTES + 4 * PROP_BYTES + BOUND_ARG_BYTES * bound_args.len())?; + if interp.options.es2015 { + return bind_es2015(interp, target, bound_this, bound_args, length); + } + interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); let f = interp.heap.alloc_object(Object::new(class, Some(proto))); @@ -559,6 +691,44 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J Ok(Value::Object(f)) } +/// The bytes [`Interp::define`] counts for new properties with these names. +fn prop_bytes(names: &[&str]) -> usize { + names.iter().map(|n| PROP_BYTES + string_bytes(n.len())).sum() +} + +/// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section +/// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the +/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps +/// the `caller` and `arguments` that throw, as without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { + let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { + Value::String(s) => s, + _ => Str::from(""), + }; + let name_len = "bound ".len().saturating_add(target_name.len()); + // A rope name is flattened first, with the copy's bytes reserved and its units charged as fuel. + let target_units = crate::string_builtins::flat_charged(interp, &target_name)?; + interp.rooted(&[Value::String(target_name.clone())], |i| { + i.reserve_heap( + OBJECT_BYTES + prop_bytes(&["length", "name", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len), + ) + })?; + crate::string_builtins::charge_units(interp, name_len)?; + let mut units: Vec = "bound ".encode_utf16().collect(); + units.extend_from_slice(&target_units); + let proto = interp.intrinsics.function_proto; + let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); + let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); + interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; + interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; + let thrower = Some(interp.intrinsics.throw_type_error); + for name in ["caller", "arguments"] { + interp.define(f, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?; + } + Ok(Value::Object(f)) +} + /// The global `eval` called indirectly (section 15.1.2.1.1): global code in the global /// environment. fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 3c58fc64a1..62d2e75210 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -235,6 +235,7 @@ impl Source { } Value::String(s) => self.quoted(interp, &s.flat()), Value::Object(id) => self.object(interp, *id), + Value::Symbol(_) => Err(interp.type_error("toSource: a Symbol cannot be written as source")), } } @@ -280,13 +281,18 @@ impl Source { // only, so an array with other properties, an object with another prototype and a property // that is not enumerable are refused. let enumerable = o.props.iter().all(|(_, p)| p.enumerable()); + let has_symbols = o.syms.as_ref().is_some_and(|m| m.len() > 0); let shape = match &o.class { Class::Array { length, .. } - if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => + if o.proto == Some(array_proto) + && enumerable + && !has_symbols + && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => { Some(Err(*length)) } Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), + Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")), Class::Ordinary if o.proto == Some(object_proto) && enumerable => { Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) } diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs new file mode 100644 index 0000000000..b40f979fc0 --- /dev/null +++ b/crates/js/src/builtins/iterator.rs @@ -0,0 +1,230 @@ +//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition, +//! ): `%IteratorPrototype%` (section 25.1.2), +//! `%ArrayIteratorPrototype%` with `Array.prototype.values`, `keys`, `entries` and `@@iterator` +//! (sections 22.1.3 and 22.1.5), `%StringIteratorPrototype%` with `String.prototype[@@iterator]` +//! (sections 21.1.3.29 and 21.1.5), which steps by code point, and the `@@iterator` of every +//! `arguments` object (section 9.4.4). Installed in a realm with [`crate::Options::es2015`] only. +//! +//! An iterator's `next` takes a unit of fuel for each step. An Array Iterator reads its object's +//! `length` at every step, so elements added while it runs are visited, and it lets go of the +//! object once it is done. + +use super::{create_at, data, native, new_array, new_string}; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Interp, JsResult}; +use crate::value::{Str, Value, number_to_str}; + +/// What an Array Iterator gives at each step (section 22.1.5.1). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArrayKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. The object or string is `None` once the iterator is done. +#[derive(Clone)] +pub(crate) enum IterState { + /// [[IteratedObject]], [[ArrayIteratorNextIndex]] and [[ArrayIterationKind]]. + Array { target: Option, next: f64, kind: ArrayKind }, + /// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units. + String { text: Option, pos: usize }, +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let Some(wk) = interp.symbols.well_known.as_ref() else { return Ok(()) }; + let (iterator, to_string_tag) = (wk.iterator.clone(), wk.to_string_tag.clone()); + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + super::symbol::sym_method(interp, iterator_proto, iterator.clone(), "[Symbol.iterator]", return_this, 0, HIDDEN)?; + + let array_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, array_iterator_proto, "next", array_iterator_next, 0)?; + interp.define_sym(array_iterator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Array Iterator"), flags: CONFIGURABLE })?; + + let string_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, string_iterator_proto, "next", string_iterator_next, 0)?; + interp.define_sym(string_iterator_proto, to_string_tag, Prop::Data { value: Value::str("String Iterator"), flags: CONFIGURABLE })?; + + let array_proto = interp.intrinsics.array_proto; + let values = native(interp, "values", array_values, 0, crate::heap::NativeKind::Plain, false)?; + data(interp, array_proto, "values", Value::Object(values), HIDDEN)?; + interp.define_sym(array_proto, iterator.clone(), Prop::Data { value: Value::Object(values), flags: HIDDEN })?; + super::method(interp, array_proto, "keys", array_keys, 0)?; + super::method(interp, array_proto, "entries", array_entries, 0)?; + + let string_proto = interp.intrinsics.string_proto; + super::symbol::sym_method(interp, string_proto, iterator, "[Symbol.iterator]", string_iterator, 0, HIDDEN)?; + + objects.array_iterator_proto = array_iterator_proto; + objects.string_iterator_proto = string_iterator_proto; + objects.array_values = values; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// Gives a new `arguments` object its `@@iterator`, `%ArrayProto_values%` (section 9.4.4.6, +/// step 20, and section 9.4.4.7, step 7), in a realm that has it. +pub(crate) fn define_arguments_iterator(interp: &mut Interp, a: ObjId) -> JsResult<()> { + let (Some(objects), Some(sym)) = (interp.symbols.objects, interp.well_known(|w| &w.iterator)) else { return Ok(()) }; + interp.define_sym(a, sym, Prop::Data { value: Value::Object(objects.array_values), flags: HIDDEN }) +} + +/// `%IteratorPrototype%[@@iterator]()` (section 25.1.2.1): the iterator itself. +fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(this) +} + +/// The bytes of an iterator result: the object and its `value` and `done` properties with their +/// keys, as [`Interp::define`] counts them. +fn iter_result_bytes() -> usize { + OBJECT_BYTES + 2 * PROP_BYTES + string_bytes("value".len()) + string_bytes("done".len()) +} + +/// CreateIterResultObject (section 7.4.7): `{ value, done }`. +fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; + let proto = interp.intrinsics.object_proto; + let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new iterator object with `state`, its target kept reachable while it is made. +fn new_iterator(interp: &mut Interp, proto: ObjId, state: IterState, root: Value) -> JsResult { + interp.rooted(&[root], |i| i.reserve_heap(OBJECT_BYTES))?; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Iterator(Box::new(state)), Some(proto))))) +} + +/// CreateArrayIterator (section 22.1.5.1) for `ToObject(this)`. +fn create_array_iterator(interp: &mut Interp, this: &Value, kind: ArrayKind) -> JsResult { + let o = interp.to_object(this)?; + let Some(proto) = interp.symbols.objects.map(|o| o.array_iterator_proto) else { return Ok(Value::Undefined) }; + new_iterator(interp, proto, IterState::Array { target: Some(o), next: 0.0, kind }, Value::Object(o)) +} + +/// `Array.prototype.values()` (section 22.1.3.32), which is also `Array.prototype[@@iterator]`. +fn array_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Values) +} + +/// `Array.prototype.keys()` (section 22.1.3.16). +fn array_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Keys) +} + +/// `Array.prototype.entries()` (section 22.1.3.4). +fn array_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Entries) +} + +/// `String.prototype[@@iterator]()` (section 21.1.3.29). +fn string_iterator(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if this.is_nullish() { + return Err(interp.type_error("String.prototype[Symbol.iterator] was called on null or undefined")); + } + let s = interp.to_str(&this)?; + let flat = Str::from_rc(crate::string_builtins::flat_charged(interp, &s)?); + let Some(proto) = interp.symbols.objects.map(|o| o.string_iterator_proto) else { return Ok(Value::Undefined) }; + let root = Value::String(flat.clone()); + new_iterator(interp, proto, IterState::String { text: Some(flat), pos: 0 }, root) +} + +/// The state of the iterator `this`, or a `TypeError` naming `what` when `this` is not one. +fn state_of<'a>(interp: &'a mut Interp, this: &Value, string: bool, what: &str) -> JsResult<&'a mut IterState> { + let ok = match this { + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Iterator(s)) => matches!(**s, IterState::String { .. }) == string, + _ => false, + }, + _ => false, + }; + if !ok { + return Err(interp.type_error(&format!("{what}.next was called on a value that is not an {what}"))); + } + match this.as_object().and_then(|o| interp.heap.object_mut(o)).map(|x| &mut x.class) { + Some(Class::Iterator(s)) => Ok(s), + _ => Err(crate::interp::Abrupt::Internal("iterator state went missing".into())), + } +} + +/// ToLength (section 7.1.20). +fn to_length(interp: &mut Interp, v: &Value) -> JsResult { + let n = interp.to_number(v)?; + if n.is_nan() || n <= 0.0 { + return Ok(0.0); + } + Ok(n.trunc().min(9_007_199_254_740_991.0)) +} + +/// `%ArrayIteratorPrototype%.next()` (section 22.1.5.2.1). +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let IterState::Array { target, next, kind } = *state_of(interp, &this, false, "Array Iterator")? else { + return Err(crate::interp::Abrupt::Internal("not an Array Iterator".into())); + }; + interp.use_fuel()?; + let Some(a) = target else { return iter_result(interp, Value::Undefined, true) }; + // Reading `length` and the element can run script that collects, and that script can finish + // the iterator, which then no longer holds the object. + let roots = [this.clone(), Value::Object(a)]; + interp.rooted(&roots, |interp| array_step(interp, &this, a, next, kind)) +} + +/// One step of an Array Iterator over `a` at index `next`, with `this` and `a` kept reachable. +fn array_step(interp: &mut Interp, this: &Value, a: ObjId, next: f64, kind: ArrayKind) -> JsResult { + let len = interp.get_from(a, &key("length"), &Value::Object(a))?; + let len = to_length(interp, &len)?; + if next >= len { + if let IterState::Array { target, .. } = state_of(interp, this, false, "Array Iterator")? { + *target = None; + } + return iter_result(interp, Value::Undefined, true); + } + if let IterState::Array { next: n, .. } = state_of(interp, this, false, "Array Iterator")? { + *n = next + 1.0; + } + let index = Value::Number(next); + let value = match kind { + ArrayKind::Keys => index, + ArrayKind::Values | ArrayKind::Entries => { + let k = number_to_str(next).flat(); + let v = interp.get_from(a, &k, &Value::Object(a))?; + if kind == ArrayKind::Values { + v + } else { + let pair = interp.rooted(std::slice::from_ref(&v), |i| new_array(i, 0))?; + interp.rooted(&[Value::Object(pair), v.clone()], |i| { + create_at(i, pair, 0.0, index)?; + create_at(i, pair, 1.0, v.clone()) + })?; + Value::Object(pair) + } + } + }; + iter_result(interp, value, false) +} + +/// `%StringIteratorPrototype%.next()` (section 21.1.5.2.1): the next code point, a surrogate +/// pair kept together and a lone surrogate given alone. +fn string_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + interp.use_fuel()?; + let state = state_of(interp, &this, true, "String Iterator")?; + let IterState::String { text, pos } = state else { return Err(crate::interp::Abrupt::Internal("not a String Iterator".into())) }; + let Some(s) = text.as_ref() else { return iter_result(interp, Value::Undefined, true) }; + let units = s.flat(); + let Some(&first) = units.get(*pos) else { + *text = None; + return iter_result(interp, Value::Undefined, true); + }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(*pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let width = if pair { 2 } else { 1 }; + let piece = units.get(*pos..*pos + width).map(<[u16]>::to_vec).unwrap_or_default(); + *pos += width; + interp.rooted(std::slice::from_ref(&this), |interp| { + let v = new_string(interp, piece)?; + iter_result(interp, v, false) + }) +} diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..e01a47b085 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -556,7 +556,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K } } Ok(match v { - Value::Undefined => Item::Skip, + Value::Undefined | Value::Symbol(_) => Item::Skip, Value::Object(_) if interp.is_callable(&v) => Item::Skip, Value::Object(o) => Item::Container(o), other => Item::Primitive(other), @@ -565,39 +565,19 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is /// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None` -/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not -/// found on the object or on its prototype chain before the object's standard prototype, the -/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that -/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and -/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. +/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String +/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and +/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called +/// first (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; - let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { - Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string), - Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true), + let string = match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Number(_)) => as_string, + Some(Class::String(_)) => true, _ => return Ok(None), }; - let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; - Ok(Some(if string { Value::String(interp.primitive_to_str(&p)) } else { Value::Number(interp.to_number(&p)?) })) -} - -/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before -/// any object on the way, `proto` included, has its own property `name`. -fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult { - let k = key(name); - let mut cur = Some(o); - while let Some(id) = cur { - interp.use_fuel()?; - if interp.get_own_property(id, &k)?.is_some() { - return Ok(false); - } - if id == proto { - return Ok(true); - } - cur = interp.heap.object(id).and_then(|x| x.proto); - } - Ok(false) + let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?; + Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } /// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes. @@ -637,7 +617,7 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul let units = flat_charged(i, s)?; write_quoted(i, out, &units) }), - Value::Undefined | Value::Object(_) => Ok(()), + Value::Undefined | Value::Object(_) | Value::Symbol(_) => Ok(()), } } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..42947c7d7a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -7,6 +7,7 @@ use super::{ELEMENT_BYTES, arg, create_at, method, new_array}; use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::{Str, Value}; pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { @@ -119,6 +120,14 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { }) } +/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section +/// 9.1.11). +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult> { + let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); + keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + Ok(keys) +} + /// `Object.getPrototypeOf` (section 15.2.3.2). fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; @@ -129,8 +138,8 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let k = interp.to_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + let k = interp.to_prop_key(&arg(args, 1))?; + match interp.get_own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -166,10 +175,10 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, true)) })?; Ok(Value::Object(o)) } @@ -189,12 +198,20 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in interp.own_keys(p)? { + let keys = own_prop_keys(interp, p)?; + // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted + // until they are defined on `o`. + for k in &keys { + if let PropKey::Sym(s) = k { + interp.temp_roots.push(Value::Symbol(s.clone())); + } + } + for k in keys { interp.use_fuel()?; - if !interp.get_own_property(p, &k)?.is_some_and(|prop| prop.enumerable()) { + if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; } - let v = interp.get_from(p, &k, &Value::Object(p))?; + let v = interp.get_value_pk(&Value::Object(p), &k)?; interp.temp_roots.push(v.clone()); let desc = to_desc(interp, &v)?; interp.temp_roots.extend(desc_values(&desc)); @@ -202,7 +219,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { } for (k, desc) in descs { interp.use_fuel()?; - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } Ok(()) })(); @@ -214,9 +231,9 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9). fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; let mut desc = match &prop { Prop::Data { value, flags } => Desc::data(value.clone(), *flags), Prop::Accessor { get, set, flags } => Desc { @@ -231,7 +248,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { if freeze && desc.is_data() { desc.writable = Some(false); } - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } if let Some(obj) = interp.heap.object_mut(o) { obj.extensible = false; @@ -263,9 +280,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs new file mode 100644 index 0000000000..b671f51e42 --- /dev/null +++ b/crates/js/src/builtins/symbol.rs @@ -0,0 +1,183 @@ +//! `Symbol` (ECMA-262 11th edition, section 19.4, ): +//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10), +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]` +//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. + +use super::{arg, constructor, create_at, data, method, native, new_array}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::interp::{Hint, Interp, JsResult}; +use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; +use crate::value::{Str, Value}; + +pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { + let well_known = WellKnown::new(); + let names = [ + ("iterator", well_known.iterator.clone()), + ("asyncIterator", well_known.async_iterator.clone()), + ("hasInstance", well_known.has_instance.clone()), + ("toPrimitive", well_known.to_primitive.clone()), + ("toStringTag", well_known.to_string_tag.clone()), + ]; + let (to_string_tag, to_primitive, has_instance) = + (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); + interp.symbols.well_known = Some(well_known); + + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let ctor = native(interp, "Symbol", symbol_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Symbol", ctor, proto)?; + method(interp, ctor, "for", symbol_for, 1)?; + method(interp, ctor, "keyFor", key_for, 1)?; + for (name, sym) in names { + data(interp, ctor, name, Value::Symbol(sym), 0)?; + } + method(interp, proto, "toString", to_string, 0)?; + method(interp, proto, "valueOf", value_of, 0)?; + let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; + interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; + interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; + sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + let date_proto = interp.intrinsics.date_proto; + sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?; + + method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; + let function_proto = interp.intrinsics.function_proto; + let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; + // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + interp.symbols.objects = Some(Es2015Objects { + symbol_proto: proto, + array_iterator_proto: proto, + string_iterator_proto: proto, + array_values: has_instance, + has_instance, + }); + Ok(()) +} + +/// Defines a built-in function as the property `sym` of `on`, with the attribute `flags`. +pub(super) fn sym_method(interp: &mut Interp, on: ObjId, sym: Sym, name: &'static str, f: NativeFn, length: u32, flags: u8) -> JsResult { + let m = native(interp, name, f, length, NativeKind::Plain, false)?; + interp.define_sym(on, sym, Prop::Data { value: Value::Object(m), flags })?; + Ok(m) +} + +/// A new Symbol, its bytes checked against the heap limit and charged to the heap. +fn new_symbol(interp: &mut Interp, description: Option, registered: bool, extra: usize) -> JsResult { + let bytes = SYMBOL_BYTES.saturating_add(extra); + let roots: Vec = description.iter().cloned().map(Value::String).collect(); + interp.rooted(&roots, |i| i.reserve_heap(bytes))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Sym::new(description, registered)) +} + +/// `Symbol([description])` (section 19.4.1.1). `new Symbol()` throws a `TypeError`. +fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + if construct { + return Err(interp.type_error("the value is not a constructor")); + } + let description = match arg(args, 0) { + Value::Undefined => None, + d => Some(interp.to_str(&d)?), + }; + new_symbol(interp, description, false, 0).map(Value::Symbol) +} + +/// `Symbol.for(key)` (section 19.4.2.2): the registry's Symbol for the key, made the first time. +fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let key = interp.to_str(&arg(args, 0))?; + let units = crate::string_builtins::flat_charged(interp, &key)?; + if let Some(v) = interp.symbols.registry.get(&*units) { + return Ok(v.clone()); + } + let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); + Ok(Value::Symbol(sym)) +} + +/// `Symbol.keyFor(sym)` (section 19.4.2.6). +fn key_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let Value::Symbol(sym) = arg(args, 0) else { return Err(interp.type_error("Symbol.keyFor was given a value that is not a Symbol")) }; + Ok(match sym.description() { + Some(d) if sym.registered() => Value::String(d.clone()), + _ => Value::Undefined, + }) +} + +/// thisSymbolValue (section 19.4.3): a Symbol, or the Symbol of a Symbol object. +fn this_symbol(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let sym = match this { + Value::Symbol(s) => Some(s.clone()), + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Symbol(s)) => Some(s.clone()), + _ => None, + }, + _ => None, + }; + sym.ok_or_else(|| interp.type_error(&format!("Symbol.prototype.{name} was called on a value that is not a Symbol"))) +} + +/// `Symbol.prototype.toString` (section 19.4.3.3): `Symbol(description)`. +fn to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "toString")?; + interp.descriptive_string(&sym) +} + +/// `Symbol.prototype.valueOf` (section 19.4.3.4). +fn value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "valueOf").map(Value::Symbol) +} + +/// The getter of `Symbol.prototype.description` (section 19.4.3.2). +fn description(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "description")?; + Ok(sym.description().map_or(Value::Undefined, |d| Value::String(d.clone()))) +} + +/// `Symbol.prototype[@@toPrimitive](hint)` (section 19.4.3.5). +fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) +} + +/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object, +/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`. +/// Any other hint, or a `this` that is not an object, throws a `TypeError`. +fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let Value::Object(o) = this else { + return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object")); + }; + // The longest hint has 7 units, so a longer string is refused before it is flattened. + let name = match arg(args, 0) { + Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()), + _ => String::new(), + }; + let hint = match name.as_str() { + "string" | "default" => Hint::String, + "number" => Hint::Number, + _ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")), + }; + interp.ordinary_to_primitive(o, &this, hint) +} + +/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the +/// order they were added. +fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = interp.to_object(&arg(args, 0))?; + interp.rooted(&[Value::Object(o)], |interp| { + let syms = interp.own_symbols(o)?; + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + create_at(interp, a, i as f64, Value::Symbol(s))?; + } + Ok(Value::Object(a)) + }) + }) +} + +/// `Function.prototype[@@hasInstance](v)` (section 19.2.3.6): OrdinaryHasInstance. +fn function_has_instance(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool) +} diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..c009dddc9a 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() { assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3"); assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4"); assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\""); + // Once the own prototype's method is deleted, the lookup goes on to Object.prototype. + let over = "Object.prototype.toString = function () { return '7'; };"; + assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\""); + assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7"); } #[test] diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index c805ad48e0..2671959b17 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -136,6 +136,15 @@ pub(crate) enum Op { /// `object function` → `object`. InitGetter(u32), InitSetter(u32), + /// `object value` → `object`: `__proto__: value` sets the object's prototype to the value + /// when it is an object or `null` (ECMA-262 2015 section B.3.1). + InitProto, + /// `function` → `function`: gives the new function the `name` `names[i]` (ECMA-262 2015 + /// section 9.2.11). + SetFunctionName(u32), + /// `name function` → `name function`: gives the new function the computed `name` on the + /// stack, after the prefix. + SetFunctionNameKey(NamePrefix), /// Pushes a new function made from `functions[i]` and the current environment. Closure(u32), /// Pushes a new regular expression object for `regexps[i]`. @@ -214,6 +223,29 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1). + GetIterator, + /// `record` → `record value`, or jumps with `record` when the iterator is done. + IterStep(u32), + /// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, `undefined` once it is done. + IterValue(u32), + /// `record` → `record`: steps the iterator without reading the result's `value`, for a hole + /// in an array pattern. + IterSkip, + /// `record x₁…xₙ` → `record x₁…xₙ array`: the values left, in an array. + IterRest(u32), + /// `record` → nothing: closes the iterator unless it is done (IteratorClose). + IterClose, + /// `record exception` → throws the exception after closing the iterator unless it is done. + IterCloseThrow, + /// `value` → `value`: a `TypeError` when it is `undefined` or `null`. + RequireObjectCoercible, + /// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`: an object pattern's property. + PatternGet(u32), + /// `object key value` → `object`: a property with a computed name. + InitIndex, + /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. + InitAccessorIndex(bool), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -305,9 +337,53 @@ pub(crate) struct Code { pub(crate) arrow: bool, /// The code reads `this` or calls `eval`, itself or in an arrow function inside it. pub(crate) uses_this: bool, - /// The function has default or rest parameters: its parameters start uninitialized, its - /// code initializes them and then enters its body with [`Op::BodyEnv`]. + /// The function has default, rest or destructured parameters: its parameters start + /// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The names the destructured parameters bind, which start uninitialized beside the + /// parameters. A destructured parameter's own entry in `params` is a name no script can + /// write. + pub(crate) pattern_names: Vec, + /// The code was read with [`crate::Options::es2015`]: its function's `length` can be + /// redefined, as ECMA-262 2015 section 19.2.4.1 has it. + pub(crate) es2015: bool, + /// The `name` its function objects get when they are made (ECMA-262 2015 sections 14.1.19 + /// and 14.1.20): a declaration's or a named function expression's name, with + /// [`crate::Options::es2015`]. + pub(crate) own_name: Option, + /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: + /// its functions have no `prototype` and cannot be constructed (section 14.3.8). + pub(crate) method: bool, +} + +/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum NamePrefix { + None, + Get, + Set, +} + +impl NamePrefix { + /// The prefix's code units, with the space that follows it. + pub(crate) fn units(self) -> &'static [u16] { + const GET: &[u16] = &[0x67, 0x65, 0x74, 0x20]; + const SET: &[u16] = &[0x73, 0x65, 0x74, 0x20]; + match self { + NamePrefix::None => &[], + NamePrefix::Get => GET, + NamePrefix::Set => SET, + } + } + + /// The prefix with the space that follows it, as text. + pub(crate) fn text(self) -> &'static str { + match self { + NamePrefix::None => "", + NamePrefix::Get => "get ", + NamePrefix::Set => "set ", + } + } } impl Code { @@ -361,7 +437,9 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1), Op::GetMemberThis(_) => e(1, 2), Op::SetMember(_) | Op::GetIndex | Op::DeleteIndex | Op::IncIndex { .. } | Op::Binary(_) => e(2, 1), - Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) => e(2, 1), + Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) | Op::InitProto => e(2, 1), + Op::SetFunctionName(_) => e(1, 1), + Op::SetFunctionNameKey(_) => e(2, 2), Op::GetIndexThis => e(2, 2), Op::SetIndex => e(3, 1), Op::Call(n) | Op::CallEval(n) => e(n.checked_add(2).ok_or("operand too large")?, 1), @@ -391,7 +469,13 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1), + Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, + Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?), + Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?), + Op::IterClose => e(1, 0), + Op::IterCloseThrow => end(2), + Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), }) } @@ -418,6 +502,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { | Op::InitProp(i) | Op::InitGetter(i) | Op::InitSetter(i) + | Op::SetFunctionName(i) | Op::PushCatch(i) | Op::InitVar(i) | Op::LoadParam(i) diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index 61b9a7f318..60df43513c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option { } } -/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number +/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number /// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are /// kept exactly in a `u128` while they fit; past that, each later digit counts only for its /// position and for whether any of the dropped bits is set. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index cbe5493cdc..26cd0a71cd 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -13,17 +13,20 @@ //! chains and labels are compiled with loops; every other kind of nesting is counted, and code //! nested deeper than [`MAX_DEPTH`] gives a `SyntaxError` instead of exhausting the stack. +mod pattern; + use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ - AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId, - TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, Property, PropertyKey, + PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; -use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify}; +use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; use crate::heap::Key; use crate::value::Str; +use pattern::Mode; /// How deeply the compiler may recurse: past the parser's default nesting limit, and shallow /// enough for a 1 MiB stack. @@ -61,6 +64,10 @@ enum Ctx { Jump { labels: Vec, is_loop: bool, plain_break: bool, brk: Label, cont: Option