use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use unityrs_core::budget::{BudgetExceeded, MemoryBudget, Permit, Reservation};
use unityrs_core::limits::Meter;
use super::{DecodeError, Format, MAX_CROP_PIXELS, MAX_PIXELS, Plan, decode, decode_with, plan};
use crate::format::Library;
#[test]
fn the_bound_comes_before_the_data() {
let (w, h) = (16388, 16384);
let needed = 4097 * 4096 * 8;
let too_large = Err(DecodeError::TooLarge {
pixels: 16388 * 16384,
max: MAX_PIXELS,
});
for len in [1, needed - 1, needed, needed + 1] {
assert_eq!(plan(Format::Dxt1, len, w, h), too_large, "{len}");
}
assert_eq!(plan(Format::Dxt1, 0, w, h), Err(DecodeError::NoImageData));
assert_eq!(
plan(Format::Dxt1, 1, -w, h),
Err(DecodeError::NegativeSize {
width: -w,
height: h
})
);
assert!(matches!(
plan(Format::Rgba32, 3, i32::MAX, i32::MAX),
Err(DecodeError::TooLarge { .. })
));
let meter = Meter::unlimited();
assert_eq!(
decode(Format::Dxt1, &[1, 2, 3], w, h, &meter).map(|_| ()),
too_large.map(|_| ())
);
assert_eq!(meter.used(), 0);
}
#[test]
fn pillows_raw_width_cap_comes_before_the_data() {
let raw = [
(Format::Rgba32, 67_108_856, 4),
(Format::Bgra32, 67_108_856, 4),
(Format::Argb32, 67_108_856, 4),
(Format::Rgb24, 89_478_478, 3),
(Format::Bgr24, 89_478_478, 3),
(Format::Argb4444, 134_217_720, 2),
(Format::Rgba4444, 134_217_720, 2),
(Format::Rgb565, 134_217_720, 2),
(Format::Alpha8, 268_435_448, 1),
(Format::R8, 268_435_448, 1),
];
let pillow_raw = Format::ALL
.iter()
.filter(|f| f.library() == Library::PillowRaw)
.count();
assert_eq!(raw.len(), pillow_raw);
for (format, max, bpp) in raw {
assert_eq!(format.raw_bits(), Some(8 * u32::try_from(bpp).unwrap()));
assert_eq!(
plan(format, 1, max, 1),
Err(DecodeError::NotEnoughData {
needed: u64::from(max.unsigned_abs()) * bpp,
got: 1
}),
"{format:?}"
);
let need = usize::try_from(u64::from(max.unsigned_abs()) * bpp).unwrap();
assert!(plan(format, need, max, 1).is_ok(), "{format:?}");
let refused = Err(DecodeError::PillowMemoryError {
width: max.unsigned_abs() + 1,
max: max.unsigned_abs(),
});
for len in [1, need + usize::try_from(bpp).unwrap()] {
assert_eq!(plan(format, len, max + 1, 1), refused, "{format:?}");
}
if 2 * (u64::from(max.unsigned_abs()) + 1) <= MAX_PIXELS {
assert_eq!(plan(format, 1, max + 1, 2), refused, "{format:?}");
}
let meter = Meter::unlimited();
assert_eq!(
decode(format, &[0], max + 1, 1, &meter).map(|_| ()),
refused.map(|_| ())
);
assert_eq!(meter.used(), 0);
}
let bc7 = 67_108_860 / 4 * 16;
assert!(plan(Format::Bc7, bc7, 67_108_860, 1).is_ok());
}
#[test]
fn the_crop_bomb_comes_after_the_data() {
let (w, h) = (59, 3_033_169);
let need = 15 * 758_293 * 8;
assert_eq!(
plan(Format::Dxt1, need - 1, w, h),
Err(DecodeError::NotEnoughData {
needed: 90_995_160,
got: 90_995_159
})
);
let bomb = plan(Format::Dxt1, need, w, h).unwrap_err();
assert_eq!(
bomb,
DecodeError::DecompressionBomb {
pixels: 178_956_971,
max: MAX_CROP_PIXELS
}
);
assert_eq!(
bomb.to_string(),
"Image size (178956971 pixels) exceeds limit of 178956970 pixels, could be \
decompression bomb DOS attack."
);
for format in [Format::Dxt5, Format::Bc7] {
assert!(matches!(
plan(format, 2 * need, w, h),
Err(DecodeError::DecompressionBomb { .. })
));
}
assert!(plan(Format::Dxt1, 12_472 / 4 * 14_352 / 4 * 8, 12_470, 14_351).is_ok());
assert!(plan(Format::Dxt1, 44_739_244 / 4 * 8, 4, 44_739_244).is_ok());
assert!(plan(Format::Rgba32, 4 * 178_956_971, w, h).is_ok());
assert!(matches!(
plan(Format::Bc7, 1 << 28, 16383, 16384),
Err(DecodeError::DecompressionBomb { .. })
));
assert!(plan(Format::Bc7, 1 << 28, 16384, 16384).is_ok());
}
#[cfg(target_pointer_width = "64")]
#[test]
fn a_bcn_length_past_2_gib_is_read_as_its_low_32_bits() {
assert!(plan(Format::Bc7, (1 << 32) + 16, 4, 4).is_ok());
assert_eq!(
plan(Format::Bc7, (1 << 32) + 15, 4, 4),
Err(DecodeError::NotEnoughData {
needed: 16,
got: (1 << 32) + 15
})
);
assert!(matches!(
plan(Format::Bc7, (1 << 31) + 16, 4, 4),
Err(DecodeError::NotEnoughData { .. })
));
assert!(plan(Format::Rgba32, (1 << 31) + 16, 2, 2).is_ok());
}
#[test]
fn texture2ddecoders_formats_refuse_what_it_reads_past() {
let etc = Format::ALL.iter().copied().filter(|f| {
f.library() == Library::Texture2DDecoder
&& !f.is_crunched()
&& f.pvrtc_2bpp().is_none()
&& f.block_size().is_some()
});
for format in etc {
let block = usize::try_from(format.block_bytes().unwrap()).unwrap();
assert!(plan(format, 6 * block, 7, 9).is_ok(), "{format:?}");
assert_eq!(
plan(format, 6 * block - 1, 7, 9),
Err(DecodeError::NotEnoughData {
needed: u64::try_from(6 * block).unwrap(),
got: u64::try_from(6 * block - 1).unwrap()
}),
"{format:?}"
);
let meter = Meter::unlimited();
assert!(matches!(
decode(format, &vec![0; 6 * block - 1], 7, 9, &meter),
Err(DecodeError::NotEnoughData { .. })
));
assert_eq!(meter.used(), 0);
for side in [-1, -3, -4, -5, -8, i32::MIN] {
for (w, h) in [(side, 4), (4, side), (side, side)] {
assert_eq!(
plan(format, 1 << 20, w, h),
Err(DecodeError::NegativeSize {
width: w,
height: h
}),
"{format:?} {w}x{h}"
);
}
}
let need = |w: u64| usize::try_from(w.div_ceil(4)).unwrap() * block;
assert!(plan(format, need(67_108_856), 67_108_856, 1).is_ok());
let refused = Err(DecodeError::PillowMemoryError {
width: 67_108_860,
max: 67_108_856,
});
for len in [1, need(67_108_860)] {
assert_eq!(plan(format, len, 67_108_857, 1), refused, "{format:?}");
}
assert!(matches!(
plan(format, 2 * 15 * 758_293 * 16, 59, 3_033_169),
Err(DecodeError::DecompressionBomb { .. })
));
}
#[cfg(target_pointer_width = "64")]
assert!(matches!(
plan(Format::EtcRgb4, (1 << 32) + 7, 4, 4),
Ok(Plan { input_bytes: 8, .. })
));
assert!(matches!(
plan(Format::EtcRgb4, (1 << 31) + 7, 4, 4),
Ok(Plan { input_bytes: 8, .. })
));
}
#[test]
fn a_panic_in_the_pixel_loop_is_contained() {
let meter = Meter::unlimited();
let data = vec![0u8; 4 * 64 * 64];
let got = decode_with(
Format::Rgba32,
&data,
64,
64,
&meter,
|_, _, _, _, out, _| {
assert_eq!(out.len(), 4 * 64 * 64);
panic!("in the loop");
},
false,
);
match got {
Err(DecodeError::Panicked { payload }) => assert_eq!(payload.message(), "in the loop"),
other => panic!("{other:?}"),
}
assert_eq!(meter.used(), 0);
let got = decode_with(
Format::Rgba32,
&[],
64,
64,
&meter,
|_, _, _, _, _, _| panic!("not reached"),
false,
);
assert_eq!(got.map(|_| ()), Err(DecodeError::NoImageData));
}
#[derive(Debug)]
struct Panicking;
impl MemoryBudget for Panicking {
fn try_reserve(&self, _: u64, _: Reservation) -> Result<Permit, BudgetExceeded> {
panic!("the budget panicked");
}
}
#[test]
fn a_panicking_budget_unwinds_out_of_the_decode() {
let meter = Meter::new(u64::MAX, Arc::new(Panicking), Reservation::Input);
let data = vec![0u8; 4 * 4 * 4];
let got = catch_unwind(AssertUnwindSafe(|| {
decode(Format::Rgba32, &data, 4, 4, &meter).map(|_| ())
}));
match got {
Err(payload) => assert_eq!(payload.downcast_ref::<&str>(), Some(&"the budget panicked")),
Ok(answer) => panic!("decode() answered {answer:?}"),
}
}