From 45530d5ce1bcc9357907b7e5eeb6e54c6198358e Mon Sep 17 00:00:00 2001
From: Eric Soroos <eric-github@soroos.net>
Date: Wed, 31 Mar 2021 21:04:59 +0200
Subject: [PATCH] fixes crash-74d2

Conflict:NA
Reference:https://github.com/python-pillow/Pillow/commit/45530d5ce1bcc9357907b7e5eeb6e54c6198358e
---
 src/libImaging/TiffDecode.c | 25 ++++++++++++++++---------
 1 file changed, 16 insertions(+), 9 deletions(-)

diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c
index cd47158..accadfd 100644
--- a/src/libImaging/TiffDecode.c
+++ b/src/libImaging/TiffDecode.c
@@ -199,7 +199,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {
     char emsg[1024] = "";
 
     ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
-    if (ret != 1) {
+    if (ret != 1 || rows_per_strip==(UINT32)(-1)) {
         rows_per_strip = state->ysize;
     }
     TRACE(("RowsPerStrip: %u \n", rows_per_strip));
@@ -214,13 +214,6 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {
     img.req_orientation = ORIENTATION_TOPLEFT;
     img.col_offset = 0;
 
-    if (state->xsize != img.width || state->ysize != img.height) {
-        TRACE(("Inconsistent Image Error: %d =? %d, %d =? %d",
-               state->xsize, img.width, state->ysize, img.height));
-        state->errcode = IMAGING_CODEC_BROKEN;
-        goto decodeycbcr_err;
-    }
-
     /* overflow check for row byte size */
     if (INT_MAX / 4 < img.width) {
         state->errcode = IMAGING_CODEC_MEMORY;
@@ -360,6 +353,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_
     TIFF *tiff;
     uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR
     int isYCbCr = 0;
+    UINT32 img_width, img_height;
 
     /* buffer is the encoded file, bytes is the length of the encoded file */
     /*     it all ends up in state->buffer, which is a uint8* from Imaging.h */
@@ -420,7 +414,20 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_
         }
     }
 
-    
+    TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &img_width);
+    TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &img_height);
+
+    if (state->xsize != img_width || state->ysize != img_height) {
+        TRACE(
+            ("Inconsistent Image Error: %d =? %d, %d =? %d",
+             state->xsize,
+             img_width,
+             state->ysize,
+             img_height));
+        state->errcode = IMAGING_CODEC_BROKEN;
+        goto decode_err;
+    }
+
     TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);
     isYCbCr = photometric == PHOTOMETRIC_YCBCR;
     
-- 
2.23.0

