Commit 6b68d9433fe for php.net

commit 6b68d9433fe5c3c7aa1c0b8f22352d87837cca71
Author: Ilia Alshanetsky <ilia@ilia.ws>
Date:   Fri May 22 09:23:34 2026 -0400

    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
    Closes GH-22125

diff --git a/NEWS b/NEWS
index 905ac0c91cf..460156172ca 100644
--- a/NEWS
+++ b/NEWS
@@ -2,6 +2,10 @@ PHP                                                                        NEWS
 |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
 ?? ??? ????, PHP 8.4.23

+- GD:
+  . Fixed bug GH-22121 (Double free in gdImageSetStyle() after
+    overflow-triggered early return). (iliaal)
+
 - Intl:
   . Fix incorrect argument positions for uninitialized calendar arguments in
     IntlCalendar::equals(), ::before(), ::after(), and ::isEquivalentTo().
diff --git a/ext/gd/libgd/gd.c b/ext/gd/libgd/gd.c
index baa8887089e..0ab26647c1d 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;