dds: validate public boundaries and bound fallible decoding

This commit is contained in:
FredApps committed 2026-11-16 18:01:22 +01:00
1 parent 2c18ddd1ed
commit 808df4f186
4 files changed
+78 -4

No files matched your search

+2
View File
@@ -38,6 +38,8 @@ assert_eq!((texture.width(), texture.height(), texture.layout()), (6, 5, Layout:
let decoded = texture.decode()?;
```
`Texture::parse` requires a complete header and nonzero dimensions. `Texture::decode` bounds its output buffer to 1 GiB; use `decode_with_limit(max_bytes)` for an explicit per-buffer budget. Allocation is fallible. This is not a total process memory limit. The `craft-image-codecs` adapter forwards its own existing `Limits::max_alloc` instead of imposing the standalone default.
The block encoder is our own: RGB565 endpoints fitted along each block's principal axis and
refined by least squares, indices picked against the palette the reader decodes; BC1 turns texels
under half opacity into its transparent black, and BC3, BC4 and BC5 pick whichever mode of their
+26 -3
View File
@@ -75,6 +75,8 @@ pub enum DdsError {
Encode(String),
/// An output buffer of this many bytes could not be allocated.
Alloc(usize),
/// The decoded output exceeds the caller-selected per-buffer byte limit.
LimitExceeded { required: usize, limit: u64 },
}
impl fmt::Display for DdsError {
@@ -84,6 +86,7 @@ impl fmt::Display for DdsError {
DdsError::Unsupported(reason) => write!(f, "unsupported DDS: {reason}"),
DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"),
DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"),
DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"),
}
}
}
@@ -383,6 +386,9 @@ fn dx10_encoding(b: &[u8]) -> Result<Encoding, DdsError> {
}
}
/// Default per-buffer decoded output budget (1 GiB). This is not a total process memory budget.
pub const DEFAULT_MAX_DECODE_BYTES: u64 = 1024 * 1024 * 1024;
/// A DDS file whose header has been read: its size and pixel layout are known before
/// [`Texture::decode`] allocates anything, so a caller can check them against its limits.
pub struct Texture<'a> {
@@ -413,6 +419,12 @@ impl<'a> Texture<'a> {
}
let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10";
let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) };
if b.len() < start {
return Err(bad("truncated header"));
}
if width == 0 || height == 0 {
return Err(bad("texture dimensions must be nonzero"));
}
Ok(Texture { bytes: b, flags, width, height, encoding, start })
}
@@ -429,19 +441,27 @@ impl<'a> Texture<'a> {
self.encoding.layout()
}
/// The top mip level's pixels in [`Texture::layout`].
/// The top mip level's pixels in [`Texture::layout`], bounded by [`DEFAULT_MAX_DECODE_BYTES`].
pub fn decode(&self) -> Result<Vec<u8>, DdsError> {
self.decode_with_limit(DEFAULT_MAX_DECODE_BYTES)
}
/// Decode with an explicit per-buffer output byte budget; allocation remains fallible.
pub fn decode_with_limit(&self, max_bytes: u64) -> Result<Vec<u8>, DdsError> {
let (b, flags, encoding) = (self.bytes, self.flags, self.encoding);
let (width, height) = (self.width, self.height);
// The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set.
let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None };
let (row_pitch, size) = encoding.level_layout(width, height, pitch)?;
let data = b.get(self.start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?;
let (w, h) = (width as usize, height as usize);
let channels = encoding.layout().channels();
let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?;
let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?;
let mut pixels = vec![0u8; total];
if total as u64 > max_bytes {
return Err(DdsError::LimitExceeded { required: total, limit: max_bytes });
}
let data = b.get(self.start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?;
let mut pixels = alloc_zeroed(total)?;
match encoding {
Encoding::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size),
Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => {
@@ -684,6 +704,9 @@ fn half((w, h): (usize, usize)) -> (usize, usize) {
/// Block compressions take the layout [`DdsCompression::layout`] names (RGBA for BC1 to BC3,
/// gray for BC4, RGB for BC5); uncompressed textures take every layout.
pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: DdsOptions) -> Result<Vec<u8>, DdsError> {
if width == 0 || height == 0 {
return Err(encode_err("texture dimensions must be nonzero"));
}
let store = Store::new(options.compression, layout)?;
let expected = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(layout.channels()));
if expected != Some(pixels.len()) {
+46
View File
@@ -0,0 +1,46 @@
use craft_dds::{DdsCompression, DdsOptions, Layout, Texture, encode};
#[test]
fn metadata_requires_a_complete_header() {
for (compression, layout, channels, header) in [(DdsCompression::None, Layout::Gray, 1, 128), (DdsCompression::Bc4, Layout::Gray, 1, 148)] {
let data = encode(4, 4, layout, &vec![7; 16 * channels], DdsOptions { compression, mipmaps: false }).unwrap();
for n in 0..header {
assert!(Texture::parse(&data[..n]).is_err(), "accepted {n}/{header} header bytes");
}
assert!(Texture::parse(&data[..header]).is_ok());
}
}
#[test]
fn empty_dimensions_are_not_textures() {
for (w, h) in [(0, 0), (0, 4), (4, 0)] {
assert!(encode(w, h, Layout::Gray, &[], DdsOptions::default()).is_err(), "encoded {w}x{h}");
}
}
#[test]
fn decoded_output_respects_explicit_budget() {
let data = encode(4, 4, Layout::Rgba, &[7; 64], DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }).unwrap();
let texture = Texture::parse(&data).unwrap();
assert!(matches!(texture.decode_with_limit(63), Err(craft_dds::DdsError::LimitExceeded { required: 64, limit: 63 })));
assert_eq!(texture.decode_with_limit(64).unwrap().len(), 64);
assert_eq!(texture.decode().unwrap(), texture.decode_with_limit(u64::MAX).unwrap());
}
#[test]
fn parse_rejects_empty_dimensions() {
let valid = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap();
for (w, h) in [(0u32, 0u32), (0, 4), (4, 0)] {
let mut data = valid.clone();
data[12..16].copy_from_slice(&h.to_le_bytes());
data[16..20].copy_from_slice(&w.to_le_bytes());
assert!(Texture::parse(&data).is_err());
}
}
#[test]
fn default_budget_rejects_oversized_header_before_payload_or_allocation() {
let mut data = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap();
data.truncate(128);
data[12..16].copy_from_slice(&65536u32.to_le_bytes());
data[16..20].copy_from_slice(&32768u32.to_le_bytes());
data[20..24].copy_from_slice(&32768u32.to_le_bytes());
let texture = Texture::parse(&data).unwrap();
assert!(matches!(texture.decode(), Err(craft_dds::DdsError::LimitExceeded { limit: craft_dds::DEFAULT_MAX_DECODE_BYTES, .. })));
assert!(matches!(texture.decode_with_limit(u64::MAX), Err(craft_dds::DdsError::Malformed(_))));
}
+4 -1
View File
@@ -15,6 +15,9 @@ fn error(e: DdsError) -> CodecError {
DdsError::Unsupported(reason) => CodecError::unsupported(Format::Dds, reason),
DdsError::Encode(reason) => CodecError::encode(Format::Dds, reason),
DdsError::Alloc(len) => CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")),
DdsError::LimitExceeded { required, limit } => {
CodecError::LimitExceeded(format!("decoded texture requires {required} bytes, exceeding limit {limit}"))
}
other => CodecError::malformed(Format::Dds, other),
}
}
@@ -37,7 +40,7 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
let texture = Texture::parse(b).map_err(error)?;
let layout = channel_layout(texture.layout());
limits.check(texture.width(), texture.height(), layout, SampleType::U8)?;
let pixels = texture.decode().map_err(error)?;
let pixels = texture.decode_with_limit(limits.max_alloc).map_err(error)?;
Image::from_u8(texture.width(), texture.height(), layout, pixels)
}