From 466d228135cc645b881118b45aa11c868b192f48 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Fri, 2 May 2025 11:50:26 +0200 Subject: [PATCH] Fix buffer overflow for BcnEncode --- Tests/test_file_dds.py | 15 +++++++++++++++ src/libImaging/BcnEncode.c | 3 +++ 2 files changed, 18 insertions(+) diff --git a/Tests/test_file_dds.py b/Tests/test_file_dds.py index 3388fce16..12be1056e 100644 --- a/Tests/test_file_dds.py +++ b/Tests/test_file_dds.py @@ -511,3 +511,18 @@ def test_save_dx10_bc5(tmp_path: Path) -> None: im = hopper("L") with pytest.raises(OSError, match="only RGB mode can be written as BC5"): im.save(out, pixel_format="BC5") + +@pytest.mark.parametrize( + "pixel_format, mode", + ( + ('DXT1', 'RGBA'), + ('DXT3', 'RGBA'), + ('BC2', 'RGBA'), + ('BC3', 'RGBA'), + ('BC5', 'RGB'), + ), +) +def test_save_large_file(tmp_path: Path, pixel_format: str, mode: str) -> None: + with hopper(mode).resize((440,440)) as im: + # should not error in valgrind + im.save(tmp_path / 'img.dds', 'DDS', pixel_format=pixel_format) diff --git a/src/libImaging/BcnEncode.c b/src/libImaging/BcnEncode.c index 2bad73b92..f6445d653 100644 --- a/src/libImaging/BcnEncode.c +++ b/src/libImaging/BcnEncode.c @@ -258,6 +258,9 @@ ImagingBcnEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { UINT8 *dst = buf; for (;;) { + if (dst + 8 >= bytes + buf) { + break; + } if (n == 5) { encode_bc3_alpha(im, state, dst, 0); dst += 8;