Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Never crash: psd, codecs, format, io are panic-free (Rule 9) (#34)

Brandon Thomas69f0e25d5f88
diff --git a/Cargo.lock b/Cargo.lock
index 6f2ebb504..69a672533 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2110,7 +2110,7 @@ dependencies = [
"qoi",
"ravif",
"rgb",
- "tiff 0.11.3",
+ "tiff",
"zune-core",
"zune-jpeg",
]
@@ -3323,7 +3323,7 @@ dependencies = [
"png 0.18.1",
"proptest",
"thiserror 2.0.21",
- "tiff 0.10.3",
+ "tiff",
"zune-core",
"zune-jpeg",
]
@@ -4714,18 +4714,6 @@ dependencies = [
"syn 3.0.6",
]
-[[package]]
-name = "tiff"
-version = "0.10.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f"
-dependencies = [
- "flate2",
- "half",
- "quick-error 2.0.1",
- "weezl",
-]
-
[[package]]
name = "tiff"
version = "0.11.3"
diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml
index 4b690b965..e824d8ec1 100644
--- a/crates/codecs/Cargo.toml
+++ b/crates/codecs/Cargo.toml
@@ -16,7 +16,7 @@ avif = ["image/avif"]
thiserror.workspace = true
image = { workspace = true, features = ["gif", "bmp", "tga", "ico", "qoi", "hdr"] }
png = "0.18"
-tiff = { version = "0.10", default-features = false, features = ["deflate", "lzw"] }
+tiff = { version = "0.11", default-features = false, features = ["deflate", "lzw"] }
exr = { version = "1.73", default-features = false }
half = "2"
flate2.workspace = true
diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs
index b60139a89..ce15c2ce1 100644
--- a/crates/codecs/src/codecs/tiff.rs
+++ b/crates/codecs/src/codecs/tiff.rs
@@ -237,7 +237,6 @@ fn rational_f64(v: tiff::decoder::ifd::Value) -> Option<f64> {
use tiff::decoder::ifd::Value;
match v {
Value::Rational(n, d) if d != 0 => Some(n as f64 / d as f64),
- Value::RationalBig(n, d) if d != 0 => Some(n as f64 / d as f64),
Value::Float(f) => Some(f as f64),
Value::Double(f) => Some(f),
Value::Unsigned(u) => Some(u as f64),
diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs
index 82c14b2f6..668f72313 100644
--- a/crates/codecs/src/image.rs
+++ b/crates/codecs/src/image.rs
@@ -144,13 +144,10 @@ fn byte_len(width: u32, height: u32, layout: ChannelLayout, sample: SampleType)
}
impl Image {
- /// A zero-filled image.
- ///
- /// # Panics
- /// If the byte size overflows `usize`.
- pub fn new(width: u32, height: u32, layout: ChannelLayout, sample: SampleType) -> Self {
- let len = byte_len(width, height, layout, sample).expect("image size overflows usize");
- Image { width, height, layout, sample, data: vec![0; len], icc: None, meta: Metadata::default() }
+ /// A zero-filled image, or an error if the byte size overflows `usize`.
+ pub fn new(width: u32, height: u32, layout: ChannelLayout, sample: SampleType) -> Result<Self, CodecError> {
+ let len = byte_len(width, height, layout, sample).ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?;
+ Ok(Image { width, height, layout, sample, data: vec![0; len], icc: None, meta: Metadata::default() })
}
/// Wrap raw interleaved, native-endian bytes.
@@ -472,7 +469,7 @@ mod tests {
#[test]
fn icc_dropped_on_model_change() {
- let img = Image::new(2, 2, ChannelLayout::Cmyk, SampleType::U8).with_icc(Some(vec![1, 2, 3]));
+ let img = Image::new(2, 2, ChannelLayout::Cmyk, SampleType::U8).unwrap().with_icc(Some(vec![1, 2, 3]));
assert!(img.convert(ChannelLayout::Rgb, SampleType::U8).icc.is_none());
assert!(img.convert(ChannelLayout::CmykA, SampleType::U16).icc.is_some());
}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index b88b15678..c5301ccca 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -11,6 +11,7 @@
//! `wasm32-unknown-unknown`. Decoders enforce [`Limits`] before allocating.
#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod codecs;
mod error;
diff --git a/crates/codecs/tests/fidelity.rs b/crates/codecs/tests/fidelity.rs
index 0b89f5147..5d77084c7 100644
--- a/crates/codecs/tests/fidelity.rs
+++ b/crates/codecs/tests/fidelity.rs
@@ -146,7 +146,7 @@ fn hdr_is_lossy() {
}
#[test]
fn ico_oversize_is_fatal() {
- let img = Image::new(512, 16, ChannelLayout::Rgba, SampleType::U8);
+ let img = Image::new(512, 16, ChannelLayout::Rgba, SampleType::U8).unwrap();
let w = warns(&img, Format::Ico);
assert!(w.iter().any(|w| w.is_fatal()));
assert!(w.contains(&W::DimensionsExceeded { max_width: 256, max_height: 256 }));
diff --git a/crates/codecs/tests/malformed.rs b/crates/codecs/tests/malformed.rs
index a3dfb591b..d92e6fda5 100644
--- a/crates/codecs/tests/malformed.rs
+++ b/crates/codecs/tests/malformed.rs
@@ -202,3 +202,53 @@ fn samples_cached() -> &'static [(Format, Vec<u8>)] {
static S: std::sync::OnceLock<Vec<(Format, Vec<u8>)>> = std::sync::OnceLock::new();
S.get_or_init(samples)
}
+
+/// A little-endian TIFF with one 1x1 8-bit grey strip and the given extra IFD entries
+/// (tag, type, count, value), sorted into place.
+fn tiny_tiff(extra: &[(u16, u16, u32, u32)]) -> Vec<u8> {
+ const SHORT: u16 = 3;
+ const LONG: u16 = 4;
+ let mut entries = vec![
+ (256, SHORT, 1, 1), // ImageWidth
+ (257, SHORT, 1, 1), // ImageLength
+ (258, SHORT, 1, 8), // BitsPerSample
+ (259, SHORT, 1, 1), // Compression: none
+ (262, SHORT, 1, 1), // Photometric: BlackIsZero
+ (273, LONG, 1, 0), // StripOffsets (patched below)
+ (277, SHORT, 1, 1), // SamplesPerPixel
+ (278, SHORT, 1, 1), // RowsPerStrip
+ (279, LONG, 1, 1), // StripByteCounts
+ ];
+ entries.extend_from_slice(extra);
+ entries.sort_by_key(|e| e.0);
+ let ifd_len = 2 + 12 * entries.len() + 4;
+ let strip = 8 + ifd_len as u32;
+ let mut b = b"II*\0".to_vec();
+ b.extend_from_slice(&8u32.to_le_bytes());
+ b.extend_from_slice(&(entries.len() as u16).to_le_bytes());
+ for (tag, ty, count, value) in entries {
+ let value = if tag == 273 { strip } else { value };
+ b.extend_from_slice(&tag.to_le_bytes());
+ b.extend_from_slice(&ty.to_le_bytes());
+ b.extend_from_slice(&count.to_le_bytes());
+ b.extend_from_slice(&value.to_le_bytes());
+ }
+ b.extend_from_slice(&0u32.to_le_bytes());
+ b.push(0x80);
+ b
+}
+
+#[test]
+fn tiff_fixture_decodes() {
+ let img = decode_as_with(Format::Tiff, &tiny_tiff(&[]), &tight()).unwrap();
+ assert_eq!((img.width(), img.height()), (1, 1));
+}
+
+/// Regression: an empty SampleFormat tag made the tiff 0.10 decoder index an empty list
+/// (`index out of bounds: the len is 0`). Found by mutation fuzzing; fixed by tiff 0.11.
+#[test]
+fn tiff_empty_sample_format_is_an_error() {
+ let bytes = tiny_tiff(&[(339, 3, 0, 0)]);
+ assert!(decode_as_with(Format::Tiff, &bytes, &tight()).is_err());
+ assert!(decode_with(&bytes, &tight()).is_err());
+}
diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rs
index b3fd97469..abfd2def0 100644
--- a/crates/codecs/tests/roundtrip.rs
+++ b/crates/codecs/tests/roundtrip.rs
@@ -243,15 +243,15 @@ fn one_pixel_images_roundtrip() {
#[test]
fn ico_rejects_oversize() {
- let img = Image::new(300, 10, ChannelLayout::Rgba, SampleType::U8);
+ let img = Image::new(300, 10, ChannelLayout::Rgba, SampleType::U8).unwrap();
assert!(matches!(encode(&img, Format::Ico, &EncodeOptions::default()), Err(CodecError::Encode { .. })));
- let img = Image::new(256, 256, ChannelLayout::Rgba, SampleType::U8);
+ let img = Image::new(256, 256, ChannelLayout::Rgba, SampleType::U8).unwrap();
assert!(encode(&img, Format::Ico, &EncodeOptions::default()).is_ok());
}
#[test]
fn empty_image_rejected() {
- let img = Image::new(0, 5, ChannelLayout::Rgb, SampleType::U8);
+ let img = Image::new(0, 5, ChannelLayout::Rgb, SampleType::U8).unwrap();
for f in writable_formats() {
assert!(encode(&img, f, &EncodeOptions::default()).is_err(), "{f:?}");
}
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index 799df7887..fe382cf87 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -18,6 +18,7 @@
//! This crate sits at L3 next to the compositor, so it does not render.
//! Callers pass previews in [`SaveOptions`]; `photocraft-io` does that.
#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod autosave;
mod convert;
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index 267df071e..d0e19a60c 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -272,11 +272,14 @@ impl Object {
}
}
+/// A bundle path and its compressed bytes.
+type Compressed<'a> = (&'a String, Arc<Vec<u8>>);
+
/// Compresses `objects` on scoped worker threads (sequentially on wasm).
-fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Vec<(&'a String, Arc<Vec<u8>>)> {
+fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result<Vec<Compressed<'a>>> {
let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 32) };
if threads < 2 || objects.len() < 2 {
- return objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed()))).collect();
+ return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed()))).collect());
}
let next = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|sc| {
@@ -293,7 +296,14 @@ fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Vec<(&'a String, Ar
})
})
.collect();
- hs.into_iter().flat_map(|h| h.join().expect("compress worker")).collect()
+ // Join every worker before looking at the results, so one failure can't leave
+ // another worker unjoined (the scope would then panic).
+ let joined: Vec<_> = hs.into_iter().map(|h| h.join()).collect();
+ let mut out = Vec::with_capacity(objects.len());
+ for r in joined {
+ out.extend(r.map_err(|_| FormatError::Io(std::io::Error::other("compression worker panicked")))?);
+ }
+ Ok(out)
})
}
@@ -344,7 +354,7 @@ impl PcraftWriter {
let mut next = HashMap::with_capacity(p.objects.len());
// New objects are compressed on all cores first (zstd dominates a full save).
let todo: Vec<(&String, &Object)> = p.objects.iter().filter(|(path, _)| !self.compressed.contains_key(*path)).collect();
- let mut fresh: HashMap<&String, Arc<Vec<u8>>> = par_compress(&todo).into_iter().collect();
+ let mut fresh: HashMap<&String, Arc<Vec<u8>>> = par_compress(&todo)?.into_iter().collect();
for (path, obj) in &p.objects {
let data = match self.compressed.get(path) {
Some(d) => {
diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs
index d4e0bda7e..3eec96c9d 100644
--- a/crates/io/src/effects_map.rs
+++ b/crates/io/src/effects_map.rs
@@ -573,6 +573,7 @@ pub fn parse_lrfx(data: &[u8]) -> Option<(bool, Vec<Effect>)> {
}
#[cfg(test)]
+#[allow(clippy::unreachable)] // clippy.toml exempts unwrap/expect/panic in tests, not unreachable!
mod tests {
use super::*;
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 5a1f97f3c..6f229f513 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -16,6 +16,7 @@
//! Exports to PSD render the merged composite with
//! `photocraft_compose::flatten`; flat exports report what is lost.
#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod adjust_map;
pub mod annotations_map;
diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs
index ab5a28d79..1a3b1a525 100644
--- a/crates/io/src/pixels.rs
+++ b/crates/io/src/pixels.rs
@@ -152,7 +152,11 @@ pub fn par_map<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync) -> Ve
std::thread::scope(|sc| {
let f = &f;
let hs: Vec<_> = items.into_iter().map(|t| sc.spawn(move || f(t))).collect();
- hs.into_iter().map(|h| h.join().expect("worker panicked")).collect()
+ // Join every worker first (an unjoined panicked thread would make the scope panic),
+ // then hand a worker's panic to the caller exactly as the sequential path would, so
+ // the shell's last-resort guard reports it instead of the scope aborting the join.
+ let joined: Vec<_> = hs.into_iter().map(|h| h.join()).collect();
+ joined.into_iter().map(|r| r.unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
})
}
diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs
index fcbe9b546..366cf8eb1 100644
--- a/crates/psd/src/lib.rs
+++ b/crates/psd/src/lib.rs
@@ -38,6 +38,7 @@
//! ```
#![forbid(unsafe_code)]
#![warn(missing_docs)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod blend;
pub mod builder;
@@ -57,6 +58,8 @@ pub mod resources;
pub mod slices;
pub mod tagged;
#[cfg(any(test, feature = "testgen"))]
+// Test-data generator (tests and fuzz seeds only): failing loudly is the point.
+#[allow(clippy::expect_used)]
pub mod testgen;
pub mod tree;