diff --git a/apps/photocraft/src/icon_theme.rs b/apps/photocraft/src/icon_theme.rs index cf2ede3b7b..562dcf76e3 100644 --- a/apps/photocraft/src/icon_theme.rs +++ b/apps/photocraft/src/icon_theme.rs @@ -202,17 +202,22 @@ pub fn rasterize_mask(svg: &[u8], px: u32) -> Option> { image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) }, ..usvg::Options::default() }; - let tree = usvg::Tree::from_data(svg, &opts).ok()?; - let size = tree.size(); - let side = size.width().max(size.height()); - if !side.is_finite() || side <= 0.0 { - return None; - } - let s = px as f32 / side; - let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0); - let mut pixmap = tiny_skia::Pixmap::new(px, px)?; - resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut()); - Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect()) + // usvg and resvg panic on some malformed drawings: such an icon is unreadable, not a crash. + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let tree = usvg::Tree::from_data(svg, &opts).ok()?; + let size = tree.size(); + let side = size.width().max(size.height()); + if !side.is_finite() || side <= 0.0 { + return None; + } + let s = px as f32 / side; + let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0); + let mut pixmap = tiny_skia::Pixmap::new(px, px)?; + resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut()); + Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect()) + })) + .ok() + .flatten() } #[cfg(test)] @@ -303,6 +308,15 @@ mod tests { assert!(rasterize_mask(SQUARE.as_bytes(), 100_000).is_none()); } + /// resvg panics rendering an offset past the pixmap's size: the icon is unreadable instead. + #[test] + fn a_mask_the_renderer_panics_on_is_none() { + let svg = r##" + + "##; + assert!(rasterize_mask(svg.as_bytes(), 16).is_none()); + } + /// An icon's `` is never loaded: not a device file, not an embedded picture. #[test] fn masks_load_no_images() { diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 6363945d7e..1340a9f0f1 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -274,10 +274,19 @@ fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Resul // re-checks the gzip magic and would decompress a second time without our size limit if // the inflated content happened to start with a nested gzip stream. let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - let tree = usvg::Tree::from_str(text, &opt).map_err(|e| IoError::Svg(e.to_string()))?; + let tree = guarded(|| usvg::Tree::from_str(text, &opt)) + .ok_or_else(|| IoError::Svg("the SVG parser failed on this drawing".into()))? + .map_err(|e| IoError::Svg(e.to_string()))?; Ok(Parsed { tree, fontless_text }) } +/// `f` under `catch_unwind`, `None` when it panics: usvg, resvg and tiny-skia panic on some +/// malformed drawings, which must fail like any unreadable file, not crash (as the HEIF and +/// JPEG XL decoders are guarded). Where a panic aborts (wasm) this changes nothing. +fn guarded(f: impl FnOnce() -> T) -> Option { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok() +} + /// The plain XML of `bytes`: itself, or the inflated content of a gzip `.svgz`, refused past /// [`MAX_INFLATED_BYTES`] (a decompression bomb) or when the stream is corrupt. fn inflate(bytes: &[u8]) -> Result, IoError> { @@ -400,8 +409,11 @@ fn import_parsed_with_budget(name: &str, parsed: Parsed, max_group_depth: usize, conv.warnings.push(format!("SVG: more than {MAX_NODES} elements; opened as one pixel layer instead of shapes")); let (w, h) = (cv.size.width, cv.size.height); if let Some(mut pixmap) = pixmap(w, h) { - resvg::render(&tree, global, &mut pixmap.as_mut()); - doc.layers.push(Layer::new("Background", LayerContent::Raster(surface(&pixmap, doc.bounds(), fmt)))); + if guarded(|| resvg::render(&tree, global, &mut pixmap.as_mut())).is_some() { + doc.layers.push(Layer::new("Background", LayerContent::Raster(surface(&pixmap, doc.bounds(), fmt)))); + } else { + conv.warnings.push("SVG: the drawing could not be rendered".to_string()); + } } } else { doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform()); @@ -421,7 +433,8 @@ pub fn rasterize(bytes: &[u8], scale: f32) -> Result"); + let e = import("image.svg", bad_image.as_bytes()).err().unwrap_or_else(|| panic!("opened")); + assert!(matches!(e, IoError::Svg(_)), "{e}"); + // resvg panics rendering an offset past the pixmap's size: that element is dropped with a + // warning, the rest of the drawing still opens. + let offset = "\ + "; + let svg = format!("{offset}"); + let r = open(&svg); + assert_eq!(r.document.layers.len(), 1, "{:?}", r.document.layers.iter().map(|l| &l.name).collect::>()); + assert!(matches!(r.document.layers[0].content, LayerContent::Shape(_))); + assert!(r.warnings.iter().any(|w| w.contains("could not be rendered")), "{:?}", r.warnings); + // The same drawing as a smart object, and past the element limit (opened as one pixel layer). + let e = svg::rasterize(svg.as_bytes(), 1.0).err().unwrap_or_else(|| panic!("rendered")); + assert!(matches!(e, IoError::Svg(_)), "{e}"); + let many = format!("{offset}{}", "".repeat(2_000)); + let r = open(&many); + assert!(r.document.layers.is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("could not be rendered")), "{:?}", r.warnings); +} + #[test] fn an_svg_round_trips_through_pcraft_as_shapes() { let r = open(&format!(