LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_lzw.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 504 614 82.1 %
Date: 2026-12-03 23:43:17 Functions: 18 20 90.0 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 1988-1997 Sam Leffler
       3             :  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
       4             :  * Copyright (c) 2022 Even Rouault
       5             :  *
       6             :  * Permission to use, copy, modify, distribute, and sell this software and
       7             :  * its documentation for any purpose is hereby granted without fee, provided
       8             :  * that (i) the above copyright notices and this permission notice appear in
       9             :  * all copies of the software and related documentation, and (ii) the names of
      10             :  * Sam Leffler and Silicon Graphics may not be used in any advertising or
      11             :  * publicity relating to the software without the specific, prior written
      12             :  * permission of Sam Leffler and Silicon Graphics.
      13             :  *
      14             :  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
      15             :  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
      16             :  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
      17             :  *
      18             :  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
      19             :  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
      20             :  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
      21             :  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
      22             :  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
      23             :  * OF THIS SOFTWARE.
      24             :  */
      25             : 
      26             : /**
      27             :  * @file tif_lzw.c
      28             :  * @brief Implement TIFF LZW encoding standard decoding and legacy decoding.
      29             :  */
      30             : 
      31             : #include "tiffiop.h"
      32             : #ifdef LZW_SUPPORT
      33             : /*
      34             :  * TIFF Library.
      35             :  * Rev 5.0 Lempel-Ziv & Welch Compression Support
      36             :  *
      37             :  * This code is derived from the compress program whose code is
      38             :  * derived from software contributed to Berkeley by James A. Woods,
      39             :  * derived from original work by Spencer Thomas and Joseph Orost.
      40             :  *
      41             :  * The original Berkeley copyright notice appears below in its entirety.
      42             :  */
      43             : #include "tif_predict.h"
      44             : 
      45             : #include <stdbool.h>
      46             : #include <stdio.h>
      47             : #include <stdlib.h>
      48             : 
      49             : /* Select the plausible largest natural integer type for the architecture */
      50             : #define SIZEOF_WORDTYPE SIZEOF_SIZE_T
      51             : /**
      52             :  * @brief Select the native size_t word for buffered LZW bits.
      53             :  * @ingroup libtiff_private_lzw
      54             :  */
      55             : typedef size_t WordType;
      56             : 
      57             : /*
      58             :  * NB: The 5.0 spec describes a different algorithm than Aldus
      59             :  *     implements.  Specifically, Aldus does code length transitions
      60             :  *     one code earlier than should be done (for real LZW).
      61             :  *     Earlier versions of this library implemented the correct
      62             :  *     LZW algorithm, but emitted codes in a bit order opposite
      63             :  *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
      64             :  *     we interpret MSB-LSB ordered codes to be images written w/
      65             :  *     old versions of this library, but otherwise adhere to the
      66             :  *     Aldus "off by one" algorithm.
      67             :  *
      68             :  * Future revisions to the TIFF spec are expected to "clarify this issue".
      69             :  */
      70             : #define LZW_COMPAT /* include backwards compatibility code */
      71             : 
      72             : #define MAXCODE(n) ((1 << (n)) - 1)
      73             : /*
      74             :  * The TIFF spec specifies that encoded bit
      75             :  * strings range from 9 to 12 bits.
      76             :  */
      77             : #define BITS_MIN 9  /* start with 9 bits */
      78             : #define BITS_MAX 12 /* max of 12 bit strings */
      79             : /* predefined codes */
      80             : #define CODE_CLEAR 256 /* code to clear string table */
      81             : #define CODE_EOI 257   /* end-of-information code */
      82             : #define CODE_FIRST 258 /* first free code entry */
      83             : #define CODE_MAX MAXCODE(BITS_MAX)
      84             : #define HSIZE 9001 /* 91% occupancy */
      85             : #define HSHIFT (13 - 8)
      86             : #ifdef LZW_COMPAT
      87             : /* NB: +1024 is for compatibility with old files */
      88             : #define CSIZE (MAXCODE(BITS_MAX) + 1024L)
      89             : #else
      90             : #define CSIZE (MAXCODE(BITS_MAX) + 1L)
      91             : #endif
      92             : 
      93             : /*
      94             :  * State block for each open TIFF file using LZW
      95             :  * compression/decompression.  Note that the predictor
      96             :  * state block must be first in this data structure.
      97             :  */
      98             : /**
      99             :  * @brief Prefix LZW state with Predictor hooks and shared bit-code state.
     100             :  * @ingroup libtiff_private_lzw
     101             :  *
     102             :  * Lives at the start of the handle-owned LZWCodecState (tif_data), which
     103             :  * LZWCleanup() frees.
     104             :  */
     105             : typedef struct
     106             : {
     107             :     /** @brief Predictor prefix; must be the first member. */
     108             :     TIFFPredictorState predict;
     109             : 
     110             :     /** @brief Current code width in bits. */
     111             :     unsigned short nbits;
     112             :     /** @brief Largest code under the current width convention. */
     113             :     unsigned short maxcode;
     114             :     /** @brief Next available dictionary code. */
     115             :     unsigned short free_ent;
     116             :     /** @brief Buffered input/output code bits. */
     117             :     WordType nextdata;
     118             :     /** @brief Number of valid buffered code bits. */
     119             :     long nextbits;
     120             : 
     121             :     /** @brief Open mode saved at codec initialisation. */
     122             :     int rw_mode;
     123             : } LZWBaseState;
     124             : 
     125             : #define lzw_nbits base.nbits
     126             : #define lzw_maxcode base.maxcode
     127             : #define lzw_free_ent base.free_ent
     128             : #define lzw_nextdata base.nextdata
     129             : #define lzw_nextbits base.nextbits
     130             : 
     131             : /*
     132             :  * Encoding-specific state.
     133             :  */
     134             : /**
     135             :  * @brief Store an encoder dictionary code in sixteen bits.
     136             :  * @ingroup libtiff_private_lzw
     137             :  */
     138             : typedef uint16_t hcode_t; /* codes fit in 16 bits */
     139             : /**
     140             :  * @brief Pair an encoder hash key with its dictionary code.
     141             :  * @ingroup libtiff_private_lzw
     142             :  *
     143             :  * Element of the HSIZE-entry enc_hashtab array owned by LZWCodecState;
     144             :  * cl_hash() marks every entry unused.
     145             :  */
     146             : typedef struct
     147             : {
     148             :     /** @brief Encoder lookup key; minus one means unused. */
     149             :     long hash;
     150             :     /** @brief Encoder dictionary code for the key. */
     151             :     hcode_t code;
     152             : } hash_t;
     153             : 
     154             : /*
     155             :  * Decoding-specific state.
     156             :  */
     157             : /**
     158             :  * @brief Link one decoder string to its preceding dictionary string.
     159             :  * @ingroup libtiff_private_lzw
     160             :  *
     161             :  * Element of the CSIZE-entry dec_codetab array owned by LZWCodecState;
     162             :  * next links point into the same array.
     163             :  */
     164             : typedef struct code_ent
     165             : {
     166             :     /**
     167             :      * @brief Borrowed link within the decoder table to the preceding string
     168             :      * entry.
     169             :      */
     170             :     struct code_ent *next;
     171             :     /** @brief Decoded string length including this entry. */
     172             :     unsigned short length;
     173             : 
     174             :     /**
     175             :      * @brief First byte of the decoded string; immediately precedes value for
     176             :      * fast paths.
     177             :      */
     178             :     unsigned char firstchar;
     179             :     /** @brief Final byte represented by this entry. */
     180             :     unsigned char value;
     181             :     /** @brief Whether the string consists of one repeated byte. */
     182             :     bool repeated;
     183             : } code_t;
     184             : 
     185             : /**
     186             :  * @brief Signature shared by the LZW decode entry points (recorded in
     187             :  * dec_decode).
     188             :  * @ingroup libtiff_private_lzw
     189             :  *
     190             :  * Matches LZWDecode() and LZWDecodeCompat(). No pointer of this type is ever
     191             :  * called: decoding is dispatched through tif_decoderow, tif_decodestrip and
     192             :  * tif_decodetile.
     193             :  *
     194             :  * @param[in,out] tif LZW handle being decoded.
     195             :  * @param[out] buf Decoded output of size bytes.
     196             :  * @param[in] size Requested decoded byte count.
     197             :  * @param[in] sample Sample plane, ignored by LZW.
     198             :  * @return One on filling output, zero on decoding failure.
     199             :  */
     200             : typedef int (*decodeFunc)(TIFF *tif, uint8_t *buf, tmsize_t size,
     201             :                           uint16_t sample);
     202             : 
     203             : /**
     204             :  * @brief Own LZW dictionaries hash storage and transfer restart state.
     205             :  * @ingroup libtiff_private_lzw
     206             :  *
     207             :  * Allocated as tif_data by TIFFInitLZW() (or LZWSetupDecode() if missing).
     208             :  * dec_codetab and enc_hashtab are allocated by decode/encode setup, and
     209             :  * LZWCleanup() frees them together with the state.
     210             :  */
     211             : typedef struct
     212             : {
     213             :     /** @brief Shared LZW/Predictor prefix, first in the codec allocation. */
     214             :     LZWBaseState base;
     215             : 
     216             :     /** @brief Right-adjusted mask for current decode width. */
     217             :     long dec_nbitsmask;
     218             :     /** @brief Bytes already returned from an interrupted decoded string. */
     219             :     tmsize_t dec_restart;
     220             :     /** @brief Number of cached raw-input bits remaining. */
     221             :     uint64_t dec_bitsleft;
     222             :     /** @brief Raw byte count saved after the preceding decoder call. */
     223             :     tmsize_t old_tif_rawcc;
     224             :     /**
     225             :      * @brief Decoder last recorded by predecode; NULL until the first
     226             :      * predecode. Used only as a first-strile detection flag, never called, and
     227             :      * may differ from the installed tif_decode* methods.
     228             :      */
     229             :     decodeFunc dec_decode;
     230             :     /** @brief Borrowed current/restart entry within dec_codetab. */
     231             :     code_t *dec_codep;
     232             :     /** @brief Borrowed preceding recognised entry. */
     233             :     code_t *dec_oldcodep;
     234             :     /** @brief Next available decoder table entry cursor. */
     235             :     code_t *dec_free_entp;
     236             :     /** @brief Current width-dependent dictionary limit cursor. */
     237             :     code_t *dec_maxcodep;
     238             :     /** @brief Owned decoder entry allocation, released by cleanup. */
     239             :     code_t *dec_codetab;
     240             :     /** @brief Latched same-strile failure cleared by predecode. */
     241             :     int read_error;
     242             : 
     243             :     /** @brief Pending previous encoder string code. */
     244             :     int enc_oldcode;
     245             :     /** @brief Input-byte threshold for the next ratio test. */
     246             :     tmsize_t enc_checkpoint;
     247             : #define CHECK_GAP 10000
     248             :     /** @brief Cached compression ratio in fixed-point form. */
     249             :     tmsize_t enc_ratio;
     250             :     /** @brief Input bytes counted for ratio estimation. */
     251             :     tmsize_t enc_incount;
     252             :     /** @brief Output code bits counted for ratio estimation. */
     253             :     tmsize_t enc_outcount;
     254             :     /** @brief Borrowed raw-buffer limit leaving room for final codes. */
     255             :     uint8_t *enc_rawlimit;
     256             :     /** @brief Owned HSIZE-entry encoding table, released by cleanup. */
     257             :     hash_t *enc_hashtab;
     258             : } LZWCodecState;
     259             : 
     260             : #define LZWState(tif) ((LZWBaseState *)(tif)->tif_data)
     261             : #define LZWDecoderState(tif) ((LZWCodecState *)LZWState(tif))
     262             : #define LZWEncoderState(tif) ((LZWCodecState *)LZWState(tif))
     263             : 
     264             : static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
     265             : #ifdef LZW_COMPAT
     266             : static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
     267             : #endif
     268             : 
     269             : /*
     270             :  * LZW Decoder.
     271             :  */
     272             : 
     273             : /**
     274             :  * @brief Accept LZW tag fixup without changes.
     275             :  * @ingroup libtiff_private_lzw
     276             :  *
     277             :  * No allocation, I/O, diagnostics, mutation or ownership effects.
     278             :  *
     279             :  * @param[in] tif Unused handle.
     280             :  * @return One unconditionally.
     281             :  */
     282        5221 : static int LZWFixupTags(TIFF *tif)
     283             : {
     284             :     (void)tif;
     285        5221 :     return (1);
     286             : }
     287             : 
     288             : /**
     289             :  * @brief Allocate and initialise the LZW decode dictionary.
     290             :  * @ingroup libtiff_private_lzw
     291             :  *
     292             :  * Allocates handle-owned codec state when absent, installs predictor hooks
     293             :  * on that path, and lazily allocates CSIZE entries. Preloads literal
     294             :  * entries and clears reserved entries. Allocation failure diagnoses and can
     295             :  * retain outer state for cleanup; no pixel I/O. Predictor initialisation
     296             :  * status is not propagated.
     297             :  *
     298             :  * @param[in,out] tif Non-NULL live LZW handle; tif_data may still be NULL,
     299             :  * in which case the state is allocated here. Serialise access.
     300             :  * @return One when dictionary storage is ready, zero on allocation failure.
     301             :  */
     302        2694 : static int LZWSetupDecode(TIFF *tif)
     303             : {
     304             :     static const char module[] = "LZWSetupDecode";
     305        2694 :     LZWCodecState *sp = LZWDecoderState(tif);
     306             :     int code;
     307             : 
     308        2694 :     if (sp == NULL)
     309             :     {
     310             :         /*
     311             :          * Allocate state block so tag methods have storage to record
     312             :          * values.
     313             :          */
     314           0 :         tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
     315           0 :         if (tif->tif_data == NULL)
     316             :         {
     317           0 :             TIFFErrorExtR(tif, module, "No space for LZW state block");
     318           0 :             return (0);
     319             :         }
     320             : 
     321           0 :         sp = LZWDecoderState(tif);
     322           0 :         sp->dec_codetab = NULL;
     323           0 :         sp->dec_decode = NULL;
     324             : 
     325             :         /*
     326             :          * Setup predictor setup.
     327             :          */
     328           0 :         (void)TIFFPredictorInit(tif);
     329             :     }
     330             : 
     331        2695 :     if (sp->dec_codetab == NULL)
     332             :     {
     333        2692 :         sp->dec_codetab = (code_t *)_TIFFmallocExt(tif, CSIZE * sizeof(code_t));
     334        2692 :         if (sp->dec_codetab == NULL)
     335             :         {
     336           0 :             TIFFErrorExtR(tif, module, "No space for LZW code table");
     337           0 :             return (0);
     338             :         }
     339             :         /*
     340             :          * Pre-load the table.
     341             :          */
     342        2692 :         code = 255;
     343       20145 :         do
     344             :         {
     345      687636 :             sp->dec_codetab[code].firstchar = (unsigned char)code;
     346      687636 :             sp->dec_codetab[code].value = (unsigned char)code;
     347      687636 :             sp->dec_codetab[code].repeated = true;
     348      687636 :             sp->dec_codetab[code].length = 1;
     349      687636 :             sp->dec_codetab[code].next = NULL;
     350      687636 :         } while (code--);
     351             :         /*
     352             :          * Zero-out the unused entries  */
     353             :         /* Silence false positive */
     354             :         /* coverity[overrun-buffer-arg] */
     355        2692 :         memset(&sp->dec_codetab[CODE_CLEAR], 0,
     356             :                (CODE_FIRST - CODE_CLEAR) * sizeof(code_t));
     357             :     }
     358        2695 :     return (1);
     359             : }
     360             : 
     361             : /*
     362             :  * Setup state for decoding a strip.
     363             :  */
     364             : /**
     365             :  * @brief Reset LZW bit and dictionary state for a strile.
     366             :  * @ingroup libtiff_private_lzw
     367             :  *
     368             :  * Requires live outer state; lazily attempts setup if needed and rejects a
     369             :  * missing dictionary. Tests the first two raw bytes for historical reversed
     370             :  * code order on every call and, with LZW_COMPAT (always defined), sets the
     371             :  * matching lzw_maxcode convention. Only on the first predecode after codec
     372             :  * initialisation (dec_decode still NULL) does it act on the result: for
     373             :  * old-style data it warns, installs LZWDecodeCompat() as the row/strip/tile
     374             :  * decoder and re-runs setup so that predictor wrappers rebind. The decoder
     375             :  * choice is not revisited for later striles: a later strile with the other code
     376             :  * order keeps the decoder chosen first (and the warning is not repeated).
     377             :  * Without LZW_COMPAT, old-style data fails on every strile but is diagnosed
     378             :  * only the first time. The setup statuses are ignored. Clears restart/error
     379             :  * state and resets code pointers/bit cache. Does not allocate output or read
     380             :  * client bytes directly; setup can allocate/diagnose.
     381             :  *
     382             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
     383             :  * cursors and matching geometry; serialise access.
     384             :  * @param[in] s Unused sample plane; predictor wrappers manage channel
     385             :  * stride.
     386             :  * @return One after reset, zero for missing dictionary or unavailable
     387             :  * compatibility support.
     388             :  */
     389        6619 : static int LZWPreDecode(TIFF *tif, uint16_t s)
     390             : {
     391             :     static const char module[] = "LZWPreDecode";
     392        6619 :     LZWCodecState *sp = LZWDecoderState(tif);
     393             : 
     394             :     (void)s;
     395        6619 :     assert(sp != NULL);
     396        6619 :     if (sp->dec_codetab == NULL)
     397             :     {
     398         115 :         tif->tif_setupdecode(tif);
     399         115 :         if (sp->dec_codetab == NULL)
     400           0 :             return (0);
     401             :     }
     402             : 
     403             :     /*
     404             :      * Check for old bit-reversed codes.
     405             :      */
     406        6619 :     if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 &&
     407         104 :         (tif->tif_rawdata[1] & 0x1))
     408             :     {
     409             : #ifdef LZW_COMPAT
     410         104 :         if (!sp->dec_decode)
     411             :         {
     412           3 :             TIFFWarningExtR(tif, module, "Old-style LZW codes, convert file");
     413             :             /*
     414             :              * Override default decoding methods with
     415             :              * ones that deal with the old coding.
     416             :              * Otherwise the predictor versions set
     417             :              * above will call the compatibility routines
     418             :              * through the dec_decode method.
     419             :              */
     420           3 :             tif->tif_decoderow = LZWDecodeCompat;
     421           3 :             tif->tif_decodestrip = LZWDecodeCompat;
     422           3 :             tif->tif_decodetile = LZWDecodeCompat;
     423             :             /*
     424             :              * If doing horizontal differencing, must
     425             :              * re-setup the predictor logic since we
     426             :              * switched the basic decoder methods...
     427             :              */
     428           3 :             (*tif->tif_setupdecode)(tif);
     429           3 :             sp->dec_decode = LZWDecodeCompat;
     430             :         }
     431         104 :         sp->lzw_maxcode = MAXCODE(BITS_MIN);
     432             : #else  /* !LZW_COMPAT */
     433             :         if (!sp->dec_decode)
     434             :         {
     435             :             TIFFErrorExtR(tif, module, "Old-style LZW codes not supported");
     436             :             sp->dec_decode = LZWDecode;
     437             :         }
     438             :         return (0);
     439             : #endif /* !LZW_COMPAT */
     440             :     }
     441             :     else
     442             :     {
     443        6515 :         sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1;
     444        6515 :         sp->dec_decode = LZWDecode;
     445             :     }
     446        6619 :     sp->lzw_nbits = BITS_MIN;
     447        6619 :     sp->lzw_nextbits = 0;
     448        6619 :     sp->lzw_nextdata = 0;
     449             : 
     450        6619 :     sp->dec_restart = 0;
     451        6619 :     sp->dec_nbitsmask = MAXCODE(BITS_MIN);
     452        6619 :     sp->dec_bitsleft = 0;
     453        6619 :     sp->old_tif_rawcc = 0;
     454        6619 :     sp->dec_free_entp = sp->dec_codetab - 1; // + CODE_FIRST;
     455             :     /*
     456             :      * Zero entries that are not yet filled in.  We do
     457             :      * this to guard against bogus input data that causes
     458             :      * us to index into undefined entries.  If you can
     459             :      * come up with a way to safely bounds-check input codes
     460             :      * while decoding then you can remove this operation.
     461             :      */
     462        6619 :     sp->dec_oldcodep = &sp->dec_codetab[0];
     463        6619 :     sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1];
     464        6619 :     sp->read_error = 0;
     465        6619 :     return (1);
     466             : }
     467             : 
     468             : /*
     469             :  * Decode a "hunk of data".
     470             :  */
     471             : 
     472             : /* Get the next 32 or 64-bit from the input data */
     473             : #if WORDS_BIGENDIAN
     474             : #define GetNextData(nextdata, bp) memcpy(&nextdata, bp, sizeof(nextdata))
     475             : #elif SIZEOF_WORDTYPE == 8
     476             : #if defined(_M_X64)
     477             : #define GetNextData(nextdata, bp) nextdata = _byteswap_uint64(*(uint64_t *)(bp))
     478             : #elif defined(__GNUC__)
     479             : #define GetNextData(nextdata, bp)                                              \
     480             :     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
     481             :     nextdata = __builtin_bswap64(nextdata)
     482             : #else
     483             : #define GetNextData(nextdata, bp)                                              \
     484             :     nextdata = (((uint64_t)bp[0]) << 56) | (((uint64_t)bp[1]) << 48) |         \
     485             :                (((uint64_t)bp[2]) << 40) | (((uint64_t)bp[3]) << 32) |         \
     486             :                (((uint64_t)bp[4]) << 24) | (((uint64_t)bp[5]) << 16) |         \
     487             :                (((uint64_t)bp[6]) << 8) | (((uint64_t)bp[7]))
     488             : #endif
     489             : #elif SIZEOF_WORDTYPE == 4
     490             : #if defined(_M_X86)
     491             : #define GetNextData(nextdata, bp)                                              \
     492             :     nextdata = _byteswap_ulong(*(unsigned long *)(bp))
     493             : #elif defined(__GNUC__)
     494             : #define GetNextData(nextdata, bp)                                              \
     495             :     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
     496             :     nextdata = __builtin_bswap32(nextdata)
     497             : #else
     498             : #define GetNextData(nextdata, bp)                                              \
     499             :     nextdata = (((uint32_t)bp[0]) << 24) | (((uint32_t)bp[1]) << 16) |         \
     500             :                (((uint32_t)bp[2]) << 8) | (((uint32_t)bp[3]))
     501             : #endif
     502             : #else
     503             : #error "Unhandled SIZEOF_WORDTYPE"
     504             : #endif
     505             : 
     506             : #define GetNextCodeLZW()                                                       \
     507             :     do                                                                         \
     508             :     {                                                                          \
     509             :         nextbits -= nbits;                                                     \
     510             :         if (nextbits < 0)                                                      \
     511             :         {                                                                      \
     512             :             if (dec_bitsleft >= 8 * SIZEOF_WORDTYPE)                           \
     513             :             {                                                                  \
     514             :                 unsigned codetmp = (unsigned)(nextdata << (-nextbits));        \
     515             :                 GetNextData(nextdata, bp);                                     \
     516             :                 bp += SIZEOF_WORDTYPE;                                         \
     517             :                 nextbits += 8 * SIZEOF_WORDTYPE;                               \
     518             :                 dec_bitsleft -= 8 * SIZEOF_WORDTYPE;                           \
     519             :                 code = (WordType)((codetmp | (nextdata >> nextbits)) &         \
     520             :                                   (WordType)nbitsmask);                        \
     521             :                 break;                                                         \
     522             :             }                                                                  \
     523             :             else                                                               \
     524             :             {                                                                  \
     525             :                 if (dec_bitsleft < 8)                                          \
     526             :                 {                                                              \
     527             :                     goto no_eoi;                                               \
     528             :                 }                                                              \
     529             :                 nextdata = (nextdata << 8) | *(bp)++;                          \
     530             :                 nextbits += 8;                                                 \
     531             :                 dec_bitsleft -= 8;                                             \
     532             :                 if (nextbits < 0)                                              \
     533             :                 {                                                              \
     534             :                     if (dec_bitsleft < 8)                                      \
     535             :                     {                                                          \
     536             :                         goto no_eoi;                                           \
     537             :                     }                                                          \
     538             :                     nextdata = (nextdata << 8) | *(bp)++;                      \
     539             :                     nextbits += 8;                                             \
     540             :                     dec_bitsleft -= 8;                                         \
     541             :                 }                                                              \
     542             :             }                                                                  \
     543             :         }                                                                      \
     544             :         code = (WordType)((nextdata >> nextbits) & (WordType)nbitsmask);       \
     545             :     } while (0)
     546             : 
     547             : /**
     548             :  * @brief Expand standard TIFF LZW codes into caller output.
     549             :  * @ingroup libtiff_private_lzw
     550             :  *
     551             :  * Requires a nonnegative writable output extent and coherent predecode
     552             :  * dictionary/bit state. Supports interrupted-string restart across calls,
     553             :  * clear/end codes and TIFF early code-width changes. Updates dictionary,
     554             :  * bit cache and raw cursors on normal exits. Detected corrupt/truncated
     555             :  * input clears the unfilled tail, latches read_error, diagnoses and returns
     556             :  * zero; some error exits do not commit local cursor state. Further calls in
     557             :  * the same strile clear requested output and fail until predecode resets
     558             :  * the latch. No allocation/client I/O or ownership transfer.
     559             :  *
     560             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
     561             :  * cursors and matching geometry; serialise access.
     562             :  * @param[out] op0 Borrowed writable output of occ0 bytes, disjoint from raw
     563             :  * input and codec tables.
     564             :  * @param[in] occ0 Nonnegative requested decoded bytes; use a positive
     565             :  * extent during an interrupted-string restart.
     566             :  * @param[in] s Unused sample plane; predictor wrappers manage channel
     567             :  * stride.
     568             :  * @return One when requested output is filled, zero on detected decoding
     569             :  * error.
     570             :  */
     571      114729 : static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
     572             : {
     573             :     static const char module[] = "LZWDecode";
     574      114729 :     LZWCodecState *sp = LZWDecoderState(tif);
     575      114729 :     uint8_t *op = (uint8_t *)op0;
     576      114729 :     tmsize_t occ = occ0;
     577             :     uint8_t *bp;
     578             :     long nbits, nextbits, nbitsmask;
     579             :     WordType nextdata;
     580             :     code_t *free_entp, *maxcodep, *oldcodep;
     581             : 
     582             :     (void)s;
     583      114729 :     assert(sp != NULL);
     584      114729 :     assert(sp->dec_codetab != NULL);
     585             : 
     586      114729 :     if (sp->read_error)
     587             :     {
     588           0 :         memset(op, 0, (size_t)occ);
     589           0 :         TIFFErrorExtR(tif, module,
     590             :                       "LZWDecode: Scanline %" PRIu32 " cannot be read due to "
     591             :                       "previous error",
     592             :                       tif->tif_dir.td_row);
     593           0 :         return 0;
     594             :     }
     595             : 
     596             :     /*
     597             :      * Restart interrupted output operation.
     598             :      */
     599      114729 :     if (sp->dec_restart)
     600             :     {
     601             :         tmsize_t residue;
     602             : 
     603      104113 :         code_t *codep = sp->dec_codep;
     604      104113 :         residue = codep->length - sp->dec_restart;
     605      104113 :         if (residue > occ)
     606             :         {
     607             :             /*
     608             :              * Residue from previous decode is sufficient
     609             :              * to satisfy decode request.  Skip to the
     610             :              * start of the decoded string, place decoded
     611             :              * values in the output buffer, and return.
     612             :              */
     613       99868 :             sp->dec_restart += occ;
     614           0 :             do
     615             :             {
     616     3160750 :                 codep = codep->next;
     617     3160750 :             } while (--residue > occ && codep);
     618       99868 :             if (codep)
     619             :             {
     620       99868 :                 uint8_t *tp = op + occ;
     621           0 :                 do
     622             :                 {
     623      176900 :                     *--tp = codep->value;
     624      176900 :                     codep = codep->next;
     625      176900 :                 } while (--occ && codep);
     626             :             }
     627       99868 :             return (1);
     628             :         }
     629             :         /*
     630             :          * Residue satisfies only part of the decode request.
     631             :          */
     632        4245 :         op += residue;
     633        4245 :         occ -= residue;
     634        4245 :         uint8_t *tp = op;
     635           0 :         do
     636             :         {
     637        6912 :             *--tp = codep->value;
     638        6912 :             codep = codep->next;
     639        6912 :         } while (--residue && codep);
     640        4245 :         sp->dec_restart = 0;
     641             :     }
     642             : 
     643       14861 :     bp = (uint8_t *)tif->tif_rawcp;
     644       14861 :     sp->dec_bitsleft +=
     645       14861 :         (((uint64_t)tif->tif_rawcc - (uint64_t)sp->old_tif_rawcc) << 3);
     646       14861 :     uint64_t dec_bitsleft = sp->dec_bitsleft;
     647       14861 :     nbits = sp->lzw_nbits;
     648       14861 :     nextdata = sp->lzw_nextdata;
     649       14861 :     nextbits = sp->lzw_nextbits;
     650       14861 :     nbitsmask = sp->dec_nbitsmask;
     651       14861 :     oldcodep = sp->dec_oldcodep;
     652       14861 :     free_entp = sp->dec_free_entp;
     653       14861 :     maxcodep = sp->dec_maxcodep;
     654       14861 :     code_t *const dec_codetab = sp->dec_codetab;
     655             :     code_t *codep;
     656             : 
     657       14861 :     if (occ == 0)
     658             :     {
     659        2276 :         goto after_loop;
     660             :     }
     661             : 
     662       12585 : begin:
     663             : {
     664             :     WordType code;
     665   118041017 :     GetNextCodeLZW();
     666   118041017 :     codep = dec_codetab + (unsigned long)code;
     667   118041017 :     if (code >= CODE_FIRST)
     668    48533618 :         goto code_above_or_equal_to_258;
     669    69507199 :     if (code < 256)
     670    69470544 :         goto code_below_256;
     671       36669 :     if (code == CODE_EOI)
     672          10 :         goto after_loop;
     673       36659 :     goto code_clear;
     674             : 
     675    69470544 : code_below_256:
     676             : {
     677    69470544 :     if (codep > free_entp)
     678           0 :         goto error_code;
     679    69470544 :     free_entp->next = oldcodep;
     680    69470544 :     free_entp->firstchar = oldcodep->firstchar;
     681    69470544 :     free_entp->length = (uint16_t)(oldcodep->length + 1);
     682    69470544 :     free_entp->value = (uint8_t)code;
     683    69470544 :     free_entp->repeated =
     684    69470544 :         (bool)(oldcodep->repeated & (oldcodep->value == code));
     685    69470544 :     if (++free_entp > maxcodep)
     686             :     {
     687       57212 :         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
     688           0 :             nbits = BITS_MAX;
     689       57212 :         nbitsmask = MAXCODE(nbits);
     690       57212 :         maxcodep = dec_codetab + nbitsmask - 1;
     691       57212 :         if (free_entp >= &dec_codetab[CSIZE])
     692             :         {
     693             :             /* At that point, the next valid states are either EOI or a
     694             :              */
     695             :             /* CODE_CLEAR. If a regular code is read, at the next */
     696             :             /* attempt at registering a new entry, we will error out */
     697             :             /* due to setting free_entp before any valid code */
     698           0 :             free_entp = dec_codetab - 1;
     699             :         }
     700             :     }
     701    69470544 :     oldcodep = codep;
     702    69470544 :     *op++ = (uint8_t)code;
     703    69470544 :     occ--;
     704    69470544 :     if (occ == 0)
     705        2735 :         goto after_loop;
     706    69467748 :     goto begin;
     707             : }
     708             : 
     709    48533618 : code_above_or_equal_to_258:
     710             : {
     711             :     /*
     712             :      * Add the new entry to the code table.
     713             :      */
     714             : 
     715    48533618 :     if (codep >= free_entp)
     716             :     {
     717      711294 :         if (codep != free_entp)
     718           2 :             goto error_code;
     719      711292 :         free_entp->value = oldcodep->firstchar;
     720             :     }
     721             :     else
     722             :     {
     723    47822246 :         free_entp->value = codep->firstchar;
     724             :     }
     725    48533617 :     free_entp->repeated =
     726    48533617 :         (bool)(oldcodep->repeated & (oldcodep->value == free_entp->value));
     727    48533617 :     free_entp->next = oldcodep;
     728             : 
     729    48533617 :     free_entp->firstchar = oldcodep->firstchar;
     730    48533617 :     free_entp->length = (uint16_t)(oldcodep->length + 1);
     731    48533617 :     if (++free_entp > maxcodep)
     732             :     {
     733       37882 :         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
     734           0 :             nbits = BITS_MAX;
     735       37882 :         nbitsmask = MAXCODE(nbits);
     736       37882 :         maxcodep = dec_codetab + nbitsmask - 1;
     737       37882 :         if (free_entp >= &dec_codetab[CSIZE])
     738             :         {
     739             :             /* At that point, the next valid states are either EOI or a
     740             :              */
     741             :             /* CODE_CLEAR. If a regular code is read, at the next */
     742             :             /* attempt at registering a new entry, we will error out */
     743             :             /* due to setting free_entp before any valid code */
     744           0 :             free_entp = dec_codetab - 1;
     745             :         }
     746             :     }
     747    48533617 :     oldcodep = codep;
     748             : 
     749             :     /*
     750             :      * Code maps to a string, copy string
     751             :      * value to output (written in reverse).
     752             :      */
     753             :     /* tiny bit faster on x86_64 to store in unsigned short than int */
     754    48533617 :     unsigned short len = codep->length;
     755             : 
     756    48533617 :     if (len < 3) /* equivalent to len == 2 given all other conditions */
     757             :     {
     758    38590721 :         if (occ <= 2)
     759             :         {
     760         966 :             if (occ == 2)
     761             :             {
     762         919 :                 memcpy(op, &(codep->firstchar), 2);
     763         919 :                 op += 2;
     764         919 :                 occ -= 2;
     765         919 :                 goto after_loop;
     766             :             }
     767          47 :             goto too_short_buffer;
     768             :         }
     769             : 
     770    38589698 :         memcpy(op, &(codep->firstchar), 2);
     771    38589698 :         op += 2;
     772    38589698 :         occ -= 2;
     773    38589698 :         goto begin; /* we can save the comparison occ > 0 */
     774             :     }
     775             : 
     776     9942886 :     if (len == 3)
     777             :     {
     778     5601088 :         if (occ <= 3)
     779             :         {
     780         344 :             if (occ == 3)
     781             :             {
     782         282 :                 op[0] = codep->firstchar;
     783         282 :                 op[1] = codep->next->value;
     784         282 :                 op[2] = codep->value;
     785         282 :                 op += 3;
     786         282 :                 occ -= 3;
     787         282 :                 goto after_loop;
     788             :             }
     789          62 :             goto too_short_buffer;
     790             :         }
     791             : 
     792     5600747 :         op[0] = codep->firstchar;
     793     5600747 :         op[1] = codep->next->value;
     794     5600747 :         op[2] = codep->value;
     795     5600747 :         op += 3;
     796     5600747 :         occ -= 3;
     797     5600747 :         goto begin; /* we can save the comparison occ > 0 */
     798             :     }
     799             : 
     800     4341798 :     if (len > occ)
     801             :     {
     802        4393 :         goto too_short_buffer;
     803             :     }
     804             : 
     805     4337408 :     if (codep->repeated)
     806             :     {
     807      954303 :         memset(op, codep->value, len);
     808      954303 :         op += len;
     809      954303 :         occ -= len;
     810      954303 :         if (occ == 0)
     811        3372 :             goto after_loop;
     812      950931 :         goto begin;
     813             :     }
     814             : 
     815     3383106 :     uint8_t *tp = op + len;
     816             : 
     817     3383106 :     assert(len >= 4);
     818             : 
     819     3383106 :     *--tp = codep->value;
     820     3383106 :     codep = codep->next;
     821     3383106 :     *--tp = codep->value;
     822     3383106 :     codep = codep->next;
     823     3383106 :     *--tp = codep->value;
     824     3383106 :     codep = codep->next;
     825     3383106 :     *--tp = codep->value;
     826     3383106 :     if (tp > op)
     827             :     {
     828      309809 :         do
     829             :         {
     830    25383291 :             codep = codep->next;
     831    25383291 :             *--tp = codep->value;
     832    25383291 :         } while (tp > op);
     833             :     }
     834             : 
     835     3383106 :     assert(occ >= len);
     836     3383106 :     op += len;
     837     3383106 :     occ -= len;
     838     3383106 :     if (occ == 0)
     839         733 :         goto after_loop;
     840     3382370 :     goto begin;
     841             : }
     842             : 
     843       36659 : code_clear:
     844             : {
     845       36659 :     free_entp = dec_codetab + CODE_FIRST;
     846       36659 :     nbits = BITS_MIN;
     847       36659 :     nbitsmask = MAXCODE(BITS_MIN);
     848       36659 :     maxcodep = dec_codetab + (unsigned long)nbitsmask - 1;
     849           0 :     do
     850             :     {
     851       35921 :         GetNextCodeLZW();
     852       35921 :     } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
     853       36659 :     if (code == CODE_EOI)
     854           0 :         goto after_loop;
     855       36659 :     if (code > CODE_EOI)
     856             :     {
     857           0 :         goto error_code;
     858             :     }
     859       36659 :     *op++ = (uint8_t)code;
     860       36659 :     occ--;
     861       36659 :     oldcodep = dec_codetab + code;
     862       36659 :     if (occ == 0)
     863          30 :         goto after_loop;
     864       36629 :     goto begin;
     865             : }
     866             : }
     867             : 
     868        4502 : too_short_buffer:
     869             : {
     870             :     /*
     871             :      * String is too long for decode buffer,
     872             :      * locate portion that will fit, copy to
     873             :      * the decode buffer, and setup restart
     874             :      * logic for the next decoding call.
     875             :      */
     876        4502 :     sp->dec_codep = codep;
     877           0 :     do
     878             :     {
     879      204361 :         codep = codep->next;
     880      204361 :     } while (codep->length > occ);
     881             : 
     882        4502 :     sp->dec_restart = occ;
     883        4502 :     uint8_t *tp = op + occ;
     884           0 :     do
     885             :     {
     886       28276 :         *--tp = codep->value;
     887       28276 :         codep = codep->next;
     888       28276 :     } while (--occ);
     889             : }
     890             : 
     891        4502 : after_loop:
     892       14859 :     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
     893       14859 :     tif->tif_rawcp = (uint8_t *)bp;
     894       14859 :     sp->old_tif_rawcc = tif->tif_rawcc;
     895       14859 :     sp->dec_bitsleft = dec_bitsleft;
     896       14859 :     sp->lzw_nbits = (unsigned short)nbits;
     897       14859 :     sp->lzw_nextdata = nextdata;
     898       14859 :     sp->lzw_nextbits = nextbits;
     899       14859 :     sp->dec_nbitsmask = nbitsmask;
     900       14859 :     sp->dec_oldcodep = oldcodep;
     901       14859 :     sp->dec_free_entp = free_entp;
     902       14859 :     sp->dec_maxcodep = maxcodep;
     903             : 
     904       14859 :     if (occ > 0)
     905             :     {
     906          10 :         memset(op, 0, (size_t)occ);
     907          10 :         sp->read_error = 1;
     908          10 :         TIFFErrorExtR(tif, module,
     909             :                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
     910             :                       " bytes)",
     911             :                       tif->tif_dir.td_row, (uint64_t)occ);
     912          10 :         return (0);
     913             :     }
     914       14849 :     return (1);
     915             : 
     916           0 : no_eoi:
     917           0 :     memset(op, 0, (size_t)occ);
     918           0 :     sp->read_error = 1;
     919           0 :     TIFFErrorExtR(tif, module,
     920             :                   "LZWDecode: Strip %" PRIu32 " not terminated with EOI code",
     921             :                   tif->tif_dir.td_curstrip);
     922           0 :     return 0;
     923           2 : error_code:
     924           2 :     memset(op, 0, (size_t)occ);
     925           2 :     sp->read_error = 1;
     926           2 :     TIFFErrorExtR(tif, tif->tif_name, "Using code not yet in table");
     927           2 :     return 0;
     928             : }
     929             : 
     930             : #ifdef LZW_COMPAT
     931             : 
     932             : /*
     933             :  * This check shouldn't be necessary because each
     934             :  * strip is suppose to be terminated with CODE_EOI.
     935             :  */
     936             : #define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)                    \
     937             :     {                                                                          \
     938             :         if (dec_bitsleft < (uint64_t)nbits)                                    \
     939             :         {                                                                      \
     940             :             TIFFWarningExtR(_tif, module,                                      \
     941             :                             "LZWDecode: Strip %" PRIu32                        \
     942             :                             " not terminated with EOI code",                   \
     943             :                             _tif->tif_dir.td_curstrip);                        \
     944             :             _code = CODE_EOI;                                                  \
     945             :         }                                                                      \
     946             :         else                                                                   \
     947             :         {                                                                      \
     948             :             _get(_sp, _bp, _code);                                             \
     949             :             dec_bitsleft -= (uint64_t)nbits;                                   \
     950             :         }                                                                      \
     951             :     }
     952             : 
     953             : /*
     954             :  * Decode a "hunk of data" for old images.
     955             :  */
     956             : #define GetNextCodeCompat(sp, bp, code)                                        \
     957             :     {                                                                          \
     958             :         nextdata |= (unsigned long)*(bp)++ << nextbits;                        \
     959             :         nextbits += 8;                                                         \
     960             :         if (nextbits < nbits)                                                  \
     961             :         {                                                                      \
     962             :             nextdata |= (unsigned long)*(bp)++ << nextbits;                    \
     963             :             nextbits += 8;                                                     \
     964             :         }                                                                      \
     965             :         code = (hcode_t)(nextdata & (unsigned long)nbitsmask);                 \
     966             :         nextdata >>= nbits;                                                    \
     967             :         nextbits -= nbits;                                                     \
     968             :     }
     969             : 
     970             : /**
     971             :  * @brief Expand historical reversed-order LZW codes into caller output.
     972             :  * @ingroup libtiff_private_lzw
     973             :  *
     974             :  * Requires compatibility predecode selection, nonnegative output extent and
     975             :  * valid dictionary/raw state. Maintains restart, bit and dictionary
     976             :  * progress across calls. Corrupt dictionary codes and zero-length strings
     977             :  * clear the entire requested output (including bytes already decoded),
     978             :  * latch read_error, diagnose and return zero without committing local
     979             :  * cursor state. Running out of input bits is treated as an end code with
     980             :  * only a warning; if output is then short, the unfilled tail is cleared,
     981             :  * read_error latched and zero returned. While read_error is latched,
     982             :  * further calls clear the requested output and fail until predecode resets
     983             :  * it. No allocation/client I/O or ownership transfer.
     984             :  *
     985             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
     986             :  * cursors and matching geometry; serialise access.
     987             :  * @param[out] op0 Borrowed writable output of occ0 bytes, disjoint from raw
     988             :  * input and codec tables.
     989             :  * @param[in] occ0 Nonnegative requested decoded bytes; use a positive
     990             :  * extent during an interrupted-string restart.
     991             :  * @param[in] s Unused sample plane; predictor wrappers manage channel
     992             :  * stride.
     993             :  * @return One when requested output is filled, zero on detected decoding
     994             :  * error.
     995             :  */
     996         104 : static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
     997             : {
     998             :     static const char module[] = "LZWDecodeCompat";
     999         104 :     LZWCodecState *sp = LZWDecoderState(tif);
    1000         104 :     uint8_t *op = (uint8_t *)op0;
    1001         104 :     tmsize_t occ = occ0;
    1002             :     uint8_t *tp;
    1003             :     uint8_t *bp;
    1004             :     int code, nbits;
    1005             :     int len;
    1006             :     long nextbits, nbitsmask;
    1007             :     WordType nextdata;
    1008             :     code_t *codep, *free_entp, *maxcodep, *oldcodep;
    1009             : 
    1010             :     (void)s;
    1011         104 :     assert(sp != NULL);
    1012             : 
    1013         104 :     if (sp->read_error)
    1014             :     {
    1015           0 :         memset(op, 0, (size_t)occ);
    1016           0 :         TIFFErrorExtR(tif, module,
    1017             :                       "LZWDecodeCompat: Scanline %" PRIu32
    1018             :                       " cannot be read due to previous error",
    1019             :                       tif->tif_dir.td_row);
    1020           0 :         return 0;
    1021             :     }
    1022             : 
    1023             :     /*
    1024             :      * Restart interrupted output operation.
    1025             :      */
    1026         104 :     if (sp->dec_restart)
    1027             :     {
    1028             :         tmsize_t residue;
    1029             : 
    1030           0 :         codep = sp->dec_codep;
    1031           0 :         residue = codep->length - sp->dec_restart;
    1032           0 :         if (residue > occ)
    1033             :         {
    1034             :             /*
    1035             :              * Residue from previous decode is sufficient
    1036             :              * to satisfy decode request.  Skip to the
    1037             :              * start of the decoded string, place decoded
    1038             :              * values in the output buffer, and return.
    1039             :              */
    1040           0 :             sp->dec_restart += occ;
    1041           0 :             do
    1042             :             {
    1043           0 :                 codep = codep->next;
    1044           0 :             } while (--residue > occ);
    1045           0 :             tp = op + occ;
    1046           0 :             do
    1047             :             {
    1048           0 :                 *--tp = codep->value;
    1049           0 :                 codep = codep->next;
    1050           0 :             } while (--occ);
    1051           0 :             return (1);
    1052             :         }
    1053             :         /*
    1054             :          * Residue satisfies only part of the decode request.
    1055             :          */
    1056           0 :         op += residue;
    1057           0 :         occ -= residue;
    1058           0 :         tp = op;
    1059           0 :         do
    1060             :         {
    1061           0 :             *--tp = codep->value;
    1062           0 :             codep = codep->next;
    1063           0 :         } while (--residue);
    1064           0 :         sp->dec_restart = 0;
    1065             :     }
    1066             : 
    1067         104 :     bp = (uint8_t *)tif->tif_rawcp;
    1068             : 
    1069         104 :     sp->dec_bitsleft +=
    1070         104 :         (((uint64_t)tif->tif_rawcc - (uint64_t)sp->old_tif_rawcc) << 3);
    1071         104 :     uint64_t dec_bitsleft = sp->dec_bitsleft;
    1072             : 
    1073         104 :     nbits = sp->lzw_nbits;
    1074         104 :     nextdata = sp->lzw_nextdata;
    1075         104 :     nextbits = sp->lzw_nextbits;
    1076         104 :     nbitsmask = sp->dec_nbitsmask;
    1077         104 :     oldcodep = sp->dec_oldcodep;
    1078         104 :     free_entp = sp->dec_free_entp;
    1079         104 :     maxcodep = sp->dec_maxcodep;
    1080             : 
    1081      208335 :     while (occ > 0)
    1082             :     {
    1083      208231 :         NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
    1084      208231 :         if (code == CODE_EOI)
    1085           0 :             break;
    1086      208231 :         if (code == CODE_CLEAR)
    1087             :         {
    1088           0 :             do
    1089             :             {
    1090         104 :                 free_entp = sp->dec_codetab + CODE_FIRST;
    1091         104 :                 _TIFFmemset(free_entp, 0,
    1092             :                             (CSIZE - CODE_FIRST) * sizeof(code_t));
    1093         104 :                 nbits = BITS_MIN;
    1094         104 :                 nbitsmask = MAXCODE(BITS_MIN);
    1095         104 :                 maxcodep = sp->dec_codetab + nbitsmask;
    1096         104 :                 NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
    1097         104 :             } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
    1098         104 :             if (code == CODE_EOI)
    1099           0 :                 break;
    1100         104 :             if (code > CODE_CLEAR)
    1101             :             {
    1102           0 :                 memset(op0, 0, (size_t)occ0);
    1103           0 :                 sp->read_error = 1;
    1104           0 :                 TIFFErrorExtR(
    1105           0 :                     tif, tif->tif_name,
    1106             :                     "LZWDecode: Corrupted LZW table at scanline %" PRIu32,
    1107             :                     tif->tif_dir.td_row);
    1108           0 :                 return (0);
    1109             :             }
    1110         104 :             *op++ = (uint8_t)code;
    1111         104 :             occ--;
    1112         104 :             oldcodep = sp->dec_codetab + code;
    1113         104 :             continue;
    1114             :         }
    1115      208127 :         codep = sp->dec_codetab + code;
    1116             : 
    1117             :         /*
    1118             :          * Add the new entry to the code table.
    1119             :          */
    1120      208127 :         if (free_entp < &sp->dec_codetab[0] ||
    1121      208127 :             free_entp >= &sp->dec_codetab[CSIZE])
    1122             :         {
    1123           0 :             memset(op0, 0, (size_t)occ0);
    1124           0 :             sp->read_error = 1;
    1125           0 :             TIFFErrorExtR(tif, module,
    1126             :                           "Corrupted LZW table at scanline %" PRIu32,
    1127             :                           tif->tif_dir.td_row);
    1128           0 :             return (0);
    1129             :         }
    1130             : 
    1131      208127 :         free_entp->next = oldcodep;
    1132      208127 :         if (free_entp->next < &sp->dec_codetab[0] ||
    1133      208127 :             free_entp->next >= &sp->dec_codetab[CSIZE])
    1134             :         {
    1135           0 :             memset(op0, 0, (size_t)occ0);
    1136           0 :             sp->read_error = 1;
    1137           0 :             TIFFErrorExtR(tif, module,
    1138             :                           "Corrupted LZW table at scanline %" PRIu32,
    1139             :                           tif->tif_dir.td_row);
    1140           0 :             return (0);
    1141             :         }
    1142      208127 :         free_entp->firstchar = free_entp->next->firstchar;
    1143      208127 :         free_entp->length = (uint16_t)(free_entp->next->length + 1);
    1144      208127 :         free_entp->value =
    1145         123 :             (codep < free_entp) ? codep->firstchar : free_entp->firstchar;
    1146      208127 :         if (++free_entp > maxcodep)
    1147             :         {
    1148        8825 :             if (++nbits > BITS_MAX) /* should not happen */
    1149        8645 :                 nbits = BITS_MAX;
    1150        8825 :             nbitsmask = MAXCODE(nbits);
    1151        8825 :             maxcodep = sp->dec_codetab + nbitsmask;
    1152             :         }
    1153      208127 :         oldcodep = codep;
    1154      208127 :         if (code >= 256)
    1155             :         {
    1156             :             /*
    1157             :              * Code maps to a string, copy string
    1158             :              * value to output (written in reverse).
    1159             :              */
    1160       69239 :             if (codep->length == 0)
    1161             :             {
    1162           0 :                 memset(op0, 0, (size_t)occ0);
    1163           0 :                 sp->read_error = 1;
    1164           0 :                 TIFFErrorExtR(
    1165             :                     tif, module,
    1166             :                     "Wrong length of decoded "
    1167             :                     "string: data probably corrupted at scanline %" PRIu32,
    1168             :                     tif->tif_dir.td_row);
    1169           0 :                 return (0);
    1170             :             }
    1171       69239 :             if (codep->length > occ)
    1172             :             {
    1173             :                 /*
    1174             :                  * String is too long for decode buffer,
    1175             :                  * locate portion that will fit, copy to
    1176             :                  * the decode buffer, and setup restart
    1177             :                  * logic for the next decoding call.
    1178             :                  */
    1179           0 :                 sp->dec_codep = codep;
    1180           0 :                 do
    1181             :                 {
    1182           0 :                     codep = codep->next;
    1183           0 :                 } while (codep->length > occ);
    1184           0 :                 sp->dec_restart = occ;
    1185           0 :                 tp = op + occ;
    1186           0 :                 do
    1187             :                 {
    1188           0 :                     *--tp = codep->value;
    1189           0 :                     codep = codep->next;
    1190           0 :                 } while (--occ);
    1191           0 :                 break;
    1192             :             }
    1193       69239 :             len = codep->length;
    1194       69239 :             tp = op + len;
    1195        7556 :             do
    1196             :             {
    1197      658192 :                 *--tp = codep->value;
    1198      658192 :                 codep = codep->next;
    1199      658192 :             } while (codep && tp > op);
    1200       69239 :             assert(occ >= len);
    1201       69239 :             op += len;
    1202       69239 :             occ -= len;
    1203             :         }
    1204             :         else
    1205             :         {
    1206      138888 :             *op++ = (uint8_t)code;
    1207      138888 :             occ--;
    1208             :         }
    1209             :     }
    1210             : 
    1211         104 :     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
    1212         104 :     tif->tif_rawcp = (uint8_t *)bp;
    1213             : 
    1214         104 :     sp->old_tif_rawcc = tif->tif_rawcc;
    1215         104 :     sp->dec_bitsleft = dec_bitsleft;
    1216             : 
    1217         104 :     sp->lzw_nbits = (unsigned short)nbits;
    1218         104 :     sp->lzw_nextdata = nextdata;
    1219         104 :     sp->lzw_nextbits = nextbits;
    1220         104 :     sp->dec_nbitsmask = nbitsmask;
    1221         104 :     sp->dec_oldcodep = oldcodep;
    1222         104 :     sp->dec_free_entp = free_entp;
    1223         104 :     sp->dec_maxcodep = maxcodep;
    1224             : 
    1225         104 :     if (occ > 0)
    1226             :     {
    1227           0 :         memset(op, 0, (size_t)occ);
    1228           0 :         sp->read_error = 1;
    1229           0 :         TIFFErrorExtR(tif, module,
    1230             :                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
    1231             :                       " bytes)",
    1232             :                       tif->tif_dir.td_row, (uint64_t)occ);
    1233           0 :         return (0);
    1234             :     }
    1235         104 :     return (1);
    1236             : }
    1237             : #endif /* LZW_COMPAT */
    1238             : 
    1239             : #ifndef LZW_READ_ONLY
    1240             : 
    1241             : static void cl_hash(LZWCodecState *);
    1242             : 
    1243             : /*
    1244             :  * LZW Encoding.
    1245             :  */
    1246             : 
    1247             : /**
    1248             :  * @brief Allocate the LZW encoder hash table.
    1249             :  * @ingroup libtiff_private_lzw
    1250             :  *
    1251             :  * Requires existing codec state and no previous unreleased encoder table;
    1252             :  * assigns a new handle-owned HSIZE allocation. Diagnoses allocation
    1253             :  * failure; no pixel I/O. Cleanup releases the table.
    1254             :  *
    1255             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
    1256             :  * cursors and matching geometry; serialise access.
    1257             :  * @return One after allocation, zero on failure.
    1258             :  */
    1259       12429 : static int LZWSetupEncode(TIFF *tif)
    1260             : {
    1261             :     static const char module[] = "LZWSetupEncode";
    1262       12429 :     LZWCodecState *sp = LZWEncoderState(tif);
    1263             : 
    1264       12429 :     assert(sp != NULL);
    1265       12429 :     sp->enc_hashtab = (hash_t *)_TIFFmallocExt(tif, HSIZE * sizeof(hash_t));
    1266       12429 :     if (sp->enc_hashtab == NULL)
    1267             :     {
    1268           0 :         TIFFErrorExtR(tif, module, "No space for LZW hash table");
    1269           0 :         return (0);
    1270             :     }
    1271       12429 :     return (1);
    1272             : }
    1273             : 
    1274             : /*
    1275             :  * Reset encoding state at the start of a strip.
    1276             :  */
    1277             : /**
    1278             :  * @brief Reset the LZW encoder dictionary bit cache and counters.
    1279             :  * @ingroup libtiff_private_lzw
    1280             :  *
    1281             :  * Requires valid outer state and an allocated hash table. A raw output
    1282             :  * buffer smaller than five bytes, the most LZWEncode() and LZWPostEncode()
    1283             :  * write after their room checks, is diagnosed and rejected. If table is
    1284             :  * NULL it
    1285             :  * invokes setup but does not check its return before clearing the table;
    1286             :  * caller must ensure setup succeeds. Resets code widths, checkpoint,
    1287             :  * pending code and output limit. Does not emit payload directly; setup can
    1288             :  * allocate/diagnose.
    1289             :  *
    1290             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
    1291             :  * cursors and matching geometry; serialise access.
    1292             :  * @param[in] s Unused sample plane; predictor wrappers manage channel
    1293             :  * stride.
    1294             :  * @return One after reset, zero for a raw buffer smaller than five bytes;
    1295             :  * not independent validation of setup success.
    1296             :  */
    1297       14233 : static int LZWPreEncode(TIFF *tif, uint16_t s)
    1298             : {
    1299             :     static const char module[] = "LZWPreEncode";
    1300       14233 :     LZWCodecState *sp = LZWEncoderState(tif);
    1301             : 
    1302             :     (void)s;
    1303       14233 :     assert(sp != NULL);
    1304             : 
    1305             :     /*
    1306             :      * LZWEncode() may write two codes (up to 4 bytes) after its room check,
    1307             :      * and LZWPostEncode() may write up to 5 bytes. Both assume the raw data
    1308             :      * buffer holds at least 5 bytes.
    1309             :      */
    1310       14233 :     if (tif->tif_rawdatasize < 5)
    1311             :     {
    1312           0 :         TIFFErrorExtR(tif, module,
    1313             :                       "Raw data buffer of %" TIFF_SSIZE_FORMAT
    1314             :                       " bytes is too small for LZW encoding, at least 5 bytes"
    1315             :                       " are needed",
    1316             :                       tif->tif_rawdatasize);
    1317           0 :         return (0);
    1318             :     }
    1319             : 
    1320       14233 :     if (sp->enc_hashtab == NULL)
    1321             :     {
    1322           2 :         tif->tif_setupencode(tif);
    1323             :     }
    1324             : 
    1325       14233 :     sp->lzw_nbits = BITS_MIN;
    1326       14233 :     sp->lzw_maxcode = MAXCODE(BITS_MIN);
    1327       14233 :     sp->lzw_free_ent = CODE_FIRST;
    1328       14233 :     sp->lzw_nextbits = 0;
    1329       14233 :     sp->lzw_nextdata = 0;
    1330       14233 :     sp->enc_checkpoint = CHECK_GAP;
    1331       14233 :     sp->enc_ratio = 0;
    1332       14233 :     sp->enc_incount = 0;
    1333       14233 :     sp->enc_outcount = 0;
    1334             :     /*
    1335             :      * The 4 here insures there is space for 2 max-sized
    1336             :      * codes in LZWEncode and LZWPostDecode.
    1337             :      */
    1338       14233 :     sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize - 1 - 4;
    1339       14233 :     cl_hash(sp);                   /* clear hash table */
    1340       14233 :     sp->enc_oldcode = (hcode_t)-1; /* generates CODE_CLEAR in LZWEncode */
    1341       14233 :     return (1);
    1342             : }
    1343             : 
    1344             : #define CALCRATIO(sp, rat)                                                     \
    1345             :     {                                                                          \
    1346             :         if (incount > 0x007fffff)                                              \
    1347             :         { /* NB: shift will overflow */                                        \
    1348             :             rat = outcount >> 8;                                               \
    1349             :             rat = (rat == 0 ? 0x7fffffff : incount / rat);                     \
    1350             :         }                                                                      \
    1351             :         else                                                                   \
    1352             :             rat = (incount << 8) / outcount;                                   \
    1353             :     }
    1354             : 
    1355             : /* Explicit 0xff masking to make icc -check=conversions happy */
    1356             : #define PutNextCode(op, c)                                                     \
    1357             :     {                                                                          \
    1358             :         nextdata = (nextdata << nbits) | c;                                    \
    1359             :         nextbits += nbits;                                                     \
    1360             :         *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);          \
    1361             :         nextbits -= 8;                                                         \
    1362             :         if (nextbits >= 8)                                                     \
    1363             :         {                                                                      \
    1364             :             *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);      \
    1365             :             nextbits -= 8;                                                     \
    1366             :         }                                                                      \
    1367             :         outcount += nbits;                                                     \
    1368             :     }
    1369             : 
    1370             : /*
    1371             :  * Encode a chunk of pixels.
    1372             :  *
    1373             :  * Uses an open addressing double hashing (no chaining) on the
    1374             :  * prefix code/next character combination.  We do a variant of
    1375             :  * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
    1376             :  * relatively-prime secondary probe.  Here, the modular division
    1377             :  * first probe is gives way to a faster exclusive-or manipulation.
    1378             :  * Also do block compression with an adaptive reset, whereby the
    1379             :  * code table is cleared when the compression ratio decreases,
    1380             :  * but after the table fills.  The variable-length output codes
    1381             :  * are re-sized at this point, and a CODE_CLEAR is generated
    1382             :  * for the decoder.
    1383             :  */
    1384             : /**
    1385             :  * @brief Compress borrowed bytes into buffered TIFF LZW codes.
    1386             :  * @ingroup libtiff_private_lzw
    1387             :  *
    1388             :  * Requires successful encoder setup/preencode, nonnegative input length and
    1389             :  * usable raw capacity/limit. Updates code/hash state, emits clear codes and
    1390             :  * adjusts code width; ratio checkpoints can reset the dictionary. Flushes
    1391             :  * when needed, invoking client I/O and diagnostics. Input is not changed.
    1392             :  * Early flush failure can leave output bytes, dictionary and local/cached
    1393             :  * progress inconsistent for retry; no rollback or ownership transfer.
    1394             :  *
    1395             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
    1396             :  * cursors and matching geometry; serialise access.
    1397             :  * @param[in] bp Borrowed readable cc-byte input, not retained.
    1398             :  * @param[in] cc Nonnegative input byte count.
    1399             :  * @param[in] s Unused sample plane; predictor wrappers manage channel
    1400             :  * stride.
    1401             :  * @return One after encoding, zero for missing state or flush failure.
    1402             :  */
    1403       36229 : static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
    1404             : {
    1405       36229 :     LZWCodecState *sp = LZWEncoderState(tif);
    1406             :     long fcode;
    1407             :     hash_t *hp;
    1408             :     int h, c;
    1409             :     hcode_t ent;
    1410             :     long disp;
    1411             :     tmsize_t incount, outcount, checkpoint;
    1412             :     WordType nextdata;
    1413             :     long nextbits;
    1414             :     int free_ent, maxcode, nbits;
    1415             :     uint8_t *op;
    1416             :     uint8_t *limit;
    1417             : 
    1418             :     (void)s;
    1419       36229 :     if (sp == NULL)
    1420           0 :         return (0);
    1421             : 
    1422       36229 :     assert(sp->enc_hashtab != NULL);
    1423             : 
    1424             :     /*
    1425             :      * Load local state.
    1426             :      */
    1427       36229 :     incount = sp->enc_incount;
    1428       36229 :     outcount = sp->enc_outcount;
    1429       36229 :     checkpoint = sp->enc_checkpoint;
    1430       36229 :     nextdata = sp->lzw_nextdata;
    1431       36229 :     nextbits = sp->lzw_nextbits;
    1432       36229 :     free_ent = sp->lzw_free_ent;
    1433       36229 :     maxcode = sp->lzw_maxcode;
    1434       36229 :     nbits = sp->lzw_nbits;
    1435       36229 :     op = tif->tif_rawcp;
    1436       36229 :     limit = sp->enc_rawlimit;
    1437       36229 :     ent = (hcode_t)sp->enc_oldcode;
    1438             : 
    1439       36229 :     if (ent == (hcode_t)-1 && cc > 0)
    1440             :     {
    1441             :         /*
    1442             :          * NB: This is safe because it can only happen
    1443             :          *     at the start of a strip where we know there
    1444             :          *     is space in the data buffer.
    1445             :          */
    1446       14233 :         PutNextCode(op, CODE_CLEAR);
    1447       14233 :         ent = *bp++;
    1448       14233 :         cc--;
    1449       14233 :         incount++;
    1450             :     }
    1451       36229 :     while (cc > 0)
    1452             :     {
    1453   828886000 :         c = *bp++;
    1454   828886000 :         cc--;
    1455   828886000 :         incount++;
    1456   828886000 :         fcode = ((long)c << BITS_MAX) + ent;
    1457   828886000 :         h = (c << HSHIFT) ^ ent; /* xor hashing */
    1458   828886000 :         hp = &sp->enc_hashtab[h];
    1459   828886000 :         if (hp->hash == fcode)
    1460             :         {
    1461   624571000 :             ent = hp->code;
    1462   624571000 :             continue;
    1463             :         }
    1464   204316000 :         if (hp->hash >= 0)
    1465             :         {
    1466             :             /*
    1467             :              * Primary hash failed, check secondary hash.
    1468             :              */
    1469   122601000 :             disp = HSIZE - h;
    1470   122601000 :             if (h == 0)
    1471       32420 :                 disp = 1;
    1472             :             do
    1473             :             {
    1474             :                 /*
    1475             :                  * Avoid pointer arithmetic because of
    1476             :                  * wraparound problems with segments.
    1477             :                  */
    1478   181389000 :                 if ((h -= (int)disp) < 0)
    1479   145200000 :                     h += HSIZE;
    1480   181389000 :                 hp = &sp->enc_hashtab[h];
    1481   181389000 :                 if (hp->hash == fcode)
    1482             :                 {
    1483    88632400 :                     ent = hp->code;
    1484    88632400 :                     goto hit;
    1485             :                 }
    1486    92757100 :             } while (hp->hash >= 0);
    1487             :         }
    1488             :         /*
    1489             :          * New entry, emit code and add to table.
    1490             :          */
    1491             :         /*
    1492             :          * Verify there is space in the buffer for the code
    1493             :          * and any potential Clear code that might be emitted
    1494             :          * below.  The value of limit is setup so that there
    1495             :          * are at least 4 bytes free--room for 2 codes.
    1496             :          */
    1497   115683000 :         if (op > limit)
    1498             :         {
    1499           1 :             tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1500           1 :             if (!TIFFFlushData1(tif))
    1501           0 :                 return 0;
    1502           1 :             op = tif->tif_rawdata;
    1503             :         }
    1504   115683000 :         PutNextCode(op, ent);
    1505   115683000 :         ent = (hcode_t)c;
    1506   115683000 :         hp->code = (hcode_t)(free_ent++);
    1507   115683000 :         hp->hash = fcode;
    1508   115683000 :         if (free_ent == CODE_MAX - 1)
    1509             :         {
    1510             :             /* table is full, emit clear code and reset */
    1511       29484 :             cl_hash(sp);
    1512       29484 :             sp->enc_ratio = 0;
    1513       29484 :             incount = 0;
    1514       29484 :             outcount = 0;
    1515       29484 :             free_ent = CODE_FIRST;
    1516       29484 :             PutNextCode(op, CODE_CLEAR);
    1517       29484 :             nbits = BITS_MIN;
    1518       29484 :             maxcode = MAXCODE(BITS_MIN);
    1519             :         }
    1520             :         else
    1521             :         {
    1522             :             /*
    1523             :              * If the next entry is going to be too big for
    1524             :              * the code size, then increase it, if possible.
    1525             :              */
    1526   115654000 :             if (free_ent > maxcode)
    1527             :             {
    1528       96271 :                 nbits++;
    1529       96271 :                 assert(nbits <= BITS_MAX);
    1530       96271 :                 maxcode = (int)MAXCODE(nbits);
    1531             :             }
    1532   115558000 :             else if (incount >= checkpoint)
    1533             :             {
    1534             :                 tmsize_t rat;
    1535             :                 /*
    1536             :                  * Check compression ratio and, if things seem
    1537             :                  * to be slipping, clear the hash table and
    1538             :                  * reset state.  The compression ratio is a
    1539             :                  * 24+8-bit fractional number.
    1540             :                  */
    1541       59245 :                 checkpoint = incount + CHECK_GAP;
    1542       59245 :                 CALCRATIO(sp, rat);
    1543       59245 :                 if (rat <= sp->enc_ratio)
    1544             :                 {
    1545         228 :                     cl_hash(sp);
    1546         228 :                     sp->enc_ratio = 0;
    1547         228 :                     incount = 0;
    1548         228 :                     outcount = 0;
    1549         228 :                     free_ent = CODE_FIRST;
    1550         228 :                     PutNextCode(op, CODE_CLEAR);
    1551         228 :                     nbits = BITS_MIN;
    1552         228 :                     maxcode = MAXCODE(BITS_MIN);
    1553             :                 }
    1554             :                 else
    1555       59017 :                     sp->enc_ratio = rat;
    1556             :             }
    1557             :         }
    1558   828923000 :     hit:;
    1559             :     }
    1560             : 
    1561             :     /*
    1562             :      * Restore global state.
    1563             :      */
    1564       36229 :     sp->enc_incount = incount;
    1565       36229 :     sp->enc_outcount = outcount;
    1566       36229 :     sp->enc_checkpoint = checkpoint;
    1567       36229 :     sp->enc_oldcode = ent;
    1568       36229 :     sp->lzw_nextdata = nextdata;
    1569       36229 :     sp->lzw_nextbits = nextbits;
    1570       36229 :     sp->lzw_free_ent = (unsigned short)free_ent;
    1571       36229 :     sp->lzw_maxcode = (unsigned short)maxcode;
    1572       36229 :     sp->lzw_nbits = (unsigned short)nbits;
    1573       36229 :     tif->tif_rawcp = op;
    1574       36229 :     return (1);
    1575             : }
    1576             : 
    1577             : /*
    1578             :  * Finish off an encoded strip by flushing the last
    1579             :  * string and tacking on an End Of Information code.
    1580             :  */
    1581             : /**
    1582             :  * @brief Emit the final LZW string end code and padding bits.
    1583             :  * @ingroup libtiff_private_lzw
    1584             :  *
    1585             :  * Requires valid encoder state and reserved raw capacity. Can flush first,
    1586             :  * emit clear/width changes, append EOI and pad the last byte, then set
    1587             :  * rawcc. Does not persist the IFD or guarantee final buffered bytes were
    1588             :  * written. Raw/file state can change before failed flush; no ownership
    1589             :  * transfer.
    1590             :  *
    1591             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
    1592             :  * cursors and matching geometry; serialise access.
    1593             :  * @return One after final codes buffered, zero on flush failure.
    1594             :  */
    1595       14233 : static int LZWPostEncode(TIFF *tif)
    1596             : {
    1597       14233 :     LZWCodecState *sp = LZWEncoderState(tif);
    1598       14233 :     uint8_t *op = tif->tif_rawcp;
    1599       14233 :     long nextbits = sp->lzw_nextbits;
    1600       14233 :     WordType nextdata = sp->lzw_nextdata;
    1601       14233 :     tmsize_t outcount = sp->enc_outcount;
    1602       14233 :     int nbits = sp->lzw_nbits;
    1603             : 
    1604       14233 :     if (op > sp->enc_rawlimit)
    1605             :     {
    1606           0 :         tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1607           0 :         if (!TIFFFlushData1(tif))
    1608           0 :             return 0;
    1609           0 :         op = tif->tif_rawdata;
    1610             :     }
    1611       14233 :     if (sp->enc_oldcode != (hcode_t)-1)
    1612             :     {
    1613       14233 :         int free_ent = sp->lzw_free_ent;
    1614             : 
    1615       14233 :         PutNextCode(op, (WordType)sp->enc_oldcode);
    1616       14233 :         sp->enc_oldcode = (hcode_t)-1;
    1617       14233 :         free_ent++;
    1618             : 
    1619       14233 :         if (free_ent == CODE_MAX - 1)
    1620             :         {
    1621             :             /* table is full, emit clear code and reset */
    1622           0 :             outcount = 0;
    1623           0 :             PutNextCode(op, CODE_CLEAR);
    1624           0 :             nbits = BITS_MIN;
    1625             :         }
    1626             :         else
    1627             :         {
    1628             :             /*
    1629             :              * If the next entry is going to be too big for
    1630             :              * the code size, then increase it, if possible.
    1631             :              */
    1632       14233 :             if (free_ent > sp->lzw_maxcode)
    1633             :             {
    1634           2 :                 nbits++;
    1635           2 :                 assert(nbits <= BITS_MAX);
    1636             :             }
    1637             :         }
    1638             :     }
    1639       14233 :     PutNextCode(op, CODE_EOI);
    1640             :     /* Explicit 0xff masking to make icc -check=conversions happy */
    1641       14233 :     if (nextbits > 0)
    1642       14092 :         *op++ = (unsigned char)((nextdata << (8 - nextbits)) & 0xff);
    1643       14233 :     tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1644             :     (void)outcount;
    1645       14233 :     return (1);
    1646             : }
    1647             : 
    1648             : /*
    1649             :  * Reset encoding hash table.
    1650             :  */
    1651             : /**
    1652             :  * @brief Mark every LZW encoder hash slot unused.
    1653             :  * @ingroup libtiff_private_lzw
    1654             :  *
    1655             :  * Requires a live HSIZE-entry table. Sets hash fields to minus one; code
    1656             :  * fields need not be cleared. No allocation, I/O, diagnostics, ownership
    1657             :  * changes or error status.
    1658             :  *
    1659             :  * @param[in,out] sp Non-NULL codec state owning an allocated HSIZE-entry
    1660             :  * encoder table.
    1661             :  */
    1662       43944 : static void cl_hash(LZWCodecState *sp)
    1663             : {
    1664       43944 :     hash_t *hp = &sp->enc_hashtab[HSIZE - 1];
    1665       43944 :     long i = HSIZE - 8;
    1666             : 
    1667             :     do
    1668             :     {
    1669    49432000 :         i -= 8;
    1670    49432000 :         hp[-7].hash = -1;
    1671    49432000 :         hp[-6].hash = -1;
    1672    49432000 :         hp[-5].hash = -1;
    1673    49432000 :         hp[-4].hash = -1;
    1674    49432000 :         hp[-3].hash = -1;
    1675    49432000 :         hp[-2].hash = -1;
    1676    49432000 :         hp[-1].hash = -1;
    1677    49432000 :         hp[0].hash = -1;
    1678    49432000 :         hp -= 8;
    1679    49432000 :     } while (i >= 0);
    1680       87889 :     for (i += 8; i > 0; i--, hp--)
    1681       43945 :         hp->hash = -1;
    1682       43944 : }
    1683             : 
    1684             : #endif
    1685             : 
    1686             : /**
    1687             :  * @brief Release LZW tables and codec state and reset methods.
    1688             :  * @ingroup libtiff_private_lzw
    1689             :  *
    1690             :  * Requires live initialised LZW state. Restores predictor chains, frees
    1691             :  * dictionary and hash table if present, frees outer state and sets tif_data
    1692             :  * NULL, then installs default compression methods. Invalidates all
    1693             :  * state/table views. Does not flush payload or close the borrowed handle;
    1694             :  * no separate status result.
    1695             :  *
    1696             :  * @param[in,out] tif Non-NULL live LZW handle with valid state, raw-buffer
    1697             :  * cursors and matching geometry; serialise access.
    1698             :  */
    1699       20129 : static void LZWCleanup(TIFF *tif)
    1700             : {
    1701       20129 :     (void)TIFFPredictorCleanup(tif);
    1702             : 
    1703       20129 :     assert(tif->tif_data != NULL);
    1704             : 
    1705       20129 :     if (LZWDecoderState(tif)->dec_codetab)
    1706        2690 :         _TIFFfreeExt(tif, LZWDecoderState(tif)->dec_codetab);
    1707             : 
    1708       20130 :     if (LZWEncoderState(tif)->enc_hashtab)
    1709       12429 :         _TIFFfreeExt(tif, LZWEncoderState(tif)->enc_hashtab);
    1710             : 
    1711       20130 :     _TIFFfreeExt(tif, tif->tif_data);
    1712       20130 :     tif->tif_data = NULL;
    1713             : 
    1714       20130 :     _TIFFSetDefaultCompressionState(tif);
    1715       20131 : }
    1716             : 
    1717             : /**
    1718             :  * @brief Report the empirical LZW expansion heuristic.
    1719             :  * @ingroup libtiff_private_lzw
    1720             :  *
    1721             :  * Ignores the handle; no allocation, I/O, diagnostics, state or ownership
    1722             :  * effects. Not a universal compression bound or data-validation guarantee.
    1723             :  *
    1724             :  * @param[in] tif Unused handle.
    1725             :  * @return One thousand four hundred.
    1726             :  */
    1727           0 : static uint64_t LZWGetMaxCompressionRatio(TIFF *tif)
    1728             : {
    1729             :     (void)tif;
    1730             : 
    1731             :     /* See README_for_libtiff_developpers.md for raw data used to estimate
    1732             :      * the maximum compression rate. */
    1733             : 
    1734             :     /* 1024x1024: 562 */
    1735             :     /* 4096x4096: 1243 */
    1736             :     /* 16383x16383: 1353 */
    1737             :     /* 65536x65536: 1362 */
    1738             : 
    1739           0 :     return 1400;
    1740             : }
    1741             : 
    1742       20132 : int TIFFInitLZW(TIFF *tif, int scheme)
    1743             : {
    1744             :     static const char module[] = "TIFFInitLZW";
    1745             :     (void)scheme;
    1746       20132 :     assert(scheme == COMPRESSION_LZW);
    1747             :     /*
    1748             :      * Allocate state block so tag methods have storage to record values.
    1749             :      */
    1750       20132 :     tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
    1751       20130 :     if (tif->tif_data == NULL)
    1752           0 :         goto bad;
    1753       20130 :     LZWDecoderState(tif)->dec_codetab = NULL;
    1754       20130 :     LZWDecoderState(tif)->dec_decode = NULL;
    1755       20130 :     LZWEncoderState(tif)->enc_hashtab = NULL;
    1756       20130 :     LZWState(tif)->rw_mode = tif->tif_mode;
    1757             : 
    1758             :     /*
    1759             :      * Install codec methods.
    1760             :      */
    1761       20130 :     tif->tif_fixuptags = LZWFixupTags;
    1762       20130 :     tif->tif_setupdecode = LZWSetupDecode;
    1763       20130 :     tif->tif_predecode = LZWPreDecode;
    1764       20130 :     tif->tif_decoderow = LZWDecode;
    1765       20130 :     tif->tif_decodestrip = LZWDecode;
    1766       20130 :     tif->tif_decodetile = LZWDecode;
    1767             : #ifndef LZW_READ_ONLY
    1768       20051 :     tif->tif_setupencode = LZWSetupEncode;
    1769       20051 :     tif->tif_preencode = LZWPreEncode;
    1770       20051 :     tif->tif_postencode = LZWPostEncode;
    1771       20051 :     tif->tif_encoderow = LZWEncode;
    1772       20051 :     tif->tif_encodestrip = LZWEncode;
    1773       20051 :     tif->tif_encodetile = LZWEncode;
    1774             : #endif
    1775       20130 :     tif->tif_getmaxcompressionratio = LZWGetMaxCompressionRatio;
    1776       20130 :     tif->tif_cleanup = LZWCleanup;
    1777             :     /*
    1778             :      * Setup predictor setup.
    1779             :      */
    1780       20130 :     (void)TIFFPredictorInit(tif);
    1781       20132 :     return (1);
    1782           0 : bad:
    1783           0 :     TIFFErrorExtR(tif, module, "No space for LZW state block");
    1784           0 :     return (0);
    1785             : }
    1786             : 
    1787             : /*
    1788             :  * Copyright (c) 1985, 1986 The Regents of the University of California.
    1789             :  * All rights reserved.
    1790             :  *
    1791             :  * This code is derived from software contributed to Berkeley by
    1792             :  * James A. Woods, derived from original work by Spencer Thomas
    1793             :  * and Joseph Orost.
    1794             :  *
    1795             :  * Redistribution and use in source and binary forms are permitted
    1796             :  * provided that the above copyright notice and this paragraph are
    1797             :  * duplicated in all such forms and that any documentation,
    1798             :  * advertising materials, and other materials related to such
    1799             :  * distribution and use acknowledge that the software was developed
    1800             :  * by the University of California, Berkeley.  The name of the
    1801             :  * University may not be used to endorse or promote products derived
    1802             :  * from this software without specific prior written permission.
    1803             :  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
    1804             :  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
    1805             :  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
    1806             :  */
    1807             : #endif /* LZW_SUPPORT */
    1808             : 
    1809             : /**
    1810             :  * @def SIZEOF_WORDTYPE
    1811             :  * @brief Size in bytes of WordType, the decoder bit-buffer word.
    1812             :  * @ingroup libtiff_private_lzw
    1813             :  *
    1814             :  * Equals SIZEOF_SIZE_T; selects the GetNextData() variant and how many
    1815             :  * bytes GetNextCodeLZW() loads at once (4 or 8).
    1816             :  */
    1817             : 
    1818             : /**
    1819             :  * @def LZW_COMPAT
    1820             :  * @brief Include decoding of historical reversed-bit-order LZW data.
    1821             :  * @ingroup libtiff_private_lzw
    1822             :  *
    1823             :  * Defined unconditionally. Enables LZWDecodeCompat(), its detection in
    1824             :  * LZWPreDecode() and 1024 extra decode-table entries in CSIZE.
    1825             :  */
    1826             : 
    1827             : /**
    1828             :  * @def MAXCODE(n)
    1829             :  * @brief Compute the inclusive maximum code for a valid bit width.
    1830             :  * @ingroup libtiff_private_lzw
    1831             :  *
    1832             :  * Expands to ((1 << n) - 1); pure, with n evaluated once.
    1833             :  *
    1834             :  * @param[in] n Code width in bits.
    1835             :  */
    1836             : 
    1837             : /**
    1838             :  * @def BITS_MIN
    1839             :  * @brief Initial and post-clear code width: 9 bits.
    1840             :  * @ingroup libtiff_private_lzw
    1841             :  */
    1842             : 
    1843             : /**
    1844             :  * @def BITS_MAX
    1845             :  * @brief Maximum code width allowed by TIFF LZW: 12 bits.
    1846             :  * @ingroup libtiff_private_lzw
    1847             :  */
    1848             : 
    1849             : /**
    1850             :  * @def CODE_CLEAR
    1851             :  * @brief Reserved code 256 that resets the string table.
    1852             :  * @ingroup libtiff_private_lzw
    1853             :  */
    1854             : 
    1855             : /**
    1856             :  * @def CODE_EOI
    1857             :  * @brief Reserved code 257 that ends the strip or tile.
    1858             :  * @ingroup libtiff_private_lzw
    1859             :  */
    1860             : 
    1861             : /**
    1862             :  * @def CODE_FIRST
    1863             :  * @brief First dictionary code assigned to a new string: 258.
    1864             :  * @ingroup libtiff_private_lzw
    1865             :  */
    1866             : 
    1867             : /**
    1868             :  * @def CODE_MAX
    1869             :  * @brief Largest 12-bit code: MAXCODE(BITS_MAX), i.e. 4095.
    1870             :  * @ingroup libtiff_private_lzw
    1871             :  */
    1872             : 
    1873             : /**
    1874             :  * @def HSIZE
    1875             :  * @brief Number of entries in the encoder hash table: 9001.
    1876             :  * @ingroup libtiff_private_lzw
    1877             :  *
    1878             :  * Upstream notes this as 91% occupancy. Indexed with HSHIFT-mixed keys
    1879             :  * and probed with a secondary displacement.
    1880             :  */
    1881             : 
    1882             : /**
    1883             :  * @def HSHIFT
    1884             :  * @brief Left shift applied to the input byte when hashing encoder strings.
    1885             :  * @ingroup libtiff_private_lzw
    1886             :  *
    1887             :  * Value 5 (13 - 8), so (byte << HSHIFT) ^ code stays within 13 bits.
    1888             :  */
    1889             : 
    1890             : /**
    1891             :  * @def CSIZE
    1892             :  * @brief Number of entries allocated for the decoder string table.
    1893             :  * @ingroup libtiff_private_lzw
    1894             :  *
    1895             :  * MAXCODE(BITS_MAX) + 1024 with LZW_COMPAT (headroom for old files),
    1896             :  * otherwise MAXCODE(BITS_MAX) + 1.
    1897             :  */
    1898             : 
    1899             : /**
    1900             :  * @def lzw_nbits
    1901             :  * @brief Member alias for base.nbits, the current code width.
    1902             :  * @ingroup libtiff_private_lzw
    1903             :  */
    1904             : 
    1905             : /**
    1906             :  * @def lzw_maxcode
    1907             :  * @brief Member alias for base.maxcode, the largest code at this width.
    1908             :  * @ingroup libtiff_private_lzw
    1909             :  */
    1910             : 
    1911             : /**
    1912             :  * @def lzw_free_ent
    1913             :  * @brief Member alias for base.free_ent, the next free dictionary code.
    1914             :  * @ingroup libtiff_private_lzw
    1915             :  */
    1916             : 
    1917             : /**
    1918             :  * @def lzw_nextdata
    1919             :  * @brief Member alias for base.nextdata, the buffered code bits.
    1920             :  * @ingroup libtiff_private_lzw
    1921             :  */
    1922             : 
    1923             : /**
    1924             :  * @def lzw_nextbits
    1925             :  * @brief Member alias for base.nextbits, the number of buffered bits.
    1926             :  * @ingroup libtiff_private_lzw
    1927             :  */
    1928             : 
    1929             : /**
    1930             :  * @def CHECK_GAP
    1931             :  * @brief Encoder input bytes between compression-ratio checks: 10000.
    1932             :  * @ingroup libtiff_private_lzw
    1933             :  *
    1934             :  * If the ratio has not improved since the previous check, the encoder emits
    1935             :  * CODE_CLEAR and resets the table.
    1936             :  */
    1937             : 
    1938             : /**
    1939             :  * @def LZWState(tif)
    1940             :  * @brief Cast tif->tif_data to the shared LZWBaseState prefix.
    1941             :  * @ingroup libtiff_private_lzw
    1942             :  *
    1943             :  * Pure cast; tif is evaluated once. Requires the LZW codec to be
    1944             :  * initialised (tif_data non-NULL).
    1945             :  *
    1946             :  * @param[in] tif Handle whose codec state is returned.
    1947             :  */
    1948             : 
    1949             : /**
    1950             :  * @def LZWDecoderState(tif)
    1951             :  * @brief Cast tif->tif_data to the full LZWCodecState for decoding.
    1952             :  * @ingroup libtiff_private_lzw
    1953             :  *
    1954             :  * Pure cast via LZWState(); tif is evaluated once. Requires the LZW codec to
    1955             :  * be initialised.
    1956             :  *
    1957             :  * @param[in] tif Handle whose codec state is returned.
    1958             :  */
    1959             : 
    1960             : /**
    1961             :  * @def LZWEncoderState(tif)
    1962             :  * @brief Cast tif->tif_data to the full LZWCodecState for encoding.
    1963             :  * @ingroup libtiff_private_lzw
    1964             :  *
    1965             :  * Pure cast via LZWState(); tif is evaluated once. Requires the LZW codec to
    1966             :  * be initialised.
    1967             :  *
    1968             :  * @param[in] tif Handle whose codec state is returned.
    1969             :  */
    1970             : 
    1971             : /**
    1972             :  * @def GetNextData(nextdata, bp)
    1973             :  * @brief Load SIZEOF_WORDTYPE bytes at bp into nextdata, first byte most
    1974             :  * significant.
    1975             :  * @ingroup libtiff_private_lzw
    1976             :  *
    1977             :  * Statement macro used by GetNextCodeLZW() to refill the bit cache with a
    1978             :  * whole word. Assigns nextdata and reads SIZEOF_WORDTYPE bytes from bp
    1979             :  * without a bounds check; does not advance bp. The portable variants
    1980             :  * evaluate bp once per byte, and the memcpy/bswap variants expand to two
    1981             :  * statements, so bp must be free of side effects and the macro must be used
    1982             :  * inside braces. The _M_X64/_M_X86 variants dereference bp through a
    1983             :  * wider pointer type, i.e. an unaligned load.
    1984             :  *
    1985             :  * @param[in,out] nextdata Unsigned WordType lvalue that receives the word.
    1986             :  * @param[in] bp Byte pointer to at least SIZEOF_WORDTYPE readable bytes.
    1987             :  */
    1988             : 
    1989             : /**
    1990             :  * @def GetNextCodeLZW()
    1991             :  * @brief Extract the next nbits-wide MSB-first code from the decoder bit
    1992             :  * cache into code, refilling from bp as needed.
    1993             :  * @ingroup libtiff_private_lzw
    1994             :  *
    1995             :  * Operates entirely on locals of LZWDecode(): reads nbits and nbitsmask,
    1996             :  * reads and updates nextbits, nextdata, bp and dec_bitsleft, and assigns
    1997             :  * code. When the cache runs short it loads a whole word with GetNextData()
    1998             :  * if dec_bitsleft holds at least one word, otherwise one or two single bytes.
    1999             :  * dec_bitsleft is reduced by the bits loaded, not by nbits.
    2000             :  *
    2001             :  * Hidden control flow: if fewer than 8 bits remain in dec_bitsleft when a
    2002             :  * byte is needed, it executes `goto no_eoi`, so the enclosing function must
    2003             :  * define a no_eoi label (LZWDecode() zeroes the output, sets read_error,
    2004             :  * reports a missing EOI with TIFFErrorExtR() and returns 0 there). Its
    2005             :  * internal `break` only leaves the macro's own do/while.
    2006             :  */
    2007             : 
    2008             : /**
    2009             :  * @def NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)
    2010             :  * @brief Fetch the next compatibility-mode code with _get, or yield CODE_EOI
    2011             :  * with a warning when fewer than nbits input bits remain.
    2012             :  * @ingroup libtiff_private_lzw
    2013             :  *
    2014             :  * Defined only with LZW_COMPAT and used by LZWDecodeCompat(). Also reads the
    2015             :  * caller locals nbits and module. If dec_bitsleft < nbits it emits
    2016             :  * TIFFWarningExtR() ("not terminated with EOI code") naming
    2017             :  * _tif->tif_dir.td_curstrip, sets _code to CODE_EOI and consumes no input;
    2018             :  * this is not treated as an error. Otherwise it expands _get(_sp, _bp, _code)
    2019             :  * and subtracts nbits from dec_bitsleft. _tif is evaluated twice on the
    2020             :  * warning path. No hidden return or goto.
    2021             :  *
    2022             :  * @param[in] _tif TIFF handle used for the warning.
    2023             :  * @param[in] _sp Codec state passed through to _get.
    2024             :  * @param[in,out] _bp Input byte-pointer lvalue, advanced by _get.
    2025             :  * @param[in,out] _code Lvalue that receives the code.
    2026             :  * @param[in] _get Code-fetch macro name, e.g. GetNextCodeCompat.
    2027             :  * @param[in,out] dec_bitsleft Lvalue holding the remaining input bit count.
    2028             :  */
    2029             : 
    2030             : /**
    2031             :  * @def GetNextCodeCompat(sp, bp, code)
    2032             :  * @brief Extract the next nbits-wide LSB-first code for old reversed-order
    2033             :  * LZW data.
    2034             :  * @ingroup libtiff_private_lzw
    2035             :  *
    2036             :  * ORs one byte, or two if nextbits is still below nbits, from *bp into the
    2037             :  * caller locals nextdata/nextbits, advancing bp each time; then assigns
    2038             :  * code = nextdata & nbitsmask and shifts nbits out of nextdata. Reads the
    2039             :  * caller locals nbits and nbitsmask. Performs no bounds check: NextCode()
    2040             :  * ensures dec_bitsleft >= nbits first. The sp operand is not used.
    2041             :  *
    2042             :  * @param[in] sp Unused; present for the NextCode() _get signature.
    2043             :  * @param[in,out] bp Input byte-pointer lvalue, advanced by 1 or 2.
    2044             :  * @param[in,out] code Lvalue that receives the code.
    2045             :  */
    2046             : 
    2047             : /**
    2048             :  * @def CALCRATIO(sp, rat)
    2049             :  * @brief Compute the encoder compression ratio incount/outcount as a 24.8
    2050             :  * fixed-point value into rat.
    2051             :  * @ingroup libtiff_private_lzw
    2052             :  *
    2053             :  * Reads the LZWEncode() locals incount (input bytes) and outcount (output
    2054             :  * bits); the sp operand is not used. If incount > 0x007fffff it divides
    2055             :  * incount by outcount >> 8 to avoid overflowing the shift, giving 0x7fffffff
    2056             :  * when that is 0; otherwise it computes (incount << 8) / outcount, which
    2057             :  * requires outcount != 0. rat is assigned up to twice. No hidden control
    2058             :  * flow or diagnostics.
    2059             :  *
    2060             :  * @param[in] sp Unused.
    2061             :  * @param[in,out] rat Lvalue that receives the ratio.
    2062             :  */
    2063             : 
    2064             : /**
    2065             :  * @def PutNextCode(op, c)
    2066             :  * @brief Append the nbits-wide code c MSB-first to the encoder output at op.
    2067             :  * @ingroup libtiff_private_lzw
    2068             :  *
    2069             :  * Shifts c into the LZWEncode()/LZWPostEncode() locals nextdata and nextbits,
    2070             :  * stores one or two complete bytes at op (advancing it each time) and adds
    2071             :  * nbits to outcount. Writes without a bounds check: callers compare op with
    2072             :  * enc_rawlimit (which reserves 4 bytes, room for two codes) and flush first.
    2073             :  * c is evaluated once; op is read and incremented up to twice. No hidden
    2074             :  * control flow or diagnostics.
    2075             :  *
    2076             :  * @param[in,out] op Output byte-pointer lvalue, advanced by 1 or 2.
    2077             :  * @param[in] c Code value, below 1 << nbits.
    2078             :  */

Generated by: LCOV version 1.14