From 509310d439e79b55cf87cac93a6d0edc8e4817cc Mon Sep 17 00:00:00 2001 From: Ilia Alshanetsky Date: Fri, 22 May 2026 09:23:34 -0400 Subject: [PATCH] Fix GH-22121: double-free in gdImageSetStyle() after overflow early return gdImageSetStyle freed im->style before checking overflow2(). When the overflow check tripped and the function early-returned, im->style was left dangling. The next gdImageSetStyle, gdImageDestroy, or gdImageSetPixel gdStyled/gdStyledBrushed dispatch then freed or dereferenced it. Move the overflow check above the free to match upstream libgd (libgd/libgd src/gd.c::gdImageSetStyle), which has always had the check first. The original divergence was an oversight in 77ba2483d95 when the overflow check was ported from libgd 2.0.29. Fixes GH-22121 --- ext/gd/libgd/gd.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ext/gd/libgd/gd.c b/ext/gd/libgd/gd.c index baa8887089ef..0ab26647c1d3 100644 --- a/ext/gd/libgd/gd.c +++ b/ext/gd/libgd/gd.c @@ -2854,12 +2854,12 @@ int gdCompareInt (const void *a, const void *b) void gdImageSetStyle (gdImagePtr im, int *style, int noOfPixels) { - if (im->style) { - gdFree(im->style); - } if (overflow2(sizeof (int), noOfPixels)) { return; } + if (im->style) { + gdFree(im->style); + } im->style = (int *) gdMalloc(sizeof(int) * noOfPixels); memcpy(im->style, style, sizeof(int) * noOfPixels); im->styleLength = noOfPixels;