572cf4
From a93eac0e843148dc2d631c3ba80af17e9c8c860f Mon Sep 17 00:00:00 2001
572cf4
From: =?UTF-8?q?F=C3=A1bio=20Cabral=20Pacheco?= <fcabralpacheco@gmail.com>
572cf4
Date: Fri, 20 Dec 2019 12:03:33 -0300
572cf4
Subject: [PATCH] Fix potential NULL pointer dereference in gdImageClone()
572cf4
572cf4
---
572cf4
 src/gd.c                          |  9 +--------
572cf4
 tests/gdimageclone/style.c        | 30 ++++++++++++++++++++++++++++++
572cf4
 5 files changed, 35 insertions(+), 9 deletions(-)
572cf4
 create mode 100644 tests/gdimageclone/style.c
572cf4
572cf4
diff --git a/src/gd.c b/src/gd.c
572cf4
index 592a0286..d564d1f9 100644
572cf4
--- a/src/gd.c
572cf4
+++ b/src/gd.c
572cf4
@@ -2865,14 +2865,6 @@ BGD_DECLARE(gdImagePtr) gdImageClone (gdImagePtr src) {
572cf4
 		}
572cf4
 	}
572cf4
 
572cf4
-	if (src->styleLength > 0) {
572cf4
-		dst->styleLength = src->styleLength;
572cf4
-		dst->stylePos    = src->stylePos;
572cf4
-		for (i = 0; i < src->styleLength; i++) {
572cf4
-			dst->style[i] = src->style[i];
572cf4
-		}
572cf4
-	}
572cf4
-
572cf4
 	dst->interlace   = src->interlace;
572cf4
 
572cf4
 	dst->alphaBlendingFlag = src->alphaBlendingFlag;
572cf4
@@ -2907,6 +2899,7 @@ BGD_DECLARE(gdImagePtr) gdImageClone (gdImagePtr src) {
572cf4
 
572cf4
 	if (src->style) {
572cf4
 		gdImageSetStyle(dst, src->style, src->styleLength);
572cf4
+		dst->stylePos = src->stylePos;
572cf4
 	}
572cf4
 
572cf4
 	for (i = 0; i < gdMaxColors; i++) {
572cf4
diff --git a/tests/gdimageclone/style.c b/tests/gdimageclone/style.c
572cf4
new file mode 100644
572cf4
index 00000000..c2b246ed
572cf4
--- /dev/null
572cf4
+++ b/tests/gdimageclone/style.c
572cf4
@@ -0,0 +1,30 @@
572cf4
+/**
572cf4
+ * Cloning an image should exactly reproduce all style related data
572cf4
+ */
572cf4
+
572cf4
+
572cf4
+#include <string.h>
572cf4
+#include "gd.h"
572cf4
+#include "gdtest.h"
572cf4
+
572cf4
+
572cf4
+int main()
572cf4
+{
572cf4
+    gdImagePtr im, clone;
572cf4
+    int style[] = {0, 0, 0};
572cf4
+
572cf4
+    im = gdImageCreate(8, 8);
572cf4
+    gdImageSetStyle(im, style, sizeof(style)/sizeof(style[0]));
572cf4
+
572cf4
+    clone = gdImageClone(im);
572cf4
+    gdTestAssert(clone != NULL);
572cf4
+
572cf4
+    gdTestAssert(clone->styleLength == im->styleLength);
572cf4
+    gdTestAssert(clone->stylePos == im->stylePos);
572cf4
+    gdTestAssert(!memcmp(clone->style, im->style, sizeof(style)/sizeof(style[0])));
572cf4
+
572cf4
+    gdImageDestroy(clone);
572cf4
+    gdImageDestroy(im);
572cf4
+
572cf4
+    return gdNumFailures();
572cf4
+}