Skip to content

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

affinity: decoded layers are admitted against an aggregate pixel budget (#4960) (#5266)

卢文彬6b9e17347743
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
index 4f0f9afe5..3e4e06615 100644
--- a/crates/affinity/README.md
+++ b/crates/affinity/README.md
@@ -132,8 +132,10 @@ test fixtures, not an exporter.
## Safety limits
-Every size is checked before it is allocated: 256 MiB per archive entry and 1 GiB per import by
-default (`Limits`), a 64 MiB zstd window, 4096 saved revisions, array lengths no longer than the
+Every size is checked before it is allocated: 256 MiB per archive entry, 1 GiB extracted per import
+and 1 GiB of decoded pixels per import by default (`Limits`: extracted bytes and materialized pixels
+are separate budgets, since a bitmap's declared size costs memory whatever its tiles hold), a 64 MiB
+zstd window, 4096 saved revisions, array lengths no longer than the
bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before
anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of
those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
diff --git a/crates/affinity/fuzz/fuzz_targets/preview.rs b/crates/affinity/fuzz/fuzz_targets/preview.rs
index 31e2bf973..63858fe71 100644
--- a/crates/affinity/fuzz/fuzz_targets/preview.rs
+++ b/crates/affinity/fuzz/fuzz_targets/preview.rs
@@ -6,5 +6,5 @@ use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = photocraft_affinity::container::header(data);
let _ = photocraft_affinity::preview(data);
- let _ = photocraft_affinity::read(data, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20 });
+ let _ = photocraft_affinity::read(data, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20, max_pixel_bytes: 64 << 20 });
});
diff --git a/crates/affinity/fuzz/fuzz_targets/stream.rs b/crates/affinity/fuzz/fuzz_targets/stream.rs
index fd6128a66..1f3895279 100644
--- a/crates/affinity/fuzz/fuzz_targets/stream.rs
+++ b/crates/affinity/fuzz/fuzz_targets/stream.rs
@@ -7,5 +7,5 @@ use libfuzzer_sys::fuzz_target;
fuzz_target!(|stream: &[u8]| {
let _ = photocraft_affinity::stream::parse(stream);
let file = photocraft_affinity::synth::container(&[("doc.dat", stream, photocraft_affinity::synth::Method::Stored)], None);
- let _ = photocraft_affinity::read(&file, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20 });
+ let _ = photocraft_affinity::read(&file, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20, max_pixel_bytes: 64 << 20 });
});
diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs
index b1a60ed43..880b7236d 100644
--- a/crates/affinity/src/container.rs
+++ b/crates/affinity/src/container.rs
@@ -26,11 +26,16 @@ pub struct Limits {
pub max_entry: usize,
/// Total bytes extracted over the whole import.
pub max_total: usize,
+ /// Bytes of decoded pixels one import may hold: every layer's RGBA together, plus the
+ /// temporary planes the layer being read decodes through. The entry limits bound what is
+ /// extracted, not what the layers materialized out of it cost (#4960).
+ pub max_pixel_bytes: usize,
}
impl Default for Limits {
fn default() -> Self {
- Self { max_entry: 256 << 20, max_total: 1 << 30 }
+ // The gigabyte the other importers allow decoded pixels (`io`'s `MAX_PIXEL_BYTES`).
+ Self { max_entry: 256 << 20, max_total: 1 << 30, max_pixel_bytes: 1 << 30 }
}
}
diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs
index 07d0adf78..7fba5a459 100644
--- a/crates/affinity/src/model.rs
+++ b/crates/affinity/src/model.rs
@@ -288,7 +288,7 @@ pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
let mut archive = Archive::open(bytes, limits)?;
let doc = archive.read("doc.dat")?;
let s = stream::parse(&doc)?;
- Reader::new(&s, &mut archive).document()
+ Reader::new(&s, &mut archive, limits).document()
}
pub(crate) struct Reader<'s, 'a, 'b> {
@@ -298,11 +298,27 @@ pub(crate) struct Reader<'s, 'a, 'b> {
warnings: BTreeMap<String, usize>,
nodes: usize,
active: HashSet<ObjId>,
+ /// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so
+ /// far hold).
+ pixels_left: usize,
}
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
- fn new(s: &'s Stream, archive: &'b mut Archive<'a>) -> Self {
- Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new() }
+ fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self {
+ Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new(), pixels_left: limits.max_pixel_bytes }
+ }
+
+ /// Admit a layer's decoded pixels before they are allocated (#4960). `rgba` is the layer's
+ /// output, which stays with the document; `planes` is the working set it decodes through and
+ /// releases. Every layer read so far is still live while this one decodes, so the peak is all
+ /// three together.
+ pub(crate) fn admit_pixels(&mut self, rgba: usize, planes: usize) -> Result<(), Error> {
+ let peak = rgba.saturating_add(planes);
+ if peak > self.pixels_left {
+ return Err(Error::Limit("decoded pixel layers exceed the pixel budget"));
+ }
+ self.pixels_left -= rgba;
+ Ok(())
}
pub(crate) fn warn(&mut self, what: impl Into<String>) {
diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs
index 8cdf9b833..bb1ecc112 100644
--- a/crates/affinity/src/raster.rs
+++ b/crates/affinity/src/raster.rs
@@ -117,6 +117,11 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
return Ok(None);
}
};
+ // A layer is materialized from its declared size, whatever the tiles hold: admit the output
+ // and the planes it decodes through before either is allocated (#4960).
+ let pixels = (w as usize).checked_mul(h as usize).ok_or(Error::Limit("pixel layer size"))?;
+ let scratch = pixels.checked_mul(channels * bps).ok_or(Error::Limit("pixel layer size"))?;
+ r.admit_pixels(pixels.checked_mul(4).ok_or(Error::Limit("pixel layer size"))?, scratch)?;
let mut planes = Vec::with_capacity(channels);
let mut cache = HashMap::new();
for c in 1..=channels {
diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs
index b28e30f3d..59ae99044 100644
--- a/crates/affinity/src/tests.rs
+++ b/crates/affinity/src/tests.rs
@@ -251,9 +251,9 @@ mod archive {
broken[90] ^= 0x55;
let mut a = Archive::open(&broken, Limits::default()).unwrap();
assert!(a.read("doc.dat").is_err());
- let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX }).unwrap();
+ let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX, ..Limits::default() }).unwrap();
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
- let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1 }).unwrap();
+ let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1, ..Limits::default() }).unwrap();
a.read("doc.dat").unwrap();
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
}
@@ -459,3 +459,82 @@ mod shapes {
assert_eq!(sub.segments[3][2], p(5.0, 20.0));
}
}
+
+/// Aggregate materialized-pixel admission (#4960). The entry limits bound what the archive
+/// extracts; these cover what the decoded layers and their working planes cost, which is declared
+/// by each bitmap's `BmpW`/`BmpH` and needs no tile data at all.
+mod pixels {
+ use crate::Error;
+ use crate::container::Limits;
+ use crate::model::{Document, Kind};
+ use crate::synth::{self, F, Method, tag};
+
+ /// A `Rstr` pixel layer whose bitmap declares `w`×`h` pixels and holds no tiles.
+ fn layer(id: u32, w: i32, h: i32) -> F {
+ F::Def(
+ id,
+ vec![tag(b"Rstr")],
+ vec![
+ (tag(b"Desc"), F::Str(format!("Layer {id}"))),
+ (tag(b"Bitm"), F::Def(id + 1, vec![tag(b"DyBm")], vec![(tag(b"BmpW"), F::I32(w)), (tag(b"BmpH"), F::I32(h)), (tag(b"Frmt"), F::Enum(0, 0))])),
+ ],
+ )
+ }
+
+ /// A document whose one page holds a pixel layer per `sizes` entry.
+ fn document(sizes: &[(i32, i32)]) -> Vec<u8> {
+ let children: Vec<F> = sizes.iter().enumerate().map(|(i, &(w, h))| layer(10 + 2 * i as u32, w, h)).collect();
+ let data = synth::stream(&[(
+ tag(b"DocR"),
+ F::Def(
+ 1,
+ vec![tag(b"DocN")],
+ vec![(
+ tag(b"Chld"),
+ F::Shared(vec![F::Def(
+ 2,
+ vec![tag(b"Sprd")],
+ vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 256.0, 256.0])), (tag(b"Chld"), F::Shared(children))],
+ )]),
+ )],
+ ),
+ )]);
+ synth::container(&[("doc.dat", &data, Method::Zlib)], None)
+ }
+
+ fn imported_layers(d: &Document) -> usize {
+ d.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count()
+ }
+
+ /// A 64×64 layer costs 16 KiB of RGBA and 16 KiB of planes, so 40 KiB admits one and not two.
+ const ONE_LAYER: usize = 40 << 10;
+
+ #[test]
+ fn a_pixel_layer_within_the_budget_imports() {
+ let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() };
+ let d = crate::model::read(&document(&[(64, 64)]), limits).unwrap();
+ assert_eq!(imported_layers(&d), 1, "{:?}", d.warnings);
+ }
+
+ #[test]
+ fn layers_past_the_pixel_budget_are_rejected_before_they_are_allocated() {
+ let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() };
+ // The document is a few hundred bytes: the sizes are in the headers, not the entries.
+ let bytes = document(&[(64, 64), (64, 64)]);
+ assert!(bytes.len() < 4096, "the fixture is {} bytes", bytes.len());
+ assert!(matches!(crate::model::read(&bytes, limits), Err(Error::Limit(_))), "the second layer materialized");
+ // Two layers fit once the budget covers their pixels together.
+ let room = Limits { max_pixel_bytes: ONE_LAYER + (32 << 10), ..Limits::default() };
+ assert_eq!(imported_layers(&crate::model::read(&bytes, room).unwrap()), 2);
+ }
+
+ #[test]
+ fn a_declared_size_larger_than_the_budget_is_rejected_on_its_own() {
+ // 2048×2048 is 16 MiB of RGBA and 16 MiB of planes, past a 1 MiB budget.
+ let limits = Limits { max_pixel_bytes: 1 << 20, ..Limits::default() };
+ assert!(
+ matches!(crate::model::read(&document(&[(2048, 2048)]), limits), Err(Error::Limit(_))),
+ "16 MiB of declared pixels materialized under a 1 MiB budget"
+ );
+ }
+}