libtiff: Merge branch 'thunder-fix' into 'master'

From 7dc39d1820a446499ef1a6f71f41d3888b526d2d Mon Sep 17 00:00:00 2001
From: Timothy Lyanguzov <[EMAIL REDACTED]>
Date: Tue, 21 May 2024 21:28:51 +0000
Subject: [PATCH] A fix for Thunder RLE

The commit https://gitlab.com/robinwatts/libtiff/-/commit/be0519ca3d222c19008fe160873f3b5c28e6b36b states:

Thunder RLE can fail to decode last run. Bug seen with GhostPDL. Decode of test tif file gives valgrind errors due to the "thunder decode" failing to extract the final run of compressed pixels.

The logic in the decoder, presumably intended to spot overruns of data, is incorrect in that runs that end at the end of a row (npixels == maxpixels) will not be decoded.

Fix this by limiting 'n', the number of pixels to copy. Note that npixels is updated by the 'unlimited' value to ensure the error reporting at the end of the loop still works.
---
 libtiff/tif_thunder.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/libtiff/tif_thunder.c b/libtiff/tif_thunder.c
index 1f97362c..7b5f6f59 100644
--- a/libtiff/tif_thunder.c
+++ b/libtiff/tif_thunder.c
@@ -107,6 +107,8 @@ static int ThunderDecode(TIFF *tif, uint8_t *op, tmsize_t maxpixels)
                  * Replicate the last pixel n times,
                  * where n is the lower-order 6 bits.
                  */
+                if (n == 0)
+                    break;
                 if (npixels & 1)
                 {
                     op[0] |= lastpixel;
@@ -117,11 +119,10 @@ static int ThunderDecode(TIFF *tif, uint8_t *op, tmsize_t maxpixels)
                 else
                     lastpixel |= lastpixel << 4;
                 npixels += n;
-                if (npixels < maxpixels)
-                {
-                    for (; n > 0; n -= 2)
-                        *op++ = (uint8_t)lastpixel;
-                }
+                if (npixels > maxpixels)
+                    break;
+                for (; n > 0; n -= 2)
+                    *op++ = (uint8_t)lastpixel;
                 if (n == -1)
                     *--op &= 0xf0;
                 lastpixel &= 0xf;