From e95059590fadaabd9aadc0c0489804d75a3c5d52 Mon Sep 17 00:00:00 2001
From: maryam ebrahimzadeh <maryam.ebr@student.sharif.edu>
Date: Mon, 19 Jul 2021 18:52:50 +0430
Subject: [PATCH 1/3] gdImageGd2Ptr memory leak

Conflict:NA
Reference:https://github.com/libgd/libgd/commit/c5fd25ce0e48fd5618a972ca9f5e28d6d62006af
---
 src/gd_gd2.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/src/gd_gd2.c b/src/gd_gd2.c
index 760e85b..0b7e624 100644
--- a/src/gd_gd2.c
+++ b/src/gd_gd2.c
@@ -910,9 +910,11 @@ _gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy)
 
 }
 
-static void
+/* returns 0 on success, 1 on failure */
+static int
 _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
 {
+	int ret = 0;
 	int ncx, ncy, cx, cy;
 	int x, y, ylo, yhi, xlo, xhi;
 	int chunkLen;
@@ -974,10 +976,12 @@ _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
 		/* */
 		chunkData = gdCalloc (cs * bytesPerPixel * cs, 1);
 		if (!chunkData) {
+			ret = 1;
 			goto fail;
 		}
 		compData = gdCalloc (compMax, 1);
 		if (!compData) {
+			ret = 1;
 			goto fail;
 		}
 
@@ -992,6 +996,7 @@ _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
 
 		chunkIdx = gdCalloc (idxSize * sizeof (t_chunk_info), 1);
 		if (!chunkIdx) {
+			ret = 1;
 			goto fail;
 		}
 	};
@@ -1106,6 +1111,8 @@ fail:
 		gdFree (chunkIdx);
 	}
 	GD2_DBG (printf ("Done\n"));
+	
+	return ret;
 
 }
 
@@ -1128,8 +1135,13 @@ BGD_DECLARE(void *) gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
 	void *rv;
 	gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
 	if (out == NULL) return NULL;
-	_gdImageGd2 (im, out, cs, fmt);
-	rv = gdDPExtractData (out, size);
+	
+	if (_gdImageGd2(im, out, cs, fmt)) {
+		rv = NULL;
+	} else {
+		rv = gdDPExtractData(out, size);
+	}
+
 	out->gd_free (out);
 	return rv;
 }
-- 
2.27.0

