From e97c8323e80988a1c7f06df8404e38a9d9fd5018 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 13 Apr 2026 18:54:59 +1000 Subject: [PATCH] Do not return negative width for text --- Tests/test_imagefontpil.py | 9 +++++++++ src/_imaging.c | 3 +++ 2 files changed, 12 insertions(+) diff --git a/Tests/test_imagefontpil.py b/Tests/test_imagefontpil.py index 883df051d1e..eb7d3d0388b 100644 --- a/Tests/test_imagefontpil.py +++ b/Tests/test_imagefontpil.py @@ -68,6 +68,15 @@ def test_textbbox(font: ImageFont.ImageFont) -> None: assert d.textbbox((0, 0), "test", font=font) == (0, 0, 24, 11) +def test_negative_dx() -> None: + glyph = struct.pack(">hhhhhhhhhh", -1, 0, 0, 0, 0, 0, 0, 0, 0, 0) + fp = BytesIO(b"PILfont\n\nDATA\n" + glyph * 256) + + font = ImageFont.ImageFont() + font._load_pilfont_data(fp, Image.new("L", (1, 1))) + assert font.getlength("A") == 0 + + def test_decompression_bomb() -> None: glyph = struct.pack(">hhhhhhhhhh", 1, 0, 0, 0, 256, 256, 0, 0, 256, 256) fp = BytesIO(b"PILfont\n\nDATA\n" + glyph * 256) diff --git a/src/_imaging.c b/src/_imaging.c index 980f827ae78..7d10b3d4725 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -2779,6 +2779,9 @@ textwidth(ImagingFontObject *self, const unsigned char *text) { xsize += self->glyphs[*text].dx; } + if (xsize < 0) { + return 0; + } return xsize; }