Blob Blame History Raw
diff --git a/src/gd_gd2.c b/src/gd_gd2.c
index 6f28461..a50b33d 100644
--- a/src/gd_gd2.c
+++ b/src/gd_gd2.c
@@ -165,6 +165,8 @@ _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
 			if (gdGetInt (&cidx[i].size, in) != 1) {
 				goto fail2;
 			};
+			if (cidx[i].offset < 0 || cidx[i].size < 0)
+				goto fail2;
 		};
 		*chunkIdx = cidx;
 	};
diff --git a/tests/Makefile.am b/tests/Makefile.am
index ed2c35b..b582266 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -129,7 +129,8 @@ endif
 
 if HAVE_LIBZ
 check_PROGRAMS += \
-	gd2/gd2_null
+	gd2/gd2_null \
+	gd2/gd2_read_corrupt
 endif
 
 if HAVE_LIBPNG
diff --git a/tests/gd2/gd2_read_corrupt.c b/tests/gd2/gd2_read_corrupt.c
new file mode 100644
index 0000000..11f6a67
--- /dev/null
+++ b/tests/gd2/gd2_read_corrupt.c
@@ -0,0 +1,25 @@
+/* Just try to read the invalid gd2 image & not crash. */
+#include "gd.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include "gdtest.h"
+
+int main()
+{
+	gdImagePtr im;
+	FILE *fp;
+	char path[1024];
+
+	/* Read the corrupt image. */
+	sprintf(path, "%s/gd2/invalid_neg_size.gd2", GDTEST_TOP_DIR);
+	fp = fopen(path, "rb");
+	if (!fp) {
+		printf("failed, cannot open file\n");
+		return 1;
+	}
+	im = gdImageCreateFromGd2(fp);
+	fclose(fp);
+
+	/* Should have failed & rejected it. */
+	return im == NULL ? 0 : 1;
+}