libtiff: Fax3: fix failure to decode some fax3 images (fixes #513)

From 8a4f6b587be4fa7bb39fe17f5f9dec52182ab26e Mon Sep 17 00:00:00 2001
From: Even Rouault <[EMAIL REDACTED]>
Date: Sat, 21 Jan 2023 16:54:21 +0100
Subject: [PATCH] Fax3: fix failure to decode some fax3 images (fixes #513)

Patch by @jsummers26
---
 libtiff/tif_fax3.c  | 2 +-
 test/CMakeLists.txt | 3 ++-
 test/Makefile.am    | 5 ++++-
 3 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/libtiff/tif_fax3.c b/libtiff/tif_fax3.c
index 9d66fc0e..a3c645cb 100644
--- a/libtiff/tif_fax3.c
+++ b/libtiff/tif_fax3.c
@@ -537,7 +537,7 @@ static int Fax3SetupState(TIFF *tif)
       TIFFroundup and TIFFSafeMultiply return zero on integer overflow
     */
     dsp->runs = (uint32_t *)NULL;
-    dsp->nruns = TIFFroundup_32(rowpixels, 32);
+    dsp->nruns = TIFFroundup_32(rowpixels + 1, 32);
     if (needsRefLine)
     {
         dsp->nruns = TIFFSafeMultiply(uint32_t, dsp->nruns, 2);
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 907aed8f..1c24b660 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -46,7 +46,8 @@ set(TIFFIMAGES
     images/rgb-3c-8b.tiff
     images/quad-lzw-compat.tiff
     images/lzw-single-strip.tiff
-    images/testfax4.tiff)
+    images/testfax4.tiff
+    images/testfax3_bug_513.tiff)
 # TIFF images using old-jpeg.  Unused unless JPEG support is enabled.
 set(TIFFIMAGES_OJPEG)
 
diff --git a/test/Makefile.am b/test/Makefile.am
index 4ba5e07c..b53b27fa 100644
--- a/test/Makefile.am
+++ b/test/Makefile.am
@@ -158,6 +158,7 @@ TESTSCRIPTS = \
 	tiff2rgba-rgb-3c-16b.sh \
 	tiff2rgba-rgb-3c-8b.sh \
 	testfax4.sh \
+	testfax3_bug_513.sh \
 	testdeflatelaststripextradata.sh \
 	$(JPEG_DEPENDENT_TESTSCRIPTS)
 
@@ -169,6 +170,7 @@ REFFILES = \
 	refs/o-tiff2ps-PS2.ps \
 	refs/o-tiff2ps-PS3.ps \
 	refs/o-testfax4.tiff \
+	refs/o-testfax3_bug_513.sh.tiff \
 	refs/o-deflate-last-strip-extra-data.tiff
 
 # This list should contain all of the TIFF files in the 'images'
@@ -193,7 +195,8 @@ TIFFIMAGES = \
 	images/ojpeg_single_strip_no_rowsperstrip.tiff \
 	images/testfax4.tiff \
 	images/deflate-last-strip-extra-data.tiff \
-	images/custom_dir_EXIF_GPS.tiff
+	images/custom_dir_EXIF_GPS.tiff \
+	images/testfax3_bug_513.tiff
 
 PNMIMAGES = \
 	images/minisblack-1c-8b.pgm \