From b4e79bfa0c7d2d08f6f1e7ec38143fc8cb11394a Mon Sep 17 00:00:00 2001
From: Even Rouault <even.rouault@spatialys.com>
Date: Fri, 22 Apr 2022 18:58:52 +0200
Subject: [PATCH] tif_lzw.c: fix potential out-of-bounds error when trying to
 read in the same tile/strip after an error has occured (fixes #410)

Conflict:NA
Reference:https://gitlab.com/libtiff/libtiff/-/commit/b4e79bfa0c7d2d08f6f1e7ec38143fc8cb11394a
---
 libtiff/tif_lzw.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/libtiff/tif_lzw.c b/libtiff/tif_lzw.c
index c28366b..1f255d9 100644
--- a/libtiff/tif_lzw.c
+++ b/libtiff/tif_lzw.c
@@ -140,6 +140,7 @@ typedef struct {
 	code_t* dec_free_entp;		/* next free entry */
 	code_t* dec_maxcodep;		/* max available entry */
 	code_t* dec_codetab;		/* kept separate for small machines */
+	int     read_error;         /* whether a read error has occured, and which should cause further reads in the same strip/tile to be aborted */
 
 	/* Encoding specific data */
 	int     enc_oldcode;		/* last code encountered */
@@ -307,6 +308,7 @@ LZWPreDecode(TIFF* tif, uint16_t s)
 	 */
 	sp->dec_oldcodep = &sp->dec_codetab[0];
 	sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1];
+	sp->read_error = 0;
 	return (1);
 }
 
@@ -399,7 +401,11 @@ LZWDecode(TIFF* tif, uint8_t* op0, tmsize_t occ0, uint16_t s)
 
 	(void) s;
 	assert(sp != NULL);
-        assert(sp->dec_codetab != NULL);
+	assert(sp->dec_codetab != NULL);
+
+	if (sp->read_error) {
+		return 0;
+	}
 
 	/*
 	  Fail if value does not fit in long.
@@ -711,6 +717,7 @@ no_eoi:
                     tif->tif_curstrip);
     return 0;
 error_code:
+    sp->read_error = 1;
     TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Using code not yet in table");
     return 0;
 }
-- 
2.27.0

