From 77ed30177516bc6c2ef7f1de6a564a0692ae50d8 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 1 Dec 2026 03:42:59 +0700 Subject: [PATCH] SVG import: refuse an SVG the memory can't hold instead of running out (#10303) * SVG import: refuse an SVG the memory can't hold instead of running out The element limit now follows the installed memory, or the process's cgroup limit where that is lower: about 8 KB an element, up to the 999,999 elements usvg reads. Past it the SVG is refused with an error naming the memory, before usvg makes its tree. Fixes #10165 * Tests: the shared element limit test follows the machine's limit --- Cargo.lock | 1 + crates/svg/Cargo.toml | 2 + crates/svg/src/import.rs | 13 +++++-- crates/svg/src/import/budget.rs | 54 ++++++++++++++++++++++++--- crates/svg/src/import/files.rs | 8 ++-- crates/svg/src/lib.rs | 6 ++- crates/svg/tests/it/import_details.rs | 21 +++++++++-- xtask/src/layers.rs | 2 + 8 files changed, 89 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 170ad40f3d..5aff7bd0a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9049,6 +9049,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 310b9c8e6f..08fcbbd3de 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } +# Installed memory (cgroup limits included), which sizes the element limit. +vectorcraft-render = { workspace = true } kurbo = { workspace = true } # Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 5e7afdd55a..20261eef95 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -28,6 +28,11 @@ pub(crate) use fx::BLEND; /// expansion bombs (#3564). pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// Most elements an SVG may expand to on this machine, its memory considered (#10165). +pub fn max_elements() -> usize { + budget::max_elements() as usize +} + mod convert; mod importer; mod layers; @@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) } let xml = parse(svg)?; // Before the style cascade of `depth::height`, as `import` measures it. - budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -142,7 +147,7 @@ pub(crate) fn import_finding( let xml = parse(svg)?; // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of // each element it reads; measured again below on the text usvg reads when that differs. - let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; @@ -165,8 +170,8 @@ pub(crate) fn import_finding( // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. let spent = match &src { Cow::Borrowed(_) if !rewritten => spent, - Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, - Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?, }; let files = found.files; files.spent_by_svg(spent); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs index 2520a8932a..b7b45f03da 100644 --- a/crates/svg/src/import/budget.rs +++ b/crates/svg/src/import/budget.rs @@ -6,8 +6,9 @@ //! sheets and the `style` attribute give the element, so a long style on an element that ``s //! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more //! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after -//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or -//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than +//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`] +//! bytes of copied styles is refused here instead. //! //! The copies are counted, never made: each element's count is worked out once and added up, so a //! `` of an element costs one addition, however many elements its copy holds. References @@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError}; /// which usvg stops (its count includes a root of its own). pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; +/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a +/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare. +const ELEMENT_BYTES: u64 = 8 << 10; + +/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the +/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused +/// with an error instead of running out of memory. +pub(crate) fn max_elements() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory())) +} + +/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known). +fn elements_for(memory: Option) -> u64 { + memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64)) +} + +/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it. +fn too_many_elements() -> SvgError { + let most = max_elements(); + match vectorcraft_render::installed_memory() { + Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20), + _ => SvgError::TooLarge(MAX_SVG_ELEMENTS), + } +} + /// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it /// shows, all together: VectorCraft's own limit. pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; @@ -209,7 +236,9 @@ pub(crate) struct Cost { impl Cost { /// The most an SVG and the SVG images it shows may cost together. - pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + pub(crate) fn limits() -> Cost { + Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS } + } pub(crate) fn add(self, other: Cost) -> Cost { Cost { @@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) { let (result, tests) = measure_spending(xml, left, depth); let result = result.map_err(|past| match past { - Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS), + Past::Elements => too_many_elements(), Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize), Past::Tests => SvgError::StylesTooComplex, Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH), @@ -562,6 +591,19 @@ mod tests { assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 }); } + #[test] + fn less_memory_reads_fewer_elements_up_to_the_element_limit() { + let most = MAX_SVG_ELEMENTS as u64; + assert_eq!(elements_for(None), most, "unknown memory"); + assert_eq!(elements_for(Some(0)), most, "unknown memory"); + assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory"); + // A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165). + let small = elements_for(Some(1 << 30)); + assert!(small < 400_000, "{small}"); + assert!(elements_for(Some(512 << 20)) < small); + assert!(max_elements() <= most); + } + #[test] fn style_sheet_rules_count_where_they_match() { let groups = "".repeat(4); @@ -614,7 +656,7 @@ mod tests { let xml = roxmltree::Document::parse(&deep).unwrap(); assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); - assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); for text in [chain(5, ""), svg("")] { let xml = roxmltree::Document::parse(&text).unwrap(); let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); @@ -674,7 +716,7 @@ mod tests { fn a_selector_that_never_matches_stops_at_the_test_limit() { let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); let xml = roxmltree::Document::parse(&never).unwrap(); - assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests)); let before = super::super::css::selector_tests(); let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 631bed3d0c..525e900c87 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -478,7 +478,7 @@ impl Files { // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the // linked SVG files measured before it left: past it, its links aren't read, and the // selector tests it made still count. - let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left); match result { Ok(cost) => reading.measured = reading.measured.add(cost), Err(e) => { @@ -593,13 +593,13 @@ impl Files { } /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most - /// what is left of [`budget::Cost::LIMITS`]. + /// what is left of [`budget::Cost::limits()`]. pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { self.set_spent(spent); } fn spent(&self) -> budget::Cost { - self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits()) } fn set_spent(&self, spent: budget::Cost) { @@ -807,7 +807,7 @@ impl Files { // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; // past the other limits, the whole SVG is refused. let spent = self.spent(); - let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) { Ok(cost) => cost, Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), Err(e) => { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ad3e91588f..0bcd5999b7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -363,6 +363,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} objects")] TooLarge(usize), + /// The SVG expands to more objects (the first number) than this machine's memory, or the + /// process's memory limit (the second number, in MB), has room to read (#10165). + #[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")] + TooLargeForMemory(usize, u64), /// The SVG expands to more nested SVG images than the reader takes (a guard against /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] @@ -536,7 +540,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu pub use glyph::glyph_art; pub use import::{ MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, - MAX_NODES, + MAX_NODES, max_elements, }; /// Import an SVG document reading the files it links to as `opts` says, also returning warnings. diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..a4046e3fe7 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -892,11 +892,22 @@ fn styles_that_expand_past_the_limit_are_refused() { assert_eq!(art(&d).len(), 5000); } +/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose +/// memory has room for fewer (#10165). +fn past_the_element_limit(err: &SvgError) -> bool { + let most = vectorcraft_svg::MAX_NODES.min(999_999); + match *err { + SvgError::TooLarge(n) => n == most, + SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(), + _ => false, + } +} + /// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. #[test] fn a_use_chain_past_the_elements_usvg_reads_is_refused() { let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images @@ -927,9 +938,13 @@ fn svg_images_share_the_element_limit() { assert_ne!(chain, unshown); let image = image_of("image/svg+xml", &unshown); let rect = r#""#; - assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + // One image fits, unless this machine's memory has room for fewer elements than it makes. + match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) { + Ok(_) => {} + Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"), + } let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index f2fb1f1ce0..869074b03f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -80,6 +80,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["pathops", "trace"], &["text", "effects"], &["render", "eps"], + // SVG import sizes its element limit from the installed memory the renderer reads (#10165). + &["render", "svg"], &["metafile", "eps"], // Non-native art in Illustrator editing data is a PDF, drawn by the PDF importer. &["pdf", "eps"],