Bound PSD layer and mask import memory before decoding (#10503)

* Bound PSD import pixel storage before decoding

* Include ZIP inflater workspace in PSD preflight

* PSD import: budget unknown-mode layers, stop after a fatal layer error, keep best-effort for non-allocation limits (#8593 review)
This commit is contained in:
Khawar Zamman Wani authored and GitHub committed 2026-11-01 12:33:09 +01:00
1 parent 560beed83e
commit 97a83f074f
21 files changed
+761 -111

No files matched your search

+1
View File
@@ -514,6 +514,7 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor
photocraft_io::ImportOptions {
max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize,
demosaic: prefs.raw_defaults.demosaic.method(),
..Default::default()
}
}
+13 -4
View File
@@ -16,10 +16,15 @@ const BAND_BYTES: usize = 32 << 20;
/// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens
/// layered (see [`crate::tiff_layers`]).
pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
import_flat_with_limit(name, bytes, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES)
}
/// [`import_flat`] with the caller's PSD pixel allowance, which a layered TIFF is held to.
pub(crate) fn import_flat_with_limit(name: &str, bytes: &[u8], pixel_limit: u64) -> Result<ImportResult, IoError> {
// Detected once; every step below branches on it.
let format = codecs::detect(bytes);
if format == Some(Format::Tiff) {
return import_tiff_page(name, bytes, None);
return import_tiff_page_with_limit(name, bytes, None, pixel_limit);
}
let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?;
// A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in
@@ -230,20 +235,24 @@ pub fn tga_alpha_channel_to_transparency(doc: &mut Document) {
/// a second full-size copy (#8169), when the machine has the memory for it (see
/// [`crate::memory`]).
pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option<usize>) -> Result<ImportResult, IoError> {
import_tiff_page_with_limit(name, bytes, page, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES)
}
fn import_tiff_page_with_limit(name: &str, bytes: &[u8], page: Option<usize>, pixel_limit: u64) -> Result<ImportResult, IoError> {
let bands = codecs::TiffBands::open(bytes, page, &codecs::Limits::banded())?;
// A page with layers or extra samples (alpha and spot channels) is decoded whole: the layers
// and channels are built from the full image. Only one copy of the layer data is kept through
// that decode.
if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) || bands.extra_samples() > 0 {
drop(bands);
return import_tiff_whole(name, bytes, page);
return import_tiff_whole(name, bytes, page, pixel_limit);
}
tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES)
}
/// A layered TIFF, or a flat one with extra samples, decoded whole: the layers are built from the
/// composite, the channels from the extra samples.
fn import_tiff_whole(name: &str, bytes: &[u8], page: Option<usize>) -> Result<ImportResult, IoError> {
fn import_tiff_whole(name: &str, bytes: &[u8], page: Option<usize>, pixel_limit: u64) -> Result<ImportResult, IoError> {
// The orientation is applied after the layer check: rotating the composite but not the
// layers would misalign them, so a layered TIFF keeps its stored orientation.
let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() };
@@ -252,7 +261,7 @@ fn import_tiff_whole(name: &str, bytes: &[u8], page: Option<usize>) -> Result<Im
Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)),
};
if let Some(layers) = img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()) {
let mut r = crate::tiff_layers::import_layered(name, &img, layers)?;
let mut r = crate::tiff_layers::import_layered(name, &img, layers, pixel_limit)?;
if orientation != 1 {
r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string());
}
+66 -20
View File
@@ -64,8 +64,10 @@ pub mod pdf;
mod pdn;
pub use pcraft_cache::PcraftExportCache;
pub mod pixels;
mod psd_budget;
mod psd_export;
mod psd_import;
pub use psd_budget::DEFAULT_PSD_IMPORT_PIXEL_BYTES;
pub mod psd_thumbnail;
pub mod raw;
pub mod slices_map;
@@ -110,6 +112,13 @@ pub enum IoError {
/// PSD parse/write failure.
#[error("PSD: {0}")]
Psd(#[from] PsdError),
/// The conservative PSD pixel-storage and workspace estimate exceeded its allowance.
#[error("PSD import needs an estimated {required} bytes of pixel memory; limit is {limit} bytes")]
PsdImportBudget { required: u64, limit: u64 },
/// A pixel buffer could not be allocated while reading a file: the file may be fine, but
/// this machine has no memory for it.
#[error("not enough memory: {0}")]
OutOfMemory(String),
/// Codec failure.
#[error("codec: {0}")]
Codec(#[from] CodecError),
@@ -339,11 +348,18 @@ pub struct ImportOptions {
pub max_group_depth: usize,
/// The demosaic method camera raws are developed with.
pub demosaic: raw::Demosaic,
/// PSD layer/mask/merged pixel allowance, including conversion workspace. May lower the
/// default cap; does not cover metadata, patterns or smart-filter caches.
pub psd_max_pixel_bytes: u64,
}
impl Default for ImportOptions {
fn default() -> Self {
ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default() }
ImportOptions {
max_group_depth: photocraft_doc::MAX_GROUP_DEPTH,
demosaic: raw::Demosaic::default(),
psd_max_pixel_bytes: DEFAULT_PSD_IMPORT_PIXEL_BYTES,
}
}
}
@@ -385,28 +401,45 @@ fn import_psd(
name: &str,
ctl: &photocraft_raster::Interrupt,
damaged: &mut bool,
parse: impl FnOnce(&dyn Fn(&PsdFile) -> bool, &dyn Fn(&PsdFile) -> bool) -> photocraft_psd::Result<(PsdFile, Option<photocraft_psd::Result<Vec<u8>>>)>,
pixel_limit: u64,
parse: impl FnOnce(
&dyn Fn(&PsdFile) -> photocraft_psd::Result<bool>,
&dyn Fn(&PsdFile) -> bool,
) -> photocraft_psd::Result<(PsdFile, Option<photocraft_psd::Result<Vec<u8>>>)>,
) -> Result<ImportResult, IoError> {
// A merged image the import reads is decoded with the parse: a ZIP one is inflated once.
// A failed read of the file (one parsed from its source) is a read error, as reading the
// whole file first would report it.
let (file, merged) =
parse(&|f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), &psd_import::can_recover_layers).map_err(|e| match e {
photocraft_psd::PsdError::Read(msg) => IoError::Read(msg),
e => e.into(),
})?;
// Nesting past the document model's cap could never be saved; reject the file with the
// actionable limit.
psd_import::check_group_depth(&file)?;
let preflight_error = std::cell::RefCell::new(None);
let parsed = parse(
&|file| {
// Only an import that keeps the layer tree is bound by the group nesting cap.
let depth = if psd_import::can_recover_layers(file) { psd_import::check_group_depth(file) } else { Ok(()) };
let checked = depth.and_then(|()| psd_budget::check(file, pixel_limit));
if let Err(error) = checked {
*preflight_error.borrow_mut() = Some(error);
return Err(PsdError::LimitExceeded("PSD import preflight refused the file"));
}
Ok(psd_import::merged_needed(file))
},
&psd_import::can_recover_layers,
);
if let Some(error) = preflight_error.into_inner() {
return Err(error);
}
let (file, merged) = parsed.map_err(|error| match error {
PsdError::Read(message) => IoError::Read(message),
PsdError::OutOfMemory(message) => IoError::OutOfMemory(message.to_string()),
error => error.into(),
})?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
// Read before the conversion, which moves the global blocks into the document.
let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data));
let (mut document, warnings, psd_damaged, read_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?;
// The file became unreadable while its layers were read from it (`import_file_for_open_with`):
// the open fails, rather than opening with those layers empty.
if let Some(e) = read_error {
return Err(IoError::Read(e.to_string()));
let (mut document, warnings, psd_damaged, fatal_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?;
// Source reads and allocation failures fail the entire open; partial layers are discarded.
if let Some(e) = fatal_error {
return Err(e);
}
*damaged = psd_damaged;
document.name = name.to_string();
@@ -436,14 +469,23 @@ pub fn import_file_for_open_with(
let bytes = photocraft_format::read_file(path).map_err(read_failed)?;
return import_for_open_with(name, &bytes, opts, ctl);
}
import_source_for_open_with(name, photocraft_psd::Source::new(source), ctl)
import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES))
}
/// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source.
pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> {
import_source_with_limit(name, source, ctl, DEFAULT_PSD_IMPORT_PIXEL_BYTES)
}
fn import_source_with_limit(
name: &str,
source: photocraft_psd::Source,
ctl: &photocraft_raster::Interrupt,
pixel_limit: u64,
) -> Result<(ImportResult, bool), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut damaged = false;
let r = import_psd(name, ctl, &mut damaged, |want, recover| PsdFile::from_source_and_merged_recovering(source, want, recover))?;
let r = import_psd(name, ctl, &mut damaged, pixel_limit, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(1.0);
Ok((r, damaged))
@@ -466,7 +508,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
// Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus
// preview_never_saves_back_to_its_native_or_renamed_source).
if is_psd(bytes) {
return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover));
return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| {
PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)
});
}
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
return affinity::import(name, bytes);
@@ -499,9 +543,11 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
// A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of
// `codec: unrecognized image format` (#5258). Magic already returned above.
if is_psd_input(name, bytes) {
return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover));
return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| {
PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)
});
}
flat::import_flat(name, bytes)
flat::import_flat_with_limit(name, bytes, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES))
}
/// Extension names can be wrong (for example, an image downloaded as WebP and renamed `.svg`).
+48 -6
View File
@@ -47,19 +47,48 @@ fn invert_sample(bytes: &mut [u8], s: SampleType) {
/// are filled with `fill[c]` (a native-endian encoded sample). Channels whose
/// `invert[c]` is set are inverted (PSD stores CMYK as `max - ink`).
pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> Vec<u8> {
let mut out = vec![0u8; n * planes.len() * s.bytes()];
interleave_into(planes, fill, n, s, invert, &mut out);
out
}
/// Fallible interleave for file imports. Validate sizes and missing-plane fills before
/// workers write disjoint slices of one reserved output buffer.
pub fn try_interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> photocraft_psd::Result<Vec<u8>> {
use photocraft_psd::PsdError;
let plane_bytes = n.checked_mul(s.bytes()).ok_or(PsdError::LimitExceeded("interleave size overflow"))?;
let len = plane_bytes.checked_mul(planes.len()).ok_or(PsdError::LimitExceeded("interleave size overflow"))?;
if len as u64 > photocraft_psd::compression::MAX_DECODED_BYTES {
return Err(PsdError::LimitExceeded("interleave exceeds MAX_DECODED_BYTES"));
}
if n > 0 && planes.is_empty() {
return Err(PsdError::Invalid("interleave needs at least one channel".into()));
}
for (c, plane) in planes.iter().enumerate() {
if plane.is_none_or(|p| p.len() < plane_bytes) && fill.get(c).is_none_or(|f| f.len() != s.bytes()) {
return Err(PsdError::Invalid("interleave fill has the wrong sample size".into()));
}
}
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory to interleave PSD pixels"))?;
out.resize(len, 0);
interleave_into(planes, fill, n, s, invert, &mut out);
Ok(out)
}
fn interleave_into(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool], out: &mut [u8]) {
if out.is_empty() {
return;
}
let bps = s.bytes();
let ch = planes.len();
let row = ch * bps;
let mut out = vec![0u8; n * row];
if out.is_empty() {
return out;
}
let bs = bands(n);
let step = bs.first().map_or(n, ExactSizeIterator::len) * row;
par_map(bs.into_iter().zip(out.chunks_mut(step)).collect(), |(band, part)| {
for (c, plane) in planes.iter().enumerate() {
let src = plane.and_then(|p| p.get(band.start * bps..)).unwrap_or_default();
let inv = src.len() >= bps && invert[c];
let inv = src.len() >= bps && invert.get(c).copied().unwrap_or(false);
let fill = fill.get(c).map(Vec::as_slice).unwrap_or_default();
match s {
SampleType::U8 => write_channel(part, ch, c, src, fill, |[v]| [if inv { 255 - v } else { v }]),
@@ -74,7 +103,6 @@ pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: Sampl
}
}
});
out
}
fn write_channel<const N: usize>(out: &mut [u8], ch: usize, c: usize, src: &[u8], fill: &[u8], decode: impl Fn([u8; N]) -> [u8; N]) {
@@ -325,6 +353,20 @@ mod tests {
}
}
#[test]
fn fallible_interleave_checks_sizes_and_missing_plane_fills() {
assert!(try_interleave(&[None], &[vec![0]], usize::MAX, SampleType::F32, &[]).is_err());
assert!(try_interleave(&[None], &[], 1, SampleType::U8, &[]).is_err());
assert!(try_interleave(&[], &[], 1, SampleType::U8, &[]).is_err());
assert!(try_interleave(&[None], &[vec![0]], usize::MAX / 2, SampleType::U8, &[]).is_err());
for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
let plane = vec![1; 1001 * s.bytes()];
let planes = [Some(plane.as_slice()), None];
let fill = vec![zero_sample(s), max_sample(s)];
assert_eq!(try_interleave(&planes, &fill, 1001, s, &[true, false]).unwrap(), interleave(&planes, &fill, 1001, s, &[true, false]));
}
}
#[test]
fn interleave_roundtrip_all_depths() {
for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
+133
View File
@@ -0,0 +1,133 @@
//! Conservative preflight for the main PSD pixel paths. This bounds decoded layer/mask/
//! merged pixels, not parser metadata, patterns or smart-filter caches (separate limits).
//!
//! Reserve the sum of all possible retained tiles and the largest workspace, without credit
//! for pruning or tile sharing. Reserving before any worker starts makes scheduling irrelevant.
use photocraft_geom::TILE_SIZE;
use photocraft_psd::{
PsdFile,
layer::{CHANNEL_REAL_USER_MASK, CHANNEL_USER_MASK, Rect},
};
use crate::IoError;
/// Default allowance for PSD layer, mask and merged-image pixels, including conversion
/// workspace and tile padding. Other format/parser limits still apply. Callers may lower it.
pub const DEFAULT_PSD_IMPORT_PIXEL_BYTES: u64 = if cfg!(target_arch = "wasm32") { 1 << 30 } else { 2 << 30 };
#[derive(Default)]
struct ImportBudget {
retained: u64,
workspace: u64,
}
fn overflow() -> IoError {
IoError::Unsupported("PSD import pixel memory estimate overflow".into())
}
// inflate_checked uses at least 8 KiB per stream, even for a one-pixel plane.
fn inflate_scratch(plane_bytes: u64, channels: u64) -> Result<u64, IoError> {
mul(plane_bytes.saturating_add(1).clamp(8192, 1 << 20), channels)
}
fn mul(a: u64, b: u64) -> Result<u64, IoError> {
a.checked_mul(b).ok_or_else(overflow)
}
impl ImportBudget {
fn retain(&mut self, bytes: u64) -> Result<(), IoError> {
self.retained = self.retained.checked_add(bytes).ok_or_else(overflow)?;
Ok(())
}
fn scratch(&mut self, bytes: u64) {
self.workspace = self.workspace.max(bytes);
}
fn required(&self) -> Result<u64, IoError> {
self.retained.checked_add(self.workspace).ok_or_else(overflow)
}
fn check(&self, limit: u64) -> Result<(), IoError> {
let required = self.required()?;
if required > limit {
return Err(IoError::PsdImportBudget { required, limit });
}
Ok(())
}
fn surface(&mut self, rect: Rect, channels: u64, sample: u64) -> Result<(), IoError> {
if rect.is_empty() {
return Ok(());
}
let tile = i64::from(TILE_SIZE);
// Division must round down for negative offsets: even a 2x2 rect straddling the
// origin occupies four tiles. Widen first, including the exclusive right/bottom edge.
let nx = (i64::from(rect.right) - 1).div_euclid(tile) - i64::from(rect.left).div_euclid(tile) + 1;
let ny = (i64::from(rect.bottom) - 1).div_euclid(tile) - i64::from(rect.top).div_euclid(tile) + 1;
self.retain(mul(mul(mul(nx as u64, ny as u64)?, (TILE_SIZE as u64).pow(2))?, mul(channels, sample)?)?)
}
}
/// No decoding here: even a compact ZIP stream must be refused before inflation. The sum
/// deliberately counts full decoded planes for every compression method, plus their row
/// buffers, interleave output and float conversion workspace. This is an upper estimate,
/// rather than a promise that an allocator or OS can satisfy an accepted import.
pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> {
let mut budget = ImportBudget::default();
let h = &file.header;
h.validate()?;
let sample = u64::from(h.depth.div_ceil(8));
let cc = match h.color_mode {
// Unknown modes use the RGB fallback, including its alpha channel.
photocraft_psd::ColorMode::Unknown(_) => 3,
mode => u64::from(mode.color_channels().unwrap_or(3)),
};
if super::psd_import::can_recover_layers(file) {
for rec in file.layers() {
if !rec.rect.is_empty() && rec.channels.iter().any(|c| c.id >= 0 || c.id == -1) {
let (w, hh) = rec.rect.size()?;
let pixels = mul(w as u64, hh as u64)?;
budget.surface(rec.rect, cc + 1, sample)?;
// Whole ZIP planes + band planes + interleave + temporary float pixels.
// Counting a full layer for each band buffer also covers a single very wide row.
let workspace = mul(pixels, mul(cc + 1, sample * 3 + 4)?)?.checked_add(inflate_scratch(mul(pixels, sample)?, cc + 1)?).ok_or_else(overflow)?;
// RLE row indexes live beside decoded planes.
budget.scratch(workspace.checked_add(mul(hh as u64 + 1, (cc + 1) * 8)?).ok_or_else(overflow)?);
}
if let Some(mask) = rec.layer_mask() {
for (id, rect) in [(CHANNEL_USER_MASK, mask.rect), (CHANNEL_REAL_USER_MASK, mask.real.map_or(mask.rect, |m| m.rect))] {
if rec.channel(id).is_none() || rect.is_empty() {
continue;
}
let (w, hh) = rect.size()?;
budget.surface(rect, 1, sample)?;
// The layer's ZIP decoders have been dropped before record_mask runs.
let pixels = mul(w as u64, hh as u64)?;
budget.scratch(mul(pixels, sample * 3 + 4)?.checked_add(inflate_scratch(mul(pixels, sample)?, 1)?).ok_or_else(overflow)?);
}
}
}
}
if super::psd_import::merged_needed(file) {
let pixels = mul(u64::from(h.width), u64::from(h.height))?;
let channels = u64::from(h.channels);
let canvas = Rect::from_xywh(0, 0, h.width, h.height);
// Multichannel and extra channels become individual grayscale surfaces. Reserving
// their tiles separately matters for images smaller than a tile.
budget.surface(canvas, channels.max(cc + 1), sample.max(1))?;
// A fallback surface can coexist with the layers when none produced usable pixels.
budget.surface(canvas, cc + 1, sample.max(1))?;
// The merged planes stay alive while layers are built.
let merged = mul(mul(h.row_bytes() as u64, u64::from(h.height))?, channels)?;
budget.retain(merged)?;
// Include float expansion/readback and RGBA fallback, even for packed bitmap input.
let converted = mul(pixels, mul(channels.max(cc + 1), sample * 3 + 12)?)?;
budget.scratch(converted.checked_add(inflate_scratch(merged, 1)?).ok_or_else(overflow)?);
}
budget.check(limit)
}
#[cfg(test)]
mod tests;
+144
View File
@@ -0,0 +1,144 @@
use super::*;
use photocraft_psd::{ColorMode, Compression, Version, testgen};
#[test]
fn retained_storage_is_summed_but_workspace_is_reused() {
let mut budget = ImportBudget::default();
budget.retain(40).unwrap();
budget.retain(20).unwrap();
budget.scratch(30);
budget.scratch(10);
assert!(budget.check(90).is_ok());
assert!(matches!(budget.check(89), Err(IoError::PsdImportBudget { required: 90, limit: 89 })));
budget.retain(u64::MAX).unwrap_err();
budget.workspace = u64::MAX;
assert!(budget.required().is_err());
}
#[test]
fn tiny_negative_offset_rectangles_pay_for_every_touched_tile() {
let mut aligned = ImportBudget::default();
aligned.surface(Rect::from_xywh(0, 0, 2, 2), 4, 2).unwrap();
let mut offset = ImportBudget::default();
offset.surface(Rect::from_xywh(-1, -1, 2, 2), 4, 2).unwrap();
assert_eq!(offset.required().unwrap(), aligned.required().unwrap() * 4);
offset.surface(Rect::default(), 4, 2).unwrap();
assert_eq!(offset.required().unwrap(), aligned.required().unwrap() * 4);
}
fn estimate(file: &PsdFile) -> u64 {
match check(file, 0).unwrap_err() {
IoError::PsdImportBudget { required, .. } => required,
error => panic!("unexpected error: {error}"),
}
}
#[test]
fn individually_fitting_layers_cannot_each_spend_the_import_allowance() {
let mut file = testgen::small(Version::Psd, Compression::Zip);
let record = file.layers()[0].clone();
file.layer_info.as_mut().unwrap().layers = vec![record.clone()];
let one = estimate(&file);
assert!(check(&file, one).is_ok());
file.layer_info.as_mut().unwrap().layers = vec![record; 8];
assert!(matches!(check(&file, one), Err(IoError::PsdImportBudget { .. })));
}
#[test]
fn large_off_canvas_layer_is_rejected_without_decoding_its_tiny_data() {
let mut file = testgen::small(Version::Psd, Compression::Zip);
file.header.width = 1;
file.header.height = 1;
file.layers_mut()[0].rect = Rect::from_xywh(-10_000, -10_000, 20_000, 20_000);
assert!(matches!(check(&file, DEFAULT_PSD_IMPORT_PIXEL_BYTES), Err(IoError::PsdImportBudget { .. })));
// Both ordinary import routes must fail before reading a deliberately missing merged
// section. No enormous decoded plane is ever constructed by this test.
let mut bytes = file.to_bytes().unwrap();
bytes.truncate(bytes.len() - file.image_data.data.len() - 2);
assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdImportBudget { .. })));
let source = photocraft_psd::Source::new(bytes);
assert!(matches!(crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdImportBudget { .. })));
}
#[test]
fn user_mask_bounds_count_even_when_the_layer_is_small() {
let mut file = testgen::small(Version::Psd, Compression::Raw);
let before = estimate(&file);
// The generator's first record has a user mask. Modify its parsed mask in place.
if let photocraft_psd::layer::MaskData::Mask(mask) = &mut file.layers_mut()[0].mask {
mask.rect = Rect::from_xywh(0, 0, 20_000, 20_000);
} else {
panic!("fixture needs a parsed mask");
}
assert!(estimate(&file) > before);
assert!(matches!(check(&file, before), Err(IoError::PsdImportBudget { .. })));
}
#[test]
fn merged_bitmap_and_multichannel_expansion_are_budgeted() {
for (mode, depth) in [(ColorMode::Bitmap, 1), (ColorMode::Multichannel, 8), (ColorMode::Rgb, 32)] {
let mut file = testgen::merged_only(Version::Psb, mode, depth, Compression::Zip, 2, 2);
let before = estimate(&file);
assert!(check(&file, before).is_ok());
file.header.width = 60_000;
file.header.height = 60_000;
assert!(matches!(check(&file, DEFAULT_PSD_IMPORT_PIXEL_BYTES), Err(IoError::PsdImportBudget { .. })));
}
}
#[test]
fn a_custom_limit_is_fatal_for_interactive_and_headless_imports() {
let file = testgen::small(Version::Psd, Compression::Zip);
let bytes = file.to_bytes().unwrap();
let limit = estimate(&file);
let opts = crate::ImportOptions { psd_max_pixel_bytes: limit, ..Default::default() };
assert!(crate::import_with_options("small.psd", &bytes, &opts).is_ok());
let opts = crate::ImportOptions { psd_max_pixel_bytes: limit - 1, ..opts };
for result in [crate::import_with_options("small.psd", &bytes, &opts), crate::import_for_open("small.psd", &bytes, &opts).map(|(result, _)| result)] {
assert!(matches!(result, Err(IoError::PsdImportBudget { .. })));
}
}
#[test]
fn accepted_off_canvas_pixels_and_depths_are_preserved() {
for depth in [8, 16, 32] {
for compression in Compression::ALL {
let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, compression);
assert!(check(&file, DEFAULT_PSD_IMPORT_PIXEL_BYTES).is_ok());
let (doc, _) = crate::psd_to_document(&file);
assert_eq!(doc.depth, crate::pixels::sample_for_depth(depth));
let bytes = file.to_bytes().unwrap();
let opened = crate::import("small.psd", &bytes).unwrap().document;
let rect = photocraft_geom::Rect::new(-8, -8, 32, 24);
assert_eq!(photocraft_compose::render(&opened, rect), photocraft_compose::render(&doc, rect));
}
}
}
#[test]
fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() {
let mut file = testgen::small(Version::Psd, Compression::Zip);
file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 20000, 20000);
let (doc, warnings) = crate::psd_to_document(&file);
assert!(doc.layers.is_empty());
assert!(warnings.iter().any(|warning| warning.contains("pixel memory")));
}
/// An unknown colour mode imports as RGB (`import_format`), layers included, so it must pay
/// for them: a layered file can't dodge the allowance by carrying mode 5.
#[test]
fn an_unknown_color_mode_pays_for_the_layers_it_imports_as_rgb() {
let rgb = testgen::small(Version::Psd, Compression::Raw);
assert!(!rgb.layers().is_empty() && !super::super::psd_import::merged_needed(&rgb), "the fixture must import its layers alone");
let mut unknown = rgb.clone();
unknown.header.color_mode = photocraft_psd::ColorMode::Unknown(5);
assert!(unknown.header.validate().is_ok());
let required = estimate(&unknown);
assert!(required >= estimate(&rgb), "the layers import as RGB and are counted");
let bytes = unknown.to_bytes().unwrap();
let opts = crate::ImportOptions { psd_max_pixel_bytes: required - 1, ..Default::default() };
assert!(matches!(crate::import_with_options("mode5.psd", &bytes, &opts), Err(IoError::PsdImportBudget { .. })));
let source = photocraft_psd::Source::new(bytes);
let refused = crate::import_source_with_limit("mode5.psd", source, &photocraft_raster::Interrupt::NONE, required - 1);
assert!(matches!(refused, Err(IoError::PsdImportBudget { .. })), "{:?}", refused.map(|(r, _)| r.warnings));
}
+112 -36
View File
@@ -16,7 +16,7 @@ use photocraft_raster::Surface;
use crate::adjust_map::{self, ADJUSTMENT_KEYS};
use crate::blocks;
use crate::pixels::{interleave, max_sample, sample_for_depth, zero_sample};
use crate::pixels::{max_sample, sample_for_depth, try_interleave, zero_sample};
/// Resources that are mapped to document fields or regenerated on export.
pub(crate) const MAPPED_RESOURCES: [u16; 19] = [
@@ -56,8 +56,8 @@ pub(crate) struct Ctx<'a> {
pub warnings: Vec<String>,
/// Decoding encountered damaged PSD data; interactive opens ask whether to continue.
pub damaged: bool,
/// Failure to read source channel data, which must fail the open.
pub read_error: Option<String>,
/// Source reads and pixel allocation failures must fail the open.
pub fatal_error: Option<crate::IoError>,
/// Document resolution (type sizes are converted to points with it).
pub dpi: f32,
/// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning).
@@ -190,6 +190,12 @@ struct Placement {
}
impl Ctx<'_> {
fn allocation_failed(&mut self, error: impl std::fmt::Display) {
let message = format!("PSD pixel allocation failed: {error}");
self.warn(message.clone());
self.fatal_error.get_or_insert(crate::IoError::OutOfMemory(message));
}
fn warn(&mut self, s: impl Into<String>) {
self.warnings.push(s.into());
}
@@ -205,7 +211,11 @@ impl Ctx<'_> {
/// (`true`); damaged data is warned about, its layer left empty (`false`).
fn channel_failed(&mut self, name: &str, id: i16, e: &photocraft_psd::PsdError) -> bool {
if let photocraft_psd::PsdError::Read(msg) = e {
self.read_error.get_or_insert_with(|| format!("layer \"{name}\": {msg}"));
self.fatal_error.get_or_insert_with(|| crate::IoError::Read(format!("layer \"{name}\": {msg}")));
return true;
}
if let photocraft_psd::PsdError::OutOfMemory(_) = e {
self.allocation_failed(format!("layer \"{name}\" channel {id}: {e}"));
return true;
}
self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty"));
@@ -245,7 +255,7 @@ impl Ctx<'_> {
/// Decodes a PSD layer channel, marking the document damaged if its data is unreadable.
fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option<Vec<u8>> {
rec.channel(id)?;
if self.read_error.is_some() {
if self.fatal_error.is_some() {
return None;
}
match rec.decode_channel(id, self.file.header.depth, self.file.header.version) {
@@ -262,7 +272,7 @@ impl Ctx<'_> {
fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface {
let r = rec.rect;
// Once the file couldn't be read the open fails: nothing more is decoded.
if r.is_empty() || r.size().is_err() || self.read_error.is_some() {
if r.is_empty() || r.size().is_err() || self.fatal_error.is_some() {
return Surface::new(self.fmt);
}
let (w, h) = r.size().unwrap_or((0, 0));
@@ -313,11 +323,20 @@ impl Ctx<'_> {
None => refs.push(None),
}
}
let mut bytes = interleave(&refs, &fill, w * (b1 - b0), s, &invert);
let mut bytes = match try_interleave(&refs, &fill, w * (b1 - b0), s, &invert) {
Ok(bytes) => bytes,
Err(error) => {
self.allocation_failed(format!("layer \"{name}\": {error}"));
return Surface::new(self.fmt);
}
};
if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 {
crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true);
}
surf.write_interleaved(Rect::new(r.left, r.top + b0 as i32, r.right, r.top + b1 as i32), &bytes);
if let Err(error) = surf.try_write_interleaved(Rect::new(r.left, r.top + b0 as i32, r.right, r.top + b1 as i32), &bytes) {
self.allocation_failed(format!("layer \"{name}\": {error}"));
return Surface::new(self.fmt);
}
}
surf.prune();
// A white background, a solid fill's cache: one tile per value, shared across layers.
@@ -342,8 +361,17 @@ impl Ctx<'_> {
&& let Some(plane) = self.channel_plane(rec, id, name)
{
let s = self.mask_fmt.sample;
let bytes = interleave(&[Some(&plane)], &[zero_sample(s)], w * h, s, &[false]);
surface.write_interleaved(Rect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes);
let bytes = match try_interleave(&[Some(&plane)], &[zero_sample(s)], w * h, s, &[false]) {
Ok(bytes) => bytes,
Err(error) => {
self.allocation_failed(format!("layer \"{name}\" mask: {error}"));
return None;
}
};
if let Err(error) = surface.try_write_interleaved(Rect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes) {
self.allocation_failed(format!("layer \"{name}\" mask: {error}"));
return None;
}
surface.prune();
surface.share_uniform_tiles(&mut self.uniform);
}
@@ -549,7 +577,8 @@ impl Ctx<'_> {
// shape's stored pixels hold the shape alone, without the fill its density and feather
// show beyond the path: render it too.
let soft = sh.has_soft_mask() && sh.fill.is_some();
if soft || ((rec.rect.is_empty() || rec.rect.size().is_err()) && (!sh.path.subpaths.is_empty() || sh.path.inverted)) {
if self.fatal_error.is_none() && (soft || ((rec.rect.is_empty() || rec.rect.size().is_err()) && (!sh.path.subpaths.is_empty() || sh.path.inverted)))
{
let canvas = Rect::new(0, 0, self.file.header.width as i32, self.file.header.height as i32);
sh.cache = Some(photocraft_vector::render_shape(&sh, self.fmt, canvas));
}
@@ -816,8 +845,8 @@ fn preserved_blocks(rec: &LayerRecord) -> Vec<([u8; 4], Arc<Vec<u8>>)> {
rec.blocks.iter().filter(|b| !REGENERATED.contains(&&b.key)).map(|b| (b.key, Arc::new(b.data.clone()))).collect()
}
fn be_to_ne_plane(plane: &[u8], s: SampleType, n: usize) -> Vec<u8> {
interleave(&[Some(plane)], &[zero_sample(s)], n, s, &[false])
fn be_to_ne_plane(plane: &[u8], s: SampleType, n: usize) -> photocraft_psd::Result<Vec<u8>> {
crate::pixels::try_interleave(&[Some(plane)], &[zero_sample(s)], n, s, &[false])
}
pub(crate) fn unicode_names(data: &[u8]) -> Vec<String> {
@@ -854,7 +883,7 @@ fn flat_composite(
match file.composite_rgba8() {
Ok(img) => return Ok(img),
// Over the output budget: the fallback below would make the same allocation.
Err(e @ PsdError::LimitExceeded(_)) => return Err(e),
Err(e @ (PsdError::LimitExceeded(_) | PsdError::OutOfMemory(_))) => return Err(e),
Err(_) => {}
}
let all = match merged {
@@ -871,7 +900,7 @@ fn flat_composite(
.ok_or(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"))?;
let plane = h.row_bytes().checked_mul(hh).ok_or(PsdError::LimitExceeded("plane size overflow"))?;
let mut data = Vec::new();
data.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for RGBA output"))?;
data.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for RGBA output"))?;
data.resize(len, 255u8);
for c in 0..3.min(usize::from(h.channels)) {
let bytes = merged_plane(all, c, plane).ok_or_else(|| PsdError::Invalid("channel size mismatch".into()))?;
@@ -885,22 +914,24 @@ fn flat_composite(
/// Writes RGBA8 `data` covering `canvas` into `s`, a band of tile rows at a time (no full-size
/// float copy of the image).
fn write_rgba8(s: &mut Surface, canvas: Rect, data: &[u8]) {
fn write_rgba8(s: &mut Surface, canvas: Rect, data: &[u8]) -> Result<(), String> {
let fmt = s.format();
let row = (canvas.width() as usize).saturating_mul(4);
let mut vals = Vec::new();
let mut vals: Vec<f32> = Vec::new();
let mut y = canvas.y0;
while y < canvas.y1 {
let band = Rect::new(canvas.x0, y, canvas.x1, y.saturating_add(TILE_SIZE).min(canvas.y1));
let start = ((y - canvas.y0) as usize).saturating_mul(row);
let Some(rows) = data.get(start..start.saturating_add((band.height() as usize).saturating_mul(row))) else { break };
vals.clear();
vals.try_reserve(rows.len().saturating_mul(fmt.channels()) / 4).map_err(|e| e.to_string())?;
for p in rows.as_chunks::<4>().0 {
vals.extend(photocraft_raster::from_rgba(&fmt, p.map(|x| f32::from(x) / 255.0)));
}
s.write_region(band, &vals);
s.try_write_region(band, &vals).map_err(|e| e.to_string())?;
y = band.y1;
}
Ok(())
}
pub(crate) fn parse_guides(data: &[u8], doc: &mut Document) {
@@ -981,7 +1012,7 @@ pub(crate) fn psd_to_document_owned(
mut file: PsdFile,
ctl: &photocraft_raster::Interrupt,
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
) -> Option<(Document, Vec<String>, bool, Option<String>)> {
) -> Option<(Document, Vec<String>, bool, Option<crate::IoError>)> {
let global = file
.global_blocks
.iter_mut()
@@ -991,7 +1022,7 @@ pub(crate) fn psd_to_document_owned(
(b.signature, b.key, Arc::new(data))
})
.collect();
psd_to_document_global(&file, ctl, decoded, global)
psd_to_document_global(&file, ctl, decoded, global, true)
}
/// Whether `file` stores spot planes the way earlier PhotoCraft versions (releases 0.1.0 to
@@ -1068,9 +1099,11 @@ pub(crate) fn merged_needed(file: &PsdFile) -> bool {
}
/// A damaged merged preview need not prevent opening independently stored layers (#6152).
/// Other modes are imported flattened, so their merged image cannot be discarded.
/// Other modes are imported flattened, so their merged image cannot be discarded. This is also
/// the decision the memory budget makes about layer pixels, so it follows [`import_format`]
/// (an unknown mode imports as RGB) rather than listing modes a second time.
pub(crate) fn can_recover_layers(file: &PsdFile) -> bool {
matches!(file.header.color_mode, PsdMode::Grayscale | PsdMode::Rgb | PsdMode::Cmyk | PsdMode::Lab) && file.header.depth != 1 && !file.layers().is_empty()
import_format(file).1 && !file.layers().is_empty()
}
fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Document, layered: bool, multichannel: bool, warnings: &mut Vec<String>) -> bool {
@@ -1163,7 +1196,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
) -> Option<(Document, Vec<String>, bool)> {
let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect();
psd_to_document_global(file, ctl, decoded, global).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged))
psd_to_document_global(file, ctl, decoded, global, false).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged))
}
fn psd_to_document_global(
@@ -1171,7 +1204,16 @@ fn psd_to_document_global(
ctl: &photocraft_raster::Interrupt,
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
global: Vec<PsdGlobalBlock>,
) -> Option<(Document, Vec<String>, bool, Option<String>)> {
preflighted: bool,
) -> Option<(Document, Vec<String>, bool, Option<crate::IoError>)> {
// Legacy conversion APIs return warnings rather than Result. Reject before metadata or
// pixels are decoded, and retain the fatal error for the ordinary import path. An import
// that checked the file against its own limit first (`preflighted`) does not estimate twice.
if !preflighted && let Err(error) = crate::psd_budget::check(file, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) {
let message = error.to_string();
let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
return Some((doc, vec![message], true, Some(error)));
}
let (mode, layered, multichannel, depth) = import_format(file);
let h = &file.header;
let mut warnings = Vec::new();
@@ -1192,7 +1234,7 @@ fn psd_to_document_global(
cmyk: fmt.mode == ColorMode::Cmyk,
warnings,
damaged,
read_error: None,
fatal_error: None,
dpi: doc.resolution_dpi,
txt2: global.iter().find(|(_, k, _)| k == b"Txt2").and_then(|(_, _, d)| photocraft_text::psd::parse_txt2(d)),
filter_effects: Vec::new(),
@@ -1231,7 +1273,7 @@ fn psd_to_document_global(
finish_import(doc, cx, ctl)
}
fn finish_import(mut doc: Document, mut cx: Ctx<'_>, ctl: &photocraft_raster::Interrupt) -> Option<(Document, Vec<String>, bool, Option<String>)> {
fn finish_import(mut doc: Document, mut cx: Ctx<'_>, ctl: &photocraft_raster::Interrupt) -> Option<(Document, Vec<String>, bool, Option<crate::IoError>)> {
let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, data)| data.clone());
let (comps, applied, state, warnings) = crate::comps_map::decode_comps(raw_comps.as_deref().map(Vec::as_slice), &doc);
(doc.layer_comps, doc.last_applied_comp, doc.last_document_state) = (comps, applied, state);
@@ -1242,7 +1284,7 @@ fn finish_import(mut doc: Document, mut cx: Ctx<'_>, ctl: &photocraft_raster::In
return None;
}
ctl.progress(1.0);
Some((doc, cx.warnings, cx.damaged, cx.read_error))
Some((doc, cx.warnings, cx.damaged, cx.fatal_error))
}
fn decode_merged(
@@ -1258,6 +1300,9 @@ fn decode_merged(
}
ctl.progress(0.1);
if let Err(error) = &merged {
if matches!(error, photocraft_psd::PsdError::OutOfMemory(_)) {
cx.allocation_failed(format!("merged image: {error}"));
}
cx.warn_unreadable_data(format!("merged image could not be decoded: {error}"));
if can_recover_layers(file) {
cx.warn_unreadable_data("extra alpha/spot channels in the merged image could not be recovered");
@@ -1273,6 +1318,9 @@ fn decode_merged(
}
fn import_decoded_content(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_>) {
if cx.fatal_error.is_some() {
return;
}
if import.multichannel {
import_multichannel(import.file, import.merged, doc, cx);
} else if import.layered {
@@ -1280,7 +1328,11 @@ fn import_decoded_content(import: DecodedImport<'_>, doc: &mut Document, cx: &mu
} else {
import_flattened(import.file, import.merged, import.sizes, import.canvas, import.fmt, doc, cx);
}
import_extra_channels(import, doc, cx);
// A layer allocation that failed above makes the whole import fail: more full-size
// planes here would only risk the abort the failure was reported to avoid.
if cx.fatal_error.is_none() {
import_extra_channels(import, doc, cx);
}
}
fn import_multichannel(file: &PsdFile, merged: &Option<photocraft_psd::Result<Vec<u8>>>, doc: &mut Document, cx: &mut Ctx<'_>) {
@@ -1317,11 +1369,17 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_
fill.push(max_sample(depth));
let mut inv = vec![cx.cmyk; cc];
inv.push(false);
let mut bytes = interleave(&planes, &fill, n, depth, &inv);
let mut bytes = match crate::pixels::try_interleave(&planes, &fill, n, depth, &inv) {
Ok(bytes) => bytes,
Err(error) => return cx.allocation_failed(format!("merged image: {error}")),
};
if fmt.mode == ColorMode::Lab && depth == SampleType::U16 {
crate::pixels::lab16_chroma(&mut bytes, cc + 1, true);
}
let mut surface = Surface::from_interleaved(fmt, canvas, &bytes);
let mut surface = Surface::new(fmt);
if let Err(error) = surface.try_write_interleaved(canvas, &bytes) {
return cx.allocation_failed(format!("merged image: {error}"));
}
if alpha_idx.is_some() {
let white = photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]);
let mut vals = Vec::new();
@@ -1335,7 +1393,9 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_
px[c] = if a <= 0.0 { 0.0 } else { crate::pixels::unmatte(px[c], a, white[c]) };
}
}
surface.write_region(band, &vals);
if let Err(error) = surface.try_write_region(band, &vals) {
return cx.allocation_failed(format!("merged image: {error}"));
}
y = band.y1;
}
}
@@ -1396,10 +1456,21 @@ fn import_flattened(
}
}
let mut surface = Surface::new(fmt);
write_rgba8(&mut surface, canvas, &img.data);
let written = write_rgba8(&mut surface, canvas, &img.data);
drop(img);
surface.prune();
doc.layers.push(flat_background(surface));
match written {
Ok(()) => {
surface.prune();
doc.layers.push(flat_background(surface));
}
Err(error) => cx.allocation_failed(format!("flattened image: {error}")),
}
}
Err(error @ photocraft_psd::PsdError::OutOfMemory(_)) => cx.allocation_failed(format!("flattened image: {error}")),
// A flattened file has nothing but its merged image: a failed source read fails the open
// rather than opening it without the image.
Err(photocraft_psd::PsdError::Read(message)) => {
cx.fatal_error.get_or_insert(crate::IoError::Read(message));
}
Err(_) if matches!(merged, Some(Err(_))) => {}
Err(error) => cx.warn_unreadable_data(format!("the image could not be read: {error}")),
@@ -1437,12 +1508,17 @@ fn import_extra_channels(import: DecodedImport<'_>, doc: &mut Document, cx: &mut
cx.warn_unreadable_data(format!("merged extra channel {idx} is incomplete and was not imported"));
break;
};
let mut raw = be_to_ne_plane(p, depth, n);
let mut raw = match be_to_ne_plane(p, depth, n) {
Ok(raw) => raw,
Err(error) => return cx.allocation_failed(format!("extra channel {idx}: {error}")),
};
if k < straight_from && photoshop_spots.get(k).copied().unwrap_or(false) {
crate::channel_map::photoshop_spot_plane(&mut raw, depth);
}
let mut s = Surface::new(cx.mask_fmt);
s.write_interleaved(canvas, &raw);
if let Err(error) = s.try_write_interleaved(canvas, &raw) {
return cx.allocation_failed(format!("extra channel {idx}: {error}"));
}
s.prune();
let name = names.get(k).cloned().unwrap_or_else(|| format!("Alpha {}", k + 1));
doc.channels.push(AlphaChannel::new(name, s));
+82
View File
@@ -388,3 +388,85 @@ fn layer_bands_end_on_tile_rows_and_cover_the_layer() {
// A small layer is one band.
assert_eq!(band_rows(0, 2000, 8000), vec![(0, 2000)]);
}
/// An allocation or read that fails while the layers are built fails the open, and the merged
/// image's extra channels are not converted on the way out: that is another full plane per
/// channel, asked for after the import was already reported as failing.
#[test]
fn a_fatal_layer_error_skips_the_extra_channel_conversion() {
use photocraft_psd::ReadAt;
struct Failing {
bytes: Vec<u8>,
data: Vec<(u64, u64)>,
armed: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl ReadAt for Failing {
fn len(&self) -> u64 {
self.bytes.len() as u64
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> {
let end = offset + buf.len() as u64;
if self.armed.load(std::sync::atomic::Ordering::SeqCst) && self.data.iter().any(|&(a, b)| offset < b && end > a) {
return Err(PsdError::Read("the drive went away".into()));
}
self.bytes.as_slice().read_at(offset, buf)
}
}
let bytes = crate::psd_export::document_to_psd(&channels_document(SampleType::U8)).to_bytes().unwrap();
let whole = PsdFile::from_bytes(&bytes).unwrap();
assert!(merged_needed(&whole), "the extra channels come from the merged image");
let converted = psd_to_document_global(&whole, &photocraft_raster::Interrupt::NONE, None, Vec::new(), false).unwrap();
assert!(converted.3.is_none() && converted.0.channels.len() == 3, "the control file converts its channels");
let lazy = PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap();
let data: Vec<(u64, u64)> =
lazy.layers().iter().flat_map(|l| &l.channels).filter_map(|c| c.stored.as_ref()).filter(|s| s.len > 0).map(|s| (s.offset, s.offset + s.len)).collect();
assert!(!data.is_empty());
// Reads fail only once the file is parsed: the layers decode lazily from the source.
let armed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let file = PsdFile::from_source(photocraft_psd::Source::new(Failing { bytes, data, armed: armed.clone() })).unwrap();
armed.store(true, std::sync::atomic::Ordering::SeqCst);
let (doc, _, _, fatal) = psd_to_document_global(&file, &photocraft_raster::Interrupt::NONE, None, Vec::new(), false).unwrap();
assert!(matches!(fatal, Some(crate::IoError::Read(_))), "{fatal:?}");
assert!(doc.channels.is_empty(), "no extra channel was converted after the failure");
}
/// Only a failed allocation fails the open; a size limit or damaged compressed data still
/// leaves the layer empty with a damage warning, and the rest of the file opens. A failed
/// allocation names the layer and its channel.
#[test]
fn only_allocation_failures_are_fatal_to_a_layer_channel() {
let file = testgen::small(Version::Psd, Compression::Raw);
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
let mut cx = Ctx {
file: &file,
global: Vec::new(),
fmt,
mask_fmt: PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false),
cc: 3,
cmyk: false,
warnings: Vec::new(),
damaged: false,
fatal_error: None,
dpi: 72.0,
txt2: None,
filter_effects: Vec::new(),
filter_masks: Default::default(),
unfiltered: Default::default(),
unfiltered_bytes: 0,
smart_contents: Default::default(),
plld_sizes: Default::default(),
vector_previews: Default::default(),
ctl: photocraft_raster::Interrupt::NONE,
done: 0,
uniform: Default::default(),
total: 0,
};
assert!(!cx.channel_failed("Layer 1", 0, &PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES")));
assert!(cx.fatal_error.is_none() && cx.damaged);
assert!(cx.channel_failed("Layer 1", 2, &PsdError::OutOfMemory("not enough memory for the decoded channel data")));
match cx.fatal_error {
Some(crate::IoError::OutOfMemory(message)) => assert!(message.contains("layer \"Layer 1\" channel 2"), "{message}"),
other => panic!("{other:?}"),
}
}
+49 -26
View File
@@ -21,7 +21,7 @@ use photocraft_raster::Surface;
use crate::flat::{csample, encode_image, image_to_document, layout_for, single_layer, try_buffer};
use crate::psd_export::PsdExportOptions;
use crate::psd_import::psd_to_document;
use crate::psd_import::psd_to_document_owned;
use crate::{ExportOptions, ExportResult, ImportResult, IoError};
/// `true` when saving `doc` as TIFF writes layer data: anything beyond a single Background
@@ -49,7 +49,7 @@ fn set_resource(resources: &mut Vec<ImageResource>, id: u16, data: Option<Vec<u8
}
/// Opens a TIFF whose `img` carries Photoshop layer data in `layers` (its 37724 tag).
pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<ImportResult, IoError> {
pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit: u64) -> Result<ImportResult, IoError> {
let mut warnings = Vec::new();
let (isd, w) = match ImageSourceData::from_bytes(layers) {
Ok(v) => v,
@@ -85,12 +85,6 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
}
// The TIFF's pixels become the PSD's merged image: planar, big-endian, CMYK inverted.
let img = if img.sample_type() == CSample::F16 {
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
std::borrow::Cow::Owned(img.convert(img.layout(), CSample::F32))
} else {
std::borrow::Cow::Borrowed(img)
};
let (mode, color_channels) = match img.layout() {
ChannelLayout::Gray | ChannelLayout::GrayA => (PsdMode::Grayscale, 1),
ChannelLayout::Rgb | ChannelLayout::Rgba => (PsdMode::Rgb, 3),
@@ -103,23 +97,17 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
CSample::F16 | CSample::F32 => 32,
};
let (w, h) = img.dimensions();
let mut data = planar_big_endian(&img, color_channels, mode == PsdMode::Cmyk)?;
let bps = img.sample_type().bytes();
// A half-float image is stored as 32-bit float; it is converted after the budget check, as
// the conversion allocates several times the decoded image.
let bps = if img.sample_type() == CSample::F16 { CSample::F32.bytes() } else { img.sample_type().bytes() };
let plane_len = (w as usize).saturating_mul(h as usize).saturating_mul(bps);
let mut added = 0usize;
for e in img.meta.extra_samples.iter().take(codecs::MAX_EXTRA_SAMPLES) {
match native_plane_to_be(&e.data, bps) {
Ok(be) if be.len() == plane_len => {
data.extend(be);
added += 1;
}
_ => warnings.push("an extra TIFF sample did not match the image and was dropped".into()),
}
}
let channels = u16::try_from(img.layout().channels().saturating_add(added)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
// The budget is checked on the model before the planar copy of the whole image is allocated,
// so an over-budget file is refused without it. The extra samples that fit the image count
// towards the channels the check sees.
let extras = img.meta.extra_samples.iter().take(codecs::MAX_EXTRA_SAMPLES).filter(|e| e.data.len() == plane_len).count();
let channels = u16::try_from(img.layout().channels().saturating_add(extras)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
let header = Header::new(isd.version, w, h, channels, depth, mode);
let image_data = ImageData::new(Compression::Raw, data);
let mut file = isd.into_psd(header, resources, image_data);
let mut file = isd.into_psd(header, resources, ImageData::new(Compression::Raw, Vec::new()));
// Empty `Patt` and the default filter mask are written so Photoshop's block list matches
// a file it saved. They carry nothing the document stores, so they are not kept: a
// round trip would otherwise grow `metadata.psd_global_blocks` on every open.
@@ -130,10 +118,41 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
});
// The same nesting limit as opening a PSD (#2940).
crate::psd_import::check_group_depth(&file)?;
// The planar composite is copied whether or not the budget counts a merged image, so it is
// held against the allowance as well.
let composite = u64::try_from(plane_len.saturating_mul(usize::from(channels))).unwrap_or(u64::MAX);
if composite > pixel_limit {
return Err(photocraft_psd::PsdError::LimitExceeded("the TIFF composite exceeds the import allowance").into());
}
crate::psd_budget::check(&file, pixel_limit - composite)?;
let img = if img.sample_type() == CSample::F16 {
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
std::borrow::Cow::Owned(img.convert(img.layout(), CSample::F32))
} else {
std::borrow::Cow::Borrowed(img)
};
let mut data = planar_big_endian(&img, color_channels, mode == PsdMode::Cmyk)?;
let mut added = 0usize;
for e in img.meta.extra_samples.iter().take(codecs::MAX_EXTRA_SAMPLES) {
match native_plane_to_be(&e.data, bps) {
Ok(be) if be.len() == plane_len => {
data.try_reserve(be.len()).map_err(|_| IoError::OutOfMemory("not enough memory for the TIFF extra samples".into()))?;
data.extend(be);
added += 1;
}
Err(error @ IoError::OutOfMemory(_)) => return Err(error),
_ => warnings.push("an extra TIFF sample did not match the image and was dropped".into()),
}
}
file.header.channels = u16::try_from(img.layout().channels().saturating_add(added)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
file.image_data = ImageData::new(Compression::Raw, data);
// Spot planes are read in Photoshop's polarity (0 = solid ink), as from a PSD. The importer's
// rule for PSDs from earlier PhotoCraft versions never applies: those versions stored no
// extra samples in a TIFF, and a TIFF with them carries 1053.
let (mut doc, w) = psd_to_document(&file);
let (mut doc, w, _, fatal_error) = psd_to_document_owned(file, &photocraft_raster::Interrupt::NONE, None).ok_or(IoError::Cancelled)?;
if let Some(error) = fatal_error {
return Err(error);
}
warnings.extend(w);
doc.name = name.to_string();
if doc.icc_profile.is_none() {
@@ -553,12 +572,16 @@ pub fn strip_foreign_order_blocks(file: &mut photocraft_psd::PsdFile) -> Vec<Str
/// Big-endian planar samples (a PSD merged-image plane) to native endian, or the reverse.
fn swap_plane(src: &[u8], bps: usize, to_be: bool) -> Result<Vec<u8>, IoError> {
if bps == 1 {
return Ok(src.to_vec());
let mut out = Vec::new();
out.try_reserve_exact(src.len()).map_err(|_| IoError::OutOfMemory("not enough memory for a TIFF extra sample".into()))?;
out.extend_from_slice(src);
return Ok(out);
}
if !matches!(bps, 2 | 4) || !src.len().is_multiple_of(bps) {
return Err(IoError::Unsupported("an extra channel plane is incomplete".into()));
}
let mut out = Vec::with_capacity(src.len());
let mut out = Vec::new();
out.try_reserve_exact(src.len()).map_err(|_| IoError::OutOfMemory("not enough memory for a TIFF extra sample".into()))?;
for c in src.chunks_exact(bps) {
match (bps, to_be, c) {
(2, true, [a, b]) => {
+4 -4
View File
@@ -210,7 +210,7 @@ pub fn decode_planes(compression: Compression, data: &[u8], layout: &PlaneLayout
return Err(PsdError::UnexpectedEof { offset: data.len(), needed: total - data.len() });
}
let mut out = Vec::new();
out.try_reserve_exact(total).map_err(|_| PsdError::LimitExceeded("not enough memory for the decoded channel data"))?;
out.try_reserve_exact(total).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?;
out.extend_from_slice(&data[..total]);
Ok(out)
}
@@ -311,7 +311,7 @@ thread_local! {
// Keep only the requested pixels, but consume the trailer to verify Adler-32.
// A bounded surplus tolerates padding without unbounded decompression work.
fn inflate_checked(data: &[u8], expected: u64, keep: bool) -> Result<Vec<u8>> {
const OOM: PsdError = PsdError::LimitExceeded("not enough memory for the decoded channel data");
const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data");
#[cfg(test)]
INFLATES.with(|n| n.set(n.get() + 1));
let mut decoder = flate2::Decompress::new(true);
@@ -364,7 +364,7 @@ fn decode_rle(data: &[u8], layout: &PlaneLayout, total: usize) -> Result<Vec<u8>
}
// Up to MAX_DECODED_BYTES: report a machine without that much memory instead of aborting.
let mut out = Vec::new();
out.try_reserve_exact(total).map_err(|_| PsdError::LimitExceeded("not enough memory for the decoded channel data"))?;
out.try_reserve_exact(total).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?;
for c in counts {
let row = r.bytes(c)?;
packbits::decode_into(row, rb, &mut out)?;
@@ -450,7 +450,7 @@ pub fn zip_compress(data: &[u8]) -> Vec<u8> {
/// bytes, so a stream declaring a huge size reports an error on a machine
/// without that much memory instead of aborting.
pub fn zip_decompress(data: &[u8], expected: usize) -> Result<Vec<u8>> {
const OOM: PsdError = PsdError::LimitExceeded("not enough memory for the decoded channel data");
const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data");
const CHUNK: usize = 1 << 20;
let mut dec = flate2::read::ZlibDecoder::new(data).take(u64::try_from(expected).unwrap_or(u64::MAX));
let mut out = Vec::new();
+4
View File
@@ -31,6 +31,10 @@ pub enum PsdError {
/// A dimension, count or allocation exceeded the configured safety limits.
#[error("limit exceeded: {0}")]
LimitExceeded(&'static str),
/// A buffer could not be allocated: the system has no memory for it. Unlike
/// [`PsdError::LimitExceeded`] the data may be valid, so the caller can retry smaller.
#[error("out of memory: {0}")]
OutOfMemory(&'static str),
/// Structurally invalid data.
#[error("invalid data: {0}")]
Invalid(String),
+42 -5
View File
@@ -132,6 +132,17 @@ impl PsdFile {
data: &[u8],
want: impl FnOnce(&PsdFile) -> bool,
recover: impl FnOnce(&PsdFile) -> bool,
) -> Result<(Self, Option<Result<Vec<u8>>>)> {
Self::from_bytes_and_merged_preflight(data, |file| Ok(want(file)), recover)
}
/// Parses with a fallible pixel preflight after layer records are available and before
/// the merged image is read, validated or decoded. A preflight error is always fatal;
/// `recover` only handles damage encountered after an accepted preflight.
pub fn from_bytes_and_merged_preflight(
data: &[u8],
want: impl FnOnce(&PsdFile) -> Result<bool>,
recover: impl FnOnce(&PsdFile) -> bool,
) -> Result<(Self, Option<Result<Vec<u8>>>)> {
let mut r = Reader::new(data);
let header = Header::read(&mut r)?;
@@ -202,7 +213,7 @@ impl PsdFile {
image_data,
write_as_psb: false,
};
let want = want(&file);
let want = want(&file)?;
let merged = file.read_merged_section(&mut r, want, recover)?;
Ok((file, merged))
}
@@ -227,13 +238,13 @@ impl PsdFile {
let merged = match merged {
Ok(merged) => merged,
Err(error) => {
if matches!(error, PsdError::LimitExceeded(_)) || !recover(file) {
if matches!(error, PsdError::LimitExceeded(_) | PsdError::OutOfMemory(_)) || !recover(file) {
return Err(error);
}
let compression = Compression::from_u16(encoded.u16()?);
let source = encoded.peek_rest();
let mut data = Vec::new();
data.try_reserve_exact(source.len()).map_err(|_| PsdError::LimitExceeded("not enough memory to retain the damaged merged image"))?;
data.try_reserve_exact(source.len()).map_err(|_| PsdError::OutOfMemory("not enough memory to retain the damaged merged image"))?;
data.extend_from_slice(source);
file.image_data = ImageData::new(compression, data);
Some(Err(error))
@@ -259,10 +270,18 @@ impl PsdFile {
r.u16()?;
let data = r.peek_rest();
let decoded = decode_planes(compression, data, &layout);
// An allocation failure is the open's, before the encoded image is copied under the same
// memory pressure.
if matches!(decoded, Err(PsdError::OutOfMemory(_))) {
return decoded.map(Ok);
}
if decoded.is_err() {
validate_planes(compression, data, &layout)?;
}
self.image_data = ImageData::new(compression, data.to_vec());
let mut copy = Vec::new();
copy.try_reserve_exact(data.len()).map_err(|_| PsdError::OutOfMemory("not enough memory to retain the merged image"))?;
copy.extend_from_slice(data);
self.image_data = ImageData::new(compression, copy);
r.skip(data.len())?;
Ok(decoded)
}
@@ -281,7 +300,7 @@ impl PsdFile {
.saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX))
.saturating_add(usize::try_from(widened).unwrap_or(usize::MAX));
let mut out = Vec::new();
out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?;
out.try_reserve(hint).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?;
if widen {
Header { version: v, ..self.header.clone() }.write(&mut out);
} else {
@@ -848,4 +867,22 @@ mod write_tests {
assert!(!other.merged_has_alpha(), "{}", String::from_utf8_lossy(&key));
}
}
#[test]
fn preflight_refusal_precedes_merged_validation_and_cannot_be_recovered() {
let file = testgen::small(Version::Psd, Compression::Zip);
let mut bytes = file.to_bytes().unwrap();
bytes.truncate(bytes.len() - file.image_data.data.len() - 2);
let recover_called = std::cell::Cell::new(false);
let preflight = |_: &PsdFile| Err(PsdError::LimitExceeded("test import budget"));
let recover = |_: &PsdFile| {
recover_called.set(true);
true
};
assert!(matches!(PsdFile::from_bytes_and_merged_preflight(&bytes, preflight, recover), Err(PsdError::LimitExceeded("test import budget"))));
assert!(matches!(
PsdFile::from_source_and_merged_preflight(crate::Source::new(bytes), preflight, recover),
Err(PsdError::LimitExceeded("test import budget"))
));
assert!(!recover_called.get());
}
}
+12 -1
View File
@@ -131,6 +131,17 @@ impl PsdFile {
source: Source,
want: impl FnOnce(&PsdFile) -> bool,
recover: impl FnOnce(&PsdFile) -> bool,
) -> Result<(Self, Option<Result<Vec<u8>>>)> {
Self::from_source_and_merged_preflight(source, |file| Ok(want(file)), recover)
}
/// Parses with a fallible pixel preflight after layer records are available and before
/// the merged image is read, validated or decoded. A preflight error is always fatal;
/// `recover` only handles damage encountered after an accepted preflight.
pub fn from_source_and_merged_preflight(
source: Source,
want: impl FnOnce(&PsdFile) -> Result<bool>,
recover: impl FnOnce(&PsdFile) -> bool,
) -> Result<(Self, Option<Result<Vec<u8>>>)> {
let mut c = Cursor::new(&source);
let header = Header::read(&mut Reader::new(&c.bytes(26)?))?;
@@ -217,7 +228,7 @@ impl PsdFile {
image_data: ImageData::new(Compression::Raw, Vec::new()),
write_as_psb: false,
};
if !want(&file) {
if !want(&file)? {
let compression = Compression::from_u16(c.u16()?);
file.image_data = ImageData { compression, data: Vec::new(), stored: Some(c.stored_rest()) };
return Ok((file, None));
+1 -1
View File
@@ -377,7 +377,7 @@ fn place_channel_plane(mut plane: Vec<u8>, source: &PlaneLayout, x: usize, y: us
fn zeroed_pattern_plane(len: usize) -> Result<Vec<u8>> {
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for the padded pattern channel"))?;
out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for the padded pattern channel"))?;
out.resize(len, 0);
Ok(out)
}
+1 -1
View File
@@ -267,7 +267,7 @@ fn large_channel_padding_within_the_existing_budget_is_allowed() {
#[test]
fn padded_plane_allocation_failure_is_an_error() {
// Capacity overflow is deterministic and never asks the OS for huge memory.
assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::LimitExceeded("not enough memory for the padded pattern channel"))));
assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::OutOfMemory("not enough memory for the padded pattern channel"))));
}
#[test]
+3 -3
View File
@@ -34,7 +34,7 @@ pub fn f32_to_bytes(samples: &[f32]) -> Vec<u8> {
/// Allocates `len` bytes, reporting a machine without that much memory instead of aborting.
fn try_buffer(len: usize) -> Result<Vec<u8>> {
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for the converted plane"))?;
out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for the converted plane"))?;
Ok(out)
}
@@ -128,7 +128,7 @@ fn interleave(mode: ColorMode, color: &[Cow<'_, [u8]>], alpha: Option<&[u8]>, pa
.filter(|&len| len as u64 <= crate::compression::MAX_DECODED_BYTES)
.ok_or(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"))?;
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| PsdError::LimitExceeded("not enough memory for RGBA output"))?;
out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for RGBA output"))?;
out.resize(len, 255);
if mode == ColorMode::Rgb {
let [r, g, b] = color else { return Err(PsdError::invalid("RGB requires three channels")) };
@@ -439,7 +439,7 @@ mod tests {
fn plane_conversion_reports_absurd_sizes() {
assert!(matches!(unpack_bits(&[0], usize::MAX / 2, 4), Err(PsdError::LimitExceeded(_))));
assert!(matches!(plane_to_u8(&[0], 1, usize::MAX / 2, 4), Err(PsdError::LimitExceeded(_))));
assert!(matches!(unpack_bits(&[0], 1 << 40, 1 << 20), Err(PsdError::LimitExceeded(_))));
assert!(matches!(unpack_bits(&[0], 1 << 40, 1 << 20), Err(PsdError::LimitExceeded(_) | PsdError::OutOfMemory(_))));
}
/// A bitmap composite whose RGBA output is over the decode budget is refused up front.
+2 -2
View File
@@ -98,7 +98,7 @@ impl ChannelData {
}
let table = bytes.get(0, table_len)?;
let mut offsets = Vec::new();
offsets.try_reserve_exact(height + 1).map_err(|_| PsdError::LimitExceeded("not enough memory for the RLE row table"))?;
offsets.try_reserve_exact(height + 1).map_err(|_| PsdError::OutOfMemory("not enough memory for the RLE row table"))?;
let mut at = table_len;
offsets.push(at);
for c in table.chunks_exact(size as usize) {
@@ -150,7 +150,7 @@ impl RowDecoder<'_> {
return Err(PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES"));
}
let mut out = Vec::new();
out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory for the decoded channel data"))?;
out.try_reserve_exact(n).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?;
match &self.kind {
Kind::Empty => {}
Kind::Raw(bytes) => out.extend_from_slice(&bytes.get((r0 * self.row_bytes) as u64, n as u64)?),
+1 -1
View File
@@ -173,7 +173,7 @@ impl Source {
return Err(out_of_range(offset, n, self.0.len()));
}
let mut out = Vec::new();
out.try_reserve_exact(n).map_err(|_| PsdError::LimitExceeded("not enough memory to read the data"))?;
out.try_reserve_exact(n).map_err(|_| PsdError::OutOfMemory("not enough memory to read the data"))?;
out.resize(n, 0);
self.0.read_at(offset, &mut out)?;
Ok(out)
+1 -1
View File
@@ -158,7 +158,7 @@ impl ImageSourceData {
// Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`.
let pad = info.pad_len(version, 4)?;
let mut data = Vec::new();
data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?;
data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::OutOfMemory("not enough memory for the layer data"))?;
info.write_unpadded(&mut data, version)?;
data.resize(data.len() + pad, 0);
padded_block(self.layer_info_key, data).write(&mut body, version, 4)?;
+19
View File
@@ -834,3 +834,22 @@ fn content_bounds_with_tile_skipping() {
s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]);
assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001));
}
#[test]
fn fallible_interleaved_writes_match_encoded_pixels_and_reject_bad_lengths() {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let format = PixelFormat::new(ColorMode::Rgb, sample, true);
let rect = Rect::new(-2, -1, 3, 2);
let bytes: Vec<u8> = (0..rect.width() as usize * rect.height() as usize * format.bytes_per_pixel()).map(|i| (i % 251) as u8).collect();
let mut surface = Surface::new(format);
assert!(surface.try_write_interleaved(rect, &bytes[..bytes.len() - 1]).is_err());
assert!(surface.tiles.is_empty());
surface.try_write_interleaved(rect, &bytes).unwrap();
assert_eq!(surface.to_interleaved(rect), bytes);
let mut shared = surface.clone();
let replacement = vec![0; bytes.len()];
shared.try_write_interleaved(rect, &replacement).unwrap();
assert_eq!(surface.to_interleaved(rect), bytes);
assert_eq!(shared.to_interleaved(rect), replacement);
}
}
+23
View File
@@ -652,6 +652,29 @@ photos are public domain, not committed; download them at 1920 px wide into `<di
size the cases were placed for (Commons rounds it to 1920). Timing on a 24 MP document through the
command: `cargo run --release -p photocraft-engine --example remove_bench`.
## PSD import pixel memory limits
PSD/PSB imports preflight layer, user-mask, merged-image and extra-channel pixel storage
before merged-image validation or decoding. The conservative estimate sums retained tile
storage (including padding and negative offsets) and the largest decode/conversion workspace.
It does not credit uniform-tile sharing or pruning, so some files that could fit after decoding
are refused. Valid off-canvas pixels are preserved; oversized layers are rejected rather than
clipped. Defaults are 2 GiB on native targets and 1 GiB on wasm. Applications can lower the
allowance with `ImportOptions::psd_max_pixel_bytes`; values above the default are capped.
The source-only convenience API uses the default; `import_file_for_open_with` honours options.
An over-budget ordinary or interactive import returns `IoError::PsdImportBudget` with the
estimated and allowed byte counts; damaged-file recovery never bypasses that error. The legacy
`psd_to_document` conversion APIs cannot return an error, so they return an empty document and
an explicit warning on preflight refusal. Layer and mask pixel allocation failures also fail
ordinary imports instead of opening partial content.
This is the first part of #8593. The allowance covers the main pixel paths, not total process
RSS: encoded input, parser metadata, patterns, smart-filter caches, embedded smart-object
contents, generated vector caches, and text preparation are outside it and retain their
existing limits. Joining these paths to a shared budget and streaming whole-plane masks are follow-up work. An accepted
estimate does not guarantee allocation success on a memory-constrained host.
## Test corpora
Real files are our best oracles, but they are large binaries, so they never go into this