From 05726c66756346f671f335eb533abd167e557352 Mon Sep 17 00:00:00 2001
From: Dirk Lemstra <dirk@git.imagemagick.org>
Date: Thu, 27 Apr 2017 12:30:48 +0200
Subject: [PATCH] [3/3] CVE-2017-8350 Fixed various leaks in ReadOneJNGImage
 reported in #447

origin: https://github.com/ImageMagick/ImageMagick/commit/a353ee3914d7f0a83078f5ef84a7766587c98121
bug: https://github.com/ImageMagick/ImageMagick/issues/447
bug-debian: https://bugs.debian.org/862587
---
 coders/png.c | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)

diff --git a/coders/png.c b/coders/png.c
index 3991e506e..3f5775909 100644
--- a/coders/png.c
+++ b/coders/png.c
@@ -4127,7 +4127,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
       AcquireNextImage(image_info,image);
 
       if (GetNextImageInList(image) == (Image *) NULL)
-        return((Image *) NULL);
+        return(DestroyImageList(image));
 
       image=SyncNextImageInList(image);
     }
@@ -4278,7 +4278,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
           exception);
 
         if (status == MagickFalse)
-          return((Image *) NULL);
+          return(DestroyImageList(image));
 
         if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
           {
@@ -4308,7 +4308,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
               exception);
 
             if (status == MagickFalse)
-              return((Image *) NULL);
+              return(DestroyImageList(image));
 
             if (jng_alpha_compression_method == 0)
               {
@@ -4562,6 +4562,19 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
        o destroy the secondary image.
   */
 
+  if (color_image_info == (ImageInfo *) NULL)
+    {
+      assert(color_image == (Image *) NULL);
+      assert(alpha_image == (Image *) NULL);
+      return(DestroyImageList(image));
+    }
+
+  if (color_image == (Image *) NULL)
+    {
+      assert(alpha_image == (Image *) NULL);
+      return(DestroyImageList(image));
+    }
+
   (void) SeekBlob(color_image,0,SEEK_SET);
 
   if (logging != MagickFalse)
@@ -4581,7 +4594,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
   color_image_info=DestroyImageInfo(color_image_info);
 
   if (jng_image == (Image *) NULL)
-    return((Image *) NULL);
+    return(DestroyImageList(image));
 
   if (logging != MagickFalse)
     (void) LogMagickEvent(CoderEvent,GetMagickModule(),
@@ -4689,6 +4702,9 @@ static Image *ReadOneJNGImage(MngInfo *mng_info,
   status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
     2*GetBlobSize(image));
 
+  if (status == MagickFalse)
+    return(DestroyImageList(image));
+
   if (logging != MagickFalse)
     (void) LogMagickEvent(CoderEvent,GetMagickModule(),
       "  exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
