LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_lzw.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 485 571 84.9 %
Date: 2024-05-04 12:52:34 Functions: 12 12 100.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             : #include "tiffiop.h"
      27             : #ifdef LZW_SUPPORT
      28             : /*
      29             :  * TIFF Library.
      30             :  * Rev 5.0 Lempel-Ziv & Welch Compression Support
      31             :  *
      32             :  * This code is derived from the compress program whose code is
      33             :  * derived from software contributed to Berkeley by James A. Woods,
      34             :  * derived from original work by Spencer Thomas and Joseph Orost.
      35             :  *
      36             :  * The original Berkeley copyright notice appears below in its entirety.
      37             :  */
      38             : #include "tif_predict.h"
      39             : 
      40             : #include <stdbool.h>
      41             : #include <stdio.h>
      42             : #include <stdlib.h>
      43             : 
      44             : /* Select the plausible largest natural integer type for the architecture */
      45             : #define SIZEOF_WORDTYPE SIZEOF_SIZE_T
      46             : typedef size_t WordType;
      47             : 
      48             : /*
      49             :  * NB: The 5.0 spec describes a different algorithm than Aldus
      50             :  *     implements.  Specifically, Aldus does code length transitions
      51             :  *     one code earlier than should be done (for real LZW).
      52             :  *     Earlier versions of this library implemented the correct
      53             :  *     LZW algorithm, but emitted codes in a bit order opposite
      54             :  *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
      55             :  *     we interpret MSB-LSB ordered codes to be images written w/
      56             :  *     old versions of this library, but otherwise adhere to the
      57             :  *     Aldus "off by one" algorithm.
      58             :  *
      59             :  * Future revisions to the TIFF spec are expected to "clarify this issue".
      60             :  */
      61             : #define LZW_COMPAT /* include backwards compatibility code */
      62             : 
      63             : #define MAXCODE(n) ((1L << (n)) - 1)
      64             : /*
      65             :  * The TIFF spec specifies that encoded bit
      66             :  * strings range from 9 to 12 bits.
      67             :  */
      68             : #define BITS_MIN 9  /* start with 9 bits */
      69             : #define BITS_MAX 12 /* max of 12 bit strings */
      70             : /* predefined codes */
      71             : #define CODE_CLEAR 256 /* code to clear string table */
      72             : #define CODE_EOI 257   /* end-of-information code */
      73             : #define CODE_FIRST 258 /* first free code entry */
      74             : #define CODE_MAX MAXCODE(BITS_MAX)
      75             : #define HSIZE 9001L /* 91% occupancy */
      76             : #define HSHIFT (13 - 8)
      77             : #ifdef LZW_COMPAT
      78             : /* NB: +1024 is for compatibility with old files */
      79             : #define CSIZE (MAXCODE(BITS_MAX) + 1024L)
      80             : #else
      81             : #define CSIZE (MAXCODE(BITS_MAX) + 1L)
      82             : #endif
      83             : 
      84             : /*
      85             :  * State block for each open TIFF file using LZW
      86             :  * compression/decompression.  Note that the predictor
      87             :  * state block must be first in this data structure.
      88             :  */
      89             : typedef struct
      90             : {
      91             :     TIFFPredictorState predict; /* predictor super class */
      92             : 
      93             :     unsigned short nbits;    /* # of bits/code */
      94             :     unsigned short maxcode;  /* maximum code for lzw_nbits */
      95             :     unsigned short free_ent; /* next free entry in hash table */
      96             :     WordType nextdata;       /* next bits of i/o */
      97             :     long nextbits;           /* # of valid bits in lzw_nextdata */
      98             : 
      99             :     int rw_mode; /* preserve rw_mode from init */
     100             : } LZWBaseState;
     101             : 
     102             : #define lzw_nbits base.nbits
     103             : #define lzw_maxcode base.maxcode
     104             : #define lzw_free_ent base.free_ent
     105             : #define lzw_nextdata base.nextdata
     106             : #define lzw_nextbits base.nextbits
     107             : 
     108             : /*
     109             :  * Encoding-specific state.
     110             :  */
     111             : typedef uint16_t hcode_t; /* codes fit in 16 bits */
     112             : typedef struct
     113             : {
     114             :     long hash;
     115             :     hcode_t code;
     116             : } hash_t;
     117             : 
     118             : /*
     119             :  * Decoding-specific state.
     120             :  */
     121             : typedef struct code_ent
     122             : {
     123             :     struct code_ent *next;
     124             :     unsigned short length; /* string len, including this token */
     125             :     /* firstchar should be placed immediately before value in this structure */
     126             :     unsigned char firstchar; /* first token of string */
     127             :     unsigned char value;     /* data value */
     128             :     bool repeated;
     129             : } code_t;
     130             : 
     131             : typedef int (*decodeFunc)(TIFF *, uint8_t *, tmsize_t, uint16_t);
     132             : 
     133             : typedef struct
     134             : {
     135             :     LZWBaseState base;
     136             : 
     137             :     /* Decoding specific data */
     138             :     long dec_nbitsmask;     /* lzw_nbits 1 bits, right adjusted */
     139             :     tmsize_t dec_restart;   /* restart count */
     140             :     uint64_t dec_bitsleft;  /* available bits in raw data */
     141             :     tmsize_t old_tif_rawcc; /* value of tif_rawcc at the end of the previous
     142             :                                TIFLZWDecode() call */
     143             :     decodeFunc dec_decode;  /* regular or backwards compatible */
     144             :     code_t *dec_codep;      /* current recognized code */
     145             :     code_t *dec_oldcodep;   /* previously recognized code */
     146             :     code_t *dec_free_entp;  /* next free entry */
     147             :     code_t *dec_maxcodep;   /* max available entry */
     148             :     code_t *dec_codetab;    /* kept separate for small machines */
     149             :     int read_error; /* whether a read error has occurred, and which should cause
     150             :                        further reads in the same strip/tile to be aborted */
     151             : 
     152             :     /* Encoding specific data */
     153             :     int enc_oldcode;         /* last code encountered */
     154             :     tmsize_t enc_checkpoint; /* point at which to clear table */
     155             : #define CHECK_GAP 10000      /* enc_ratio check interval */
     156             :     tmsize_t enc_ratio;      /* current compression ratio */
     157             :     tmsize_t enc_incount;    /* (input) data bytes encoded */
     158             :     tmsize_t enc_outcount;   /* encoded (output) bytes */
     159             :     uint8_t *enc_rawlimit;   /* bound on tif_rawdata buffer */
     160             :     hash_t *enc_hashtab;     /* kept separate for small machines */
     161             : } LZWCodecState;
     162             : 
     163             : #define LZWState(tif) ((LZWBaseState *)(tif)->tif_data)
     164             : #define LZWDecoderState(tif) ((LZWCodecState *)LZWState(tif))
     165             : #define LZWEncoderState(tif) ((LZWCodecState *)LZWState(tif))
     166             : 
     167             : static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
     168             : #ifdef LZW_COMPAT
     169             : static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
     170             : #endif
     171             : static void cl_hash(LZWCodecState *);
     172             : 
     173             : /*
     174             :  * LZW Decoder.
     175             :  */
     176             : 
     177        4073 : static int LZWFixupTags(TIFF *tif)
     178             : {
     179             :     (void)tif;
     180        4073 :     return (1);
     181             : }
     182             : 
     183        2387 : static int LZWSetupDecode(TIFF *tif)
     184             : {
     185             :     static const char module[] = "LZWSetupDecode";
     186        2387 :     LZWCodecState *sp = LZWDecoderState(tif);
     187             :     int code;
     188             : 
     189        2387 :     if (sp == NULL)
     190             :     {
     191             :         /*
     192             :          * Allocate state block so tag methods have storage to record
     193             :          * values.
     194             :          */
     195           0 :         tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
     196           0 :         if (tif->tif_data == NULL)
     197             :         {
     198           0 :             TIFFErrorExtR(tif, module, "No space for LZW state block");
     199           0 :             return (0);
     200             :         }
     201             : 
     202           0 :         sp = LZWDecoderState(tif);
     203           0 :         sp->dec_codetab = NULL;
     204           0 :         sp->dec_decode = NULL;
     205             : 
     206             :         /*
     207             :          * Setup predictor setup.
     208             :          */
     209           0 :         (void)TIFFPredictorInit(tif);
     210             :     }
     211             : 
     212        2388 :     if (sp->dec_codetab == NULL)
     213             :     {
     214        2384 :         sp->dec_codetab = (code_t *)_TIFFmallocExt(tif, CSIZE * sizeof(code_t));
     215        2386 :         if (sp->dec_codetab == NULL)
     216             :         {
     217           2 :             TIFFErrorExtR(tif, module, "No space for LZW code table");
     218           0 :             return (0);
     219             :         }
     220             :         /*
     221             :          * Pre-load the table.
     222             :          */
     223        2384 :         code = 255;
     224             :         do
     225             :         {
     226      606689 :             sp->dec_codetab[code].firstchar = (unsigned char)code;
     227      606689 :             sp->dec_codetab[code].value = (unsigned char)code;
     228      606689 :             sp->dec_codetab[code].repeated = true;
     229      606689 :             sp->dec_codetab[code].length = 1;
     230      606689 :             sp->dec_codetab[code].next = NULL;
     231      606689 :         } while (code--);
     232             :         /*
     233             :          * Zero-out the unused entries  */
     234             :         /* Silence false positive */
     235             :         /* coverity[overrun-buffer-arg] */
     236        2384 :         memset(&sp->dec_codetab[CODE_CLEAR], 0,
     237             :                (CODE_FIRST - CODE_CLEAR) * sizeof(code_t));
     238             :     }
     239        2388 :     return (1);
     240             : }
     241             : 
     242             : /*
     243             :  * Setup state for decoding a strip.
     244             :  */
     245        4746 : static int LZWPreDecode(TIFF *tif, uint16_t s)
     246             : {
     247             :     static const char module[] = "LZWPreDecode";
     248        4746 :     LZWCodecState *sp = LZWDecoderState(tif);
     249             : 
     250             :     (void)s;
     251        4746 :     assert(sp != NULL);
     252        4746 :     if (sp->dec_codetab == NULL)
     253             :     {
     254          33 :         tif->tif_setupdecode(tif);
     255          33 :         if (sp->dec_codetab == NULL)
     256           0 :             return (0);
     257             :     }
     258             : 
     259             :     /*
     260             :      * Check for old bit-reversed codes.
     261             :      */
     262        4746 :     if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 &&
     263          77 :         (tif->tif_rawdata[1] & 0x1))
     264             :     {
     265             : #ifdef LZW_COMPAT
     266          77 :         if (!sp->dec_decode)
     267             :         {
     268           1 :             TIFFWarningExtR(tif, module, "Old-style LZW codes, convert file");
     269             :             /*
     270             :              * Override default decoding methods with
     271             :              * ones that deal with the old coding.
     272             :              * Otherwise the predictor versions set
     273             :              * above will call the compatibility routines
     274             :              * through the dec_decode method.
     275             :              */
     276           1 :             tif->tif_decoderow = LZWDecodeCompat;
     277           1 :             tif->tif_decodestrip = LZWDecodeCompat;
     278           1 :             tif->tif_decodetile = LZWDecodeCompat;
     279             :             /*
     280             :              * If doing horizontal differencing, must
     281             :              * re-setup the predictor logic since we
     282             :              * switched the basic decoder methods...
     283             :              */
     284           1 :             (*tif->tif_setupdecode)(tif);
     285           1 :             sp->dec_decode = LZWDecodeCompat;
     286             :         }
     287          77 :         sp->lzw_maxcode = MAXCODE(BITS_MIN);
     288             : #else  /* !LZW_COMPAT */
     289             :         if (!sp->dec_decode)
     290             :         {
     291             :             TIFFErrorExtR(tif, module, "Old-style LZW codes not supported");
     292             :             sp->dec_decode = LZWDecode;
     293             :         }
     294             :         return (0);
     295             : #endif /* !LZW_COMPAT */
     296             :     }
     297             :     else
     298             :     {
     299        4669 :         sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1;
     300        4669 :         sp->dec_decode = LZWDecode;
     301             :     }
     302        4746 :     sp->lzw_nbits = BITS_MIN;
     303        4746 :     sp->lzw_nextbits = 0;
     304        4746 :     sp->lzw_nextdata = 0;
     305             : 
     306        4746 :     sp->dec_restart = 0;
     307        4746 :     sp->dec_nbitsmask = MAXCODE(BITS_MIN);
     308        4746 :     sp->dec_bitsleft = 0;
     309        4746 :     sp->old_tif_rawcc = 0;
     310        4746 :     sp->dec_free_entp = sp->dec_codetab - 1; // + CODE_FIRST;
     311             :     /*
     312             :      * Zero entries that are not yet filled in.  We do
     313             :      * this to guard against bogus input data that causes
     314             :      * us to index into undefined entries.  If you can
     315             :      * come up with a way to safely bounds-check input codes
     316             :      * while decoding then you can remove this operation.
     317             :      */
     318        4746 :     sp->dec_oldcodep = &sp->dec_codetab[0];
     319        4746 :     sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1];
     320        4746 :     sp->read_error = 0;
     321        4746 :     return (1);
     322             : }
     323             : 
     324             : /*
     325             :  * Decode a "hunk of data".
     326             :  */
     327             : 
     328             : /* Get the next 32 or 64-bit from the input data */
     329             : #ifdef WORDS_BIGENDIAN
     330             : #define GetNextData(nextdata, bp) memcpy(&nextdata, bp, sizeof(nextdata))
     331             : #elif SIZEOF_WORDTYPE == 8
     332             : #if defined(_M_X64)
     333             : #define GetNextData(nextdata, bp) nextdata = _byteswap_uint64(*(uint64_t *)(bp))
     334             : #elif defined(__GNUC__)
     335             : #define GetNextData(nextdata, bp)                                              \
     336             :     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
     337             :     nextdata = __builtin_bswap64(nextdata)
     338             : #else
     339             : #define GetNextData(nextdata, bp)                                              \
     340             :     nextdata = (((uint64_t)bp[0]) << 56) | (((uint64_t)bp[1]) << 48) |         \
     341             :                (((uint64_t)bp[2]) << 40) | (((uint64_t)bp[3]) << 32) |         \
     342             :                (((uint64_t)bp[4]) << 24) | (((uint64_t)bp[5]) << 16) |         \
     343             :                (((uint64_t)bp[6]) << 8) | (((uint64_t)bp[7]))
     344             : #endif
     345             : #elif SIZEOF_WORDTYPE == 4
     346             : #if defined(_M_X86)
     347             : #define GetNextData(nextdata, bp)                                              \
     348             :     nextdata = _byteswap_ulong(*(unsigned long *)(bp))
     349             : #elif defined(__GNUC__)
     350             : #define GetNextData(nextdata, bp)                                              \
     351             :     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
     352             :     nextdata = __builtin_bswap32(nextdata)
     353             : #else
     354             : #define GetNextData(nextdata, bp)                                              \
     355             :     nextdata = (((uint32_t)bp[0]) << 24) | (((uint32_t)bp[1]) << 16) |         \
     356             :                (((uint32_t)bp[2]) << 8) | (((uint32_t)bp[3]))
     357             : #endif
     358             : #else
     359             : #error "Unhandled SIZEOF_WORDTYPE"
     360             : #endif
     361             : 
     362             : #define GetNextCodeLZW()                                                       \
     363             :     do                                                                         \
     364             :     {                                                                          \
     365             :         nextbits -= nbits;                                                     \
     366             :         if (nextbits < 0)                                                      \
     367             :         {                                                                      \
     368             :             if (dec_bitsleft >= 8 * SIZEOF_WORDTYPE)                           \
     369             :             {                                                                  \
     370             :                 unsigned codetmp = (unsigned)(nextdata << (-nextbits));        \
     371             :                 GetNextData(nextdata, bp);                                     \
     372             :                 bp += SIZEOF_WORDTYPE;                                         \
     373             :                 nextbits += 8 * SIZEOF_WORDTYPE;                               \
     374             :                 dec_bitsleft -= 8 * SIZEOF_WORDTYPE;                           \
     375             :                 code = (WordType)((codetmp | (nextdata >> nextbits)) &         \
     376             :                                   nbitsmask);                                  \
     377             :                 break;                                                         \
     378             :             }                                                                  \
     379             :             else                                                               \
     380             :             {                                                                  \
     381             :                 if (dec_bitsleft < 8)                                          \
     382             :                 {                                                              \
     383             :                     goto no_eoi;                                               \
     384             :                 }                                                              \
     385             :                 nextdata = (nextdata << 8) | *(bp)++;                          \
     386             :                 nextbits += 8;                                                 \
     387             :                 dec_bitsleft -= 8;                                             \
     388             :                 if (nextbits < 0)                                              \
     389             :                 {                                                              \
     390             :                     if (dec_bitsleft < 8)                                      \
     391             :                     {                                                          \
     392             :                         goto no_eoi;                                           \
     393             :                     }                                                          \
     394             :                     nextdata = (nextdata << 8) | *(bp)++;                      \
     395             :                     nextbits += 8;                                             \
     396             :                     dec_bitsleft -= 8;                                         \
     397             :                 }                                                              \
     398             :             }                                                                  \
     399             :         }                                                                      \
     400             :         code = (WordType)((nextdata >> nextbits) & nbitsmask);                 \
     401             :     } while (0)
     402             : 
     403      112882 : static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
     404             : {
     405             :     static const char module[] = "LZWDecode";
     406      112882 :     LZWCodecState *sp = LZWDecoderState(tif);
     407      112882 :     uint8_t *op = (uint8_t *)op0;
     408      112882 :     tmsize_t occ = occ0;
     409             :     uint8_t *bp;
     410             :     long nbits, nextbits, nbitsmask;
     411             :     WordType nextdata;
     412             :     code_t *free_entp, *maxcodep, *oldcodep;
     413             : 
     414             :     (void)s;
     415      112882 :     assert(sp != NULL);
     416      112882 :     assert(sp->dec_codetab != NULL);
     417             : 
     418      112882 :     if (sp->read_error)
     419             :     {
     420           0 :         TIFFErrorExtR(tif, module,
     421             :                       "LZWDecode: Scanline %" PRIu32 " cannot be read due to "
     422             :                       "previous error",
     423             :                       tif->tif_row);
     424           0 :         return 0;
     425             :     }
     426             : 
     427             :     /*
     428             :      * Restart interrupted output operation.
     429             :      */
     430      112882 :     if (sp->dec_restart)
     431             :     {
     432             :         tmsize_t residue;
     433             : 
     434      104113 :         code_t *codep = sp->dec_codep;
     435      104113 :         residue = codep->length - sp->dec_restart;
     436      104113 :         if (residue > occ)
     437             :         {
     438             :             /*
     439             :              * Residue from previous decode is sufficient
     440             :              * to satisfy decode request.  Skip to the
     441             :              * start of the decoded string, place decoded
     442             :              * values in the output buffer, and return.
     443             :              */
     444       99868 :             sp->dec_restart += occ;
     445             :             do
     446             :             {
     447     3160750 :                 codep = codep->next;
     448     3160750 :             } while (--residue > occ && codep);
     449       99868 :             if (codep)
     450             :             {
     451       99868 :                 uint8_t *tp = op + occ;
     452             :                 do
     453             :                 {
     454      176900 :                     *--tp = codep->value;
     455      176900 :                     codep = codep->next;
     456      176900 :                 } while (--occ && codep);
     457             :             }
     458       99868 :             return (1);
     459             :         }
     460             :         /*
     461             :          * Residue satisfies only part of the decode request.
     462             :          */
     463        4245 :         op += residue;
     464        4245 :         occ -= residue;
     465        4245 :         uint8_t *tp = op;
     466             :         do
     467             :         {
     468        6912 :             *--tp = codep->value;
     469        6912 :             codep = codep->next;
     470        6912 :         } while (--residue && codep);
     471        4245 :         sp->dec_restart = 0;
     472             :     }
     473             : 
     474       13014 :     bp = (uint8_t *)tif->tif_rawcp;
     475       13014 :     sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
     476       13014 :     uint64_t dec_bitsleft = sp->dec_bitsleft;
     477       13014 :     nbits = sp->lzw_nbits;
     478       13014 :     nextdata = sp->lzw_nextdata;
     479       13014 :     nextbits = sp->lzw_nextbits;
     480       13014 :     nbitsmask = sp->dec_nbitsmask;
     481       13014 :     oldcodep = sp->dec_oldcodep;
     482       13014 :     free_entp = sp->dec_free_entp;
     483       13014 :     maxcodep = sp->dec_maxcodep;
     484       13014 :     code_t *const dec_codetab = sp->dec_codetab;
     485             :     code_t *codep;
     486             : 
     487       13014 :     if (occ == 0)
     488             :     {
     489        2276 :         goto after_loop;
     490             :     }
     491             : 
     492       10738 : begin:
     493             : {
     494             :     WordType code;
     495    23953900 :     GetNextCodeLZW();
     496    23953900 :     codep = dec_codetab + code;
     497    23953900 :     if (code >= CODE_FIRST)
     498    20131400 :         goto code_above_or_equal_to_258;
     499     3822580 :     if (code < 256)
     500     3813180 :         goto code_below_256;
     501        9400 :     if (code == CODE_EOI)
     502           0 :         goto after_loop;
     503        9400 :     goto code_clear;
     504             : 
     505     3813180 : code_below_256:
     506             : {
     507     3813180 :     if (codep > free_entp)
     508           0 :         goto error_code;
     509     3813180 :     free_entp->next = oldcodep;
     510     3813180 :     free_entp->firstchar = oldcodep->firstchar;
     511     3813180 :     free_entp->length = oldcodep->length + 1;
     512     3813180 :     free_entp->value = (uint8_t)code;
     513     3813180 :     free_entp->repeated =
     514     3813180 :         (bool)(oldcodep->repeated & (oldcodep->value == code));
     515     3813180 :     if (++free_entp > maxcodep)
     516             :     {
     517        3750 :         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
     518           0 :             nbits = BITS_MAX;
     519        3750 :         nbitsmask = MAXCODE(nbits);
     520        3750 :         maxcodep = dec_codetab + nbitsmask - 1;
     521        3750 :         if (free_entp >= &dec_codetab[CSIZE])
     522             :         {
     523             :             /* At that point, the next valid states are either EOI or a */
     524             :             /* CODE_CLEAR. If a regular code is read, at the next */
     525             :             /* attempt at registering a new entry, we will error out */
     526             :             /* due to setting free_entp before any valid code */
     527           0 :             free_entp = dec_codetab - 1;
     528             :         }
     529             :     }
     530     3813180 :     oldcodep = codep;
     531     3813180 :     *op++ = (uint8_t)code;
     532     3813180 :     occ--;
     533     3813180 :     if (occ == 0)
     534        2571 :         goto after_loop;
     535     3810610 :     goto begin;
     536             : }
     537             : 
     538    20131400 : code_above_or_equal_to_258:
     539             : {
     540             :     /*
     541             :      * Add the new entry to the code table.
     542             :      */
     543             : 
     544    20131400 :     if (codep >= free_entp)
     545             :     {
     546     3259280 :         if (codep != free_entp)
     547           0 :             goto error_code;
     548     3259280 :         free_entp->value = oldcodep->firstchar;
     549             :     }
     550             :     else
     551             :     {
     552    16872100 :         free_entp->value = codep->firstchar;
     553             :     }
     554    20131400 :     free_entp->repeated =
     555    20131400 :         (bool)(oldcodep->repeated & (oldcodep->value == free_entp->value));
     556    20131400 :     free_entp->next = oldcodep;
     557             : 
     558    20131400 :     free_entp->firstchar = oldcodep->firstchar;
     559    20131400 :     free_entp->length = oldcodep->length + 1;
     560    20131400 :     if (++free_entp > maxcodep)
     561             :     {
     562       16312 :         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
     563           0 :             nbits = BITS_MAX;
     564       16312 :         nbitsmask = MAXCODE(nbits);
     565       16312 :         maxcodep = dec_codetab + nbitsmask - 1;
     566       16312 :         if (free_entp >= &dec_codetab[CSIZE])
     567             :         {
     568             :             /* At that point, the next valid states are either EOI or a */
     569             :             /* CODE_CLEAR. If a regular code is read, at the next */
     570             :             /* attempt at registering a new entry, we will error out */
     571             :             /* due to setting free_entp before any valid code */
     572           0 :             free_entp = dec_codetab - 1;
     573             :         }
     574             :     }
     575    20131400 :     oldcodep = codep;
     576             : 
     577             :     /*
     578             :      * Code maps to a string, copy string
     579             :      * value to output (written in reverse).
     580             :      */
     581             :     /* tiny bit faster on x86_64 to store in unsigned short than int */
     582    20131400 :     unsigned short len = codep->length;
     583             : 
     584    20131400 :     if (len < 3) /* equivalent to len == 2 given all other conditions */
     585             :     {
     586     3045640 :         if (occ <= 2)
     587             :         {
     588         527 :             if (occ == 2)
     589             :             {
     590         480 :                 memcpy(op, &(codep->firstchar), 2);
     591         480 :                 op += 2;
     592         480 :                 occ -= 2;
     593         480 :                 goto after_loop;
     594             :             }
     595          47 :             goto too_short_buffer;
     596             :         }
     597             : 
     598     3045120 :         memcpy(op, &(codep->firstchar), 2);
     599     3045120 :         op += 2;
     600     3045120 :         occ -= 2;
     601     3045120 :         goto begin; /* we can save the comparison occ > 0 */
     602             :     }
     603             : 
     604    17085700 :     if (len == 3)
     605             :     {
     606     2398530 :         if (occ <= 3)
     607             :         {
     608         290 :             if (occ == 3)
     609             :             {
     610         229 :                 op[0] = codep->firstchar;
     611         229 :                 op[1] = codep->next->value;
     612         229 :                 op[2] = codep->value;
     613         229 :                 op += 3;
     614         229 :                 occ -= 3;
     615         229 :                 goto after_loop;
     616             :             }
     617          61 :             goto too_short_buffer;
     618             :         }
     619             : 
     620     2398240 :         op[0] = codep->firstchar;
     621     2398240 :         op[1] = codep->next->value;
     622     2398240 :         op[2] = codep->value;
     623     2398240 :         op += 3;
     624     2398240 :         occ -= 3;
     625     2398240 :         goto begin; /* we can save the comparison occ > 0 */
     626             :     }
     627             : 
     628    14687200 :     if (len > occ)
     629             :     {
     630        4315 :         goto too_short_buffer;
     631             :     }
     632             : 
     633    14682900 :     if (codep->repeated)
     634             :     {
     635      560390 :         memset(op, codep->value, len);
     636      560390 :         op += len;
     637      560390 :         occ -= len;
     638      560390 :         if (occ == 0)
     639        2710 :             goto after_loop;
     640      557680 :         goto begin;
     641             :     }
     642             : 
     643    14122500 :     uint8_t *tp = op + len;
     644             : 
     645    14122500 :     assert(len >= 4);
     646             : 
     647    14122500 :     *--tp = codep->value;
     648    14122500 :     codep = codep->next;
     649    14122500 :     *--tp = codep->value;
     650    14122500 :     codep = codep->next;
     651    14122500 :     *--tp = codep->value;
     652    14122500 :     codep = codep->next;
     653    14122500 :     *--tp = codep->value;
     654    14122500 :     if (tp > op)
     655             :     {
     656             :         do
     657             :         {
     658   110959000 :             codep = codep->next;
     659   110959000 :             *--tp = codep->value;
     660   110959000 :         } while (tp > op);
     661             :     }
     662             : 
     663    14122500 :     assert(occ >= len);
     664    14122500 :     op += len;
     665    14122500 :     occ -= len;
     666    14122500 :     if (occ == 0)
     667         296 :         goto after_loop;
     668    14122200 :     goto begin;
     669             : }
     670             : 
     671        9400 : code_clear:
     672             : {
     673        9400 :     free_entp = dec_codetab + CODE_FIRST;
     674        9400 :     nbits = BITS_MIN;
     675        9400 :     nbitsmask = MAXCODE(BITS_MIN);
     676        9400 :     maxcodep = dec_codetab + nbitsmask - 1;
     677             :     do
     678             :     {
     679       10196 :         GetNextCodeLZW();
     680       10196 :     } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
     681        9400 :     if (code == CODE_EOI)
     682           0 :         goto after_loop;
     683        9400 :     if (code > CODE_EOI)
     684             :     {
     685           0 :         goto error_code;
     686             :     }
     687        9400 :     *op++ = (uint8_t)code;
     688        9400 :     occ--;
     689        9400 :     oldcodep = dec_codetab + code;
     690        9400 :     if (occ == 0)
     691          29 :         goto after_loop;
     692        9371 :     goto begin;
     693             : }
     694             : }
     695             : 
     696        4423 : too_short_buffer:
     697             : {
     698             :     /*
     699             :      * String is too long for decode buffer,
     700             :      * locate portion that will fit, copy to
     701             :      * the decode buffer, and setup restart
     702             :      * logic for the next decoding call.
     703             :      */
     704        4423 :     sp->dec_codep = codep;
     705             :     do
     706             :     {
     707      195355 :         codep = codep->next;
     708      195355 :     } while (codep->length > occ);
     709             : 
     710        4423 :     sp->dec_restart = occ;
     711        4423 :     uint8_t *tp = op + occ;
     712             :     do
     713             :     {
     714       18847 :         *--tp = codep->value;
     715       18847 :         codep = codep->next;
     716       18847 :     } while (--occ);
     717             : }
     718             : 
     719        4423 : after_loop:
     720       13014 :     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
     721       13014 :     tif->tif_rawcp = (uint8_t *)bp;
     722       13014 :     sp->old_tif_rawcc = tif->tif_rawcc;
     723       13014 :     sp->dec_bitsleft = dec_bitsleft;
     724       13014 :     sp->lzw_nbits = (unsigned short)nbits;
     725       13014 :     sp->lzw_nextdata = nextdata;
     726       13014 :     sp->lzw_nextbits = nextbits;
     727       13014 :     sp->dec_nbitsmask = nbitsmask;
     728       13014 :     sp->dec_oldcodep = oldcodep;
     729       13014 :     sp->dec_free_entp = free_entp;
     730       13014 :     sp->dec_maxcodep = maxcodep;
     731             : 
     732       13014 :     if (occ > 0)
     733             :     {
     734           0 :         TIFFErrorExtR(tif, module,
     735             :                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
     736             :                       " bytes)",
     737             :                       tif->tif_row, (uint64_t)occ);
     738           0 :         return (0);
     739             :     }
     740       13014 :     return (1);
     741             : 
     742           0 : no_eoi:
     743           0 :     sp->read_error = 1;
     744           0 :     TIFFErrorExtR(tif, module,
     745             :                   "LZWDecode: Strip %" PRIu32 " not terminated with EOI code",
     746             :                   tif->tif_curstrip);
     747           0 :     return 0;
     748           0 : error_code:
     749           0 :     sp->read_error = 1;
     750           0 :     TIFFErrorExtR(tif, tif->tif_name, "Using code not yet in table");
     751           0 :     return 0;
     752             : }
     753             : 
     754             : #ifdef LZW_COMPAT
     755             : 
     756             : /*
     757             :  * This check shouldn't be necessary because each
     758             :  * strip is suppose to be terminated with CODE_EOI.
     759             :  */
     760             : #define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)                    \
     761             :     {                                                                          \
     762             :         if (dec_bitsleft < (uint64_t)nbits)                                    \
     763             :         {                                                                      \
     764             :             TIFFWarningExtR(_tif, module,                                      \
     765             :                             "LZWDecode: Strip %" PRIu32                        \
     766             :                             " not terminated with EOI code",                   \
     767             :                             _tif->tif_curstrip);                               \
     768             :             _code = CODE_EOI;                                                  \
     769             :         }                                                                      \
     770             :         else                                                                   \
     771             :         {                                                                      \
     772             :             _get(_sp, _bp, _code);                                             \
     773             :             dec_bitsleft -= nbits;                                             \
     774             :         }                                                                      \
     775             :     }
     776             : 
     777             : /*
     778             :  * Decode a "hunk of data" for old images.
     779             :  */
     780             : #define GetNextCodeCompat(sp, bp, code)                                        \
     781             :     {                                                                          \
     782             :         nextdata |= (unsigned long)*(bp)++ << nextbits;                        \
     783             :         nextbits += 8;                                                         \
     784             :         if (nextbits < nbits)                                                  \
     785             :         {                                                                      \
     786             :             nextdata |= (unsigned long)*(bp)++ << nextbits;                    \
     787             :             nextbits += 8;                                                     \
     788             :         }                                                                      \
     789             :         code = (hcode_t)(nextdata & nbitsmask);                                \
     790             :         nextdata >>= nbits;                                                    \
     791             :         nextbits -= nbits;                                                     \
     792             :     }
     793             : 
     794          77 : static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
     795             : {
     796             :     static const char module[] = "LZWDecodeCompat";
     797          77 :     LZWCodecState *sp = LZWDecoderState(tif);
     798          77 :     uint8_t *op = (uint8_t *)op0;
     799          77 :     tmsize_t occ = occ0;
     800             :     uint8_t *tp;
     801             :     uint8_t *bp;
     802             :     int code, nbits;
     803             :     int len;
     804             :     long nextbits, nbitsmask;
     805             :     WordType nextdata;
     806             :     code_t *codep, *free_entp, *maxcodep, *oldcodep;
     807             : 
     808             :     (void)s;
     809          77 :     assert(sp != NULL);
     810             : 
     811             :     /*
     812             :      * Restart interrupted output operation.
     813             :      */
     814          77 :     if (sp->dec_restart)
     815             :     {
     816             :         tmsize_t residue;
     817             : 
     818           0 :         codep = sp->dec_codep;
     819           0 :         residue = codep->length - sp->dec_restart;
     820           0 :         if (residue > occ)
     821             :         {
     822             :             /*
     823             :              * Residue from previous decode is sufficient
     824             :              * to satisfy decode request.  Skip to the
     825             :              * start of the decoded string, place decoded
     826             :              * values in the output buffer, and return.
     827             :              */
     828           0 :             sp->dec_restart += occ;
     829             :             do
     830             :             {
     831           0 :                 codep = codep->next;
     832           0 :             } while (--residue > occ);
     833           0 :             tp = op + occ;
     834             :             do
     835             :             {
     836           0 :                 *--tp = codep->value;
     837           0 :                 codep = codep->next;
     838           0 :             } while (--occ);
     839           0 :             return (1);
     840             :         }
     841             :         /*
     842             :          * Residue satisfies only part of the decode request.
     843             :          */
     844           0 :         op += residue;
     845           0 :         occ -= residue;
     846           0 :         tp = op;
     847             :         do
     848             :         {
     849           0 :             *--tp = codep->value;
     850           0 :             codep = codep->next;
     851           0 :         } while (--residue);
     852           0 :         sp->dec_restart = 0;
     853             :     }
     854             : 
     855          77 :     bp = (uint8_t *)tif->tif_rawcp;
     856             : 
     857          77 :     sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
     858          77 :     uint64_t dec_bitsleft = sp->dec_bitsleft;
     859             : 
     860          77 :     nbits = sp->lzw_nbits;
     861          77 :     nextdata = sp->lzw_nextdata;
     862          77 :     nextbits = sp->lzw_nextbits;
     863          77 :     nbitsmask = sp->dec_nbitsmask;
     864          77 :     oldcodep = sp->dec_oldcodep;
     865          77 :     free_entp = sp->dec_free_entp;
     866          77 :     maxcodep = sp->dec_maxcodep;
     867             : 
     868      154139 :     while (occ > 0)
     869             :     {
     870      154062 :         NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
     871      154062 :         if (code == CODE_EOI)
     872           0 :             break;
     873      154062 :         if (code == CODE_CLEAR)
     874             :         {
     875             :             do
     876             :             {
     877          77 :                 free_entp = sp->dec_codetab + CODE_FIRST;
     878          77 :                 _TIFFmemset(free_entp, 0,
     879             :                             (CSIZE - CODE_FIRST) * sizeof(code_t));
     880          77 :                 nbits = BITS_MIN;
     881          77 :                 nbitsmask = MAXCODE(BITS_MIN);
     882          77 :                 maxcodep = sp->dec_codetab + nbitsmask;
     883          77 :                 NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
     884          77 :             } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
     885          77 :             if (code == CODE_EOI)
     886           0 :                 break;
     887          77 :             if (code > CODE_CLEAR)
     888             :             {
     889           0 :                 TIFFErrorExtR(
     890           0 :                     tif, tif->tif_name,
     891             :                     "LZWDecode: Corrupted LZW table at scanline %" PRIu32,
     892             :                     tif->tif_row);
     893           0 :                 return (0);
     894             :             }
     895          77 :             *op++ = (uint8_t)code;
     896          77 :             occ--;
     897          77 :             oldcodep = sp->dec_codetab + code;
     898          77 :             continue;
     899             :         }
     900      153985 :         codep = sp->dec_codetab + code;
     901             : 
     902             :         /*
     903             :          * Add the new entry to the code table.
     904             :          */
     905      153985 :         if (free_entp < &sp->dec_codetab[0] ||
     906      153985 :             free_entp >= &sp->dec_codetab[CSIZE])
     907             :         {
     908           0 :             TIFFErrorExtR(tif, module,
     909             :                           "Corrupted LZW table at scanline %" PRIu32,
     910             :                           tif->tif_row);
     911           0 :             return (0);
     912             :         }
     913             : 
     914      153985 :         free_entp->next = oldcodep;
     915      153985 :         if (free_entp->next < &sp->dec_codetab[0] ||
     916      153985 :             free_entp->next >= &sp->dec_codetab[CSIZE])
     917             :         {
     918           0 :             TIFFErrorExtR(tif, module,
     919             :                           "Corrupted LZW table at scanline %" PRIu32,
     920             :                           tif->tif_row);
     921           0 :             return (0);
     922             :         }
     923      153985 :         free_entp->firstchar = free_entp->next->firstchar;
     924      153985 :         free_entp->length = free_entp->next->length + 1;
     925      153985 :         free_entp->value =
     926             :             (codep < free_entp) ? codep->firstchar : free_entp->firstchar;
     927      153985 :         if (++free_entp > maxcodep)
     928             :         {
     929        4700 :             if (++nbits > BITS_MAX) /* should not happen */
     930        4564 :                 nbits = BITS_MAX;
     931        4700 :             nbitsmask = MAXCODE(nbits);
     932        4700 :             maxcodep = sp->dec_codetab + nbitsmask;
     933             :         }
     934      153985 :         oldcodep = codep;
     935      153985 :         if (code >= 256)
     936             :         {
     937             :             /*
     938             :              * Code maps to a string, copy string
     939             :              * value to output (written in reverse).
     940             :              */
     941       54141 :             if (codep->length == 0)
     942             :             {
     943           0 :                 TIFFErrorExtR(
     944             :                     tif, module,
     945             :                     "Wrong length of decoded "
     946             :                     "string: data probably corrupted at scanline %" PRIu32,
     947             :                     tif->tif_row);
     948           0 :                 return (0);
     949             :             }
     950       54141 :             if (codep->length > occ)
     951             :             {
     952             :                 /*
     953             :                  * String is too long for decode buffer,
     954             :                  * locate portion that will fit, copy to
     955             :                  * the decode buffer, and setup restart
     956             :                  * logic for the next decoding call.
     957             :                  */
     958           0 :                 sp->dec_codep = codep;
     959             :                 do
     960             :                 {
     961           0 :                     codep = codep->next;
     962           0 :                 } while (codep->length > occ);
     963           0 :                 sp->dec_restart = occ;
     964           0 :                 tp = op + occ;
     965             :                 do
     966             :                 {
     967           0 :                     *--tp = codep->value;
     968           0 :                     codep = codep->next;
     969           0 :                 } while (--occ);
     970           0 :                 break;
     971             :             }
     972       54141 :             len = codep->length;
     973       54141 :             tp = op + len;
     974             :             do
     975             :             {
     976      489903 :                 *--tp = codep->value;
     977      489903 :                 codep = codep->next;
     978      489903 :             } while (codep && tp > op);
     979       54141 :             assert(occ >= len);
     980       54141 :             op += len;
     981       54141 :             occ -= len;
     982             :         }
     983             :         else
     984             :         {
     985       99844 :             *op++ = (uint8_t)code;
     986       99844 :             occ--;
     987             :         }
     988             :     }
     989             : 
     990          77 :     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
     991          77 :     tif->tif_rawcp = (uint8_t *)bp;
     992             : 
     993          77 :     sp->old_tif_rawcc = tif->tif_rawcc;
     994          77 :     sp->dec_bitsleft = dec_bitsleft;
     995             : 
     996          77 :     sp->lzw_nbits = (unsigned short)nbits;
     997          77 :     sp->lzw_nextdata = nextdata;
     998          77 :     sp->lzw_nextbits = nextbits;
     999          77 :     sp->dec_nbitsmask = nbitsmask;
    1000          77 :     sp->dec_oldcodep = oldcodep;
    1001          77 :     sp->dec_free_entp = free_entp;
    1002          77 :     sp->dec_maxcodep = maxcodep;
    1003             : 
    1004          77 :     if (occ > 0)
    1005             :     {
    1006           0 :         TIFFErrorExtR(tif, module,
    1007             :                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
    1008             :                       " bytes)",
    1009             :                       tif->tif_row, (uint64_t)occ);
    1010           0 :         return (0);
    1011             :     }
    1012          77 :     return (1);
    1013             : }
    1014             : #endif /* LZW_COMPAT */
    1015             : 
    1016             : /*
    1017             :  * LZW Encoding.
    1018             :  */
    1019             : 
    1020       11259 : static int LZWSetupEncode(TIFF *tif)
    1021             : {
    1022             :     static const char module[] = "LZWSetupEncode";
    1023       11259 :     LZWCodecState *sp = LZWEncoderState(tif);
    1024             : 
    1025       11259 :     assert(sp != NULL);
    1026       11259 :     sp->enc_hashtab = (hash_t *)_TIFFmallocExt(tif, HSIZE * sizeof(hash_t));
    1027       11259 :     if (sp->enc_hashtab == NULL)
    1028             :     {
    1029           1 :         TIFFErrorExtR(tif, module, "No space for LZW hash table");
    1030           0 :         return (0);
    1031             :     }
    1032       11258 :     return (1);
    1033             : }
    1034             : 
    1035             : /*
    1036             :  * Reset encoding state at the start of a strip.
    1037             :  */
    1038       12918 : static int LZWPreEncode(TIFF *tif, uint16_t s)
    1039             : {
    1040       12918 :     LZWCodecState *sp = LZWEncoderState(tif);
    1041             : 
    1042             :     (void)s;
    1043       12918 :     assert(sp != NULL);
    1044             : 
    1045       12918 :     if (sp->enc_hashtab == NULL)
    1046             :     {
    1047           0 :         tif->tif_setupencode(tif);
    1048             :     }
    1049             : 
    1050       12918 :     sp->lzw_nbits = BITS_MIN;
    1051       12918 :     sp->lzw_maxcode = MAXCODE(BITS_MIN);
    1052       12918 :     sp->lzw_free_ent = CODE_FIRST;
    1053       12918 :     sp->lzw_nextbits = 0;
    1054       12918 :     sp->lzw_nextdata = 0;
    1055       12918 :     sp->enc_checkpoint = CHECK_GAP;
    1056       12918 :     sp->enc_ratio = 0;
    1057       12918 :     sp->enc_incount = 0;
    1058       12918 :     sp->enc_outcount = 0;
    1059             :     /*
    1060             :      * The 4 here insures there is space for 2 max-sized
    1061             :      * codes in LZWEncode and LZWPostDecode.
    1062             :      */
    1063       12918 :     sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize - 1 - 4;
    1064       12918 :     cl_hash(sp);                   /* clear hash table */
    1065       12918 :     sp->enc_oldcode = (hcode_t)-1; /* generates CODE_CLEAR in LZWEncode */
    1066       12918 :     return (1);
    1067             : }
    1068             : 
    1069             : #define CALCRATIO(sp, rat)                                                     \
    1070             :     {                                                                          \
    1071             :         if (incount > 0x007fffff)                                              \
    1072             :         { /* NB: shift will overflow */                                        \
    1073             :             rat = outcount >> 8;                                               \
    1074             :             rat = (rat == 0 ? 0x7fffffff : incount / rat);                     \
    1075             :         }                                                                      \
    1076             :         else                                                                   \
    1077             :             rat = (incount << 8) / outcount;                                   \
    1078             :     }
    1079             : 
    1080             : /* Explicit 0xff masking to make icc -check=conversions happy */
    1081             : #define PutNextCode(op, c)                                                     \
    1082             :     {                                                                          \
    1083             :         nextdata = (nextdata << nbits) | c;                                    \
    1084             :         nextbits += nbits;                                                     \
    1085             :         *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);          \
    1086             :         nextbits -= 8;                                                         \
    1087             :         if (nextbits >= 8)                                                     \
    1088             :         {                                                                      \
    1089             :             *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);      \
    1090             :             nextbits -= 8;                                                     \
    1091             :         }                                                                      \
    1092             :         outcount += nbits;                                                     \
    1093             :     }
    1094             : 
    1095             : /*
    1096             :  * Encode a chunk of pixels.
    1097             :  *
    1098             :  * Uses an open addressing double hashing (no chaining) on the
    1099             :  * prefix code/next character combination.  We do a variant of
    1100             :  * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
    1101             :  * relatively-prime secondary probe.  Here, the modular division
    1102             :  * first probe is gives way to a faster exclusive-or manipulation.
    1103             :  * Also do block compression with an adaptive reset, whereby the
    1104             :  * code table is cleared when the compression ratio decreases,
    1105             :  * but after the table fills.  The variable-length output codes
    1106             :  * are re-sized at this point, and a CODE_CLEAR is generated
    1107             :  * for the decoder.
    1108             :  */
    1109       34914 : static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
    1110             : {
    1111       34914 :     register LZWCodecState *sp = LZWEncoderState(tif);
    1112             :     register long fcode;
    1113             :     register hash_t *hp;
    1114             :     register int h, c;
    1115             :     hcode_t ent;
    1116             :     long disp;
    1117             :     tmsize_t incount, outcount, checkpoint;
    1118             :     WordType nextdata;
    1119             :     long nextbits;
    1120             :     int free_ent, maxcode, nbits;
    1121             :     uint8_t *op;
    1122             :     uint8_t *limit;
    1123             : 
    1124             :     (void)s;
    1125       34914 :     if (sp == NULL)
    1126           0 :         return (0);
    1127             : 
    1128       34914 :     assert(sp->enc_hashtab != NULL);
    1129             : 
    1130             :     /*
    1131             :      * Load local state.
    1132             :      */
    1133       34914 :     incount = sp->enc_incount;
    1134       34914 :     outcount = sp->enc_outcount;
    1135       34914 :     checkpoint = sp->enc_checkpoint;
    1136       34914 :     nextdata = sp->lzw_nextdata;
    1137       34914 :     nextbits = sp->lzw_nextbits;
    1138       34914 :     free_ent = sp->lzw_free_ent;
    1139       34914 :     maxcode = sp->lzw_maxcode;
    1140       34914 :     nbits = sp->lzw_nbits;
    1141       34914 :     op = tif->tif_rawcp;
    1142       34914 :     limit = sp->enc_rawlimit;
    1143       34914 :     ent = (hcode_t)sp->enc_oldcode;
    1144             : 
    1145       34914 :     if (ent == (hcode_t)-1 && cc > 0)
    1146             :     {
    1147             :         /*
    1148             :          * NB: This is safe because it can only happen
    1149             :          *     at the start of a strip where we know there
    1150             :          *     is space in the data buffer.
    1151             :          */
    1152       12918 :         PutNextCode(op, CODE_CLEAR);
    1153       12918 :         ent = *bp++;
    1154       12918 :         cc--;
    1155       12918 :         incount++;
    1156             :     }
    1157       34914 :     while (cc > 0)
    1158             :     {
    1159   565272000 :         c = *bp++;
    1160   565272000 :         cc--;
    1161   565272000 :         incount++;
    1162   565272000 :         fcode = ((long)c << BITS_MAX) + ent;
    1163   565272000 :         h = (c << HSHIFT) ^ ent; /* xor hashing */
    1164             : #ifdef _WINDOWS
    1165             :         /*
    1166             :          * Check hash index for an overflow.
    1167             :          */
    1168             :         if (h >= HSIZE)
    1169             :             h -= HSIZE;
    1170             : #endif
    1171   565272000 :         hp = &sp->enc_hashtab[h];
    1172   565272000 :         if (hp->hash == fcode)
    1173             :         {
    1174   445328000 :             ent = hp->code;
    1175   445328000 :             continue;
    1176             :         }
    1177   119944000 :         if (hp->hash >= 0)
    1178             :         {
    1179             :             /*
    1180             :              * Primary hash failed, check secondary hash.
    1181             :              */
    1182   101220000 :             disp = HSIZE - h;
    1183   101220000 :             if (h == 0)
    1184       13805 :                 disp = 1;
    1185             :             do
    1186             :             {
    1187             :                 /*
    1188             :                  * Avoid pointer arithmetic because of
    1189             :                  * wraparound problems with segments.
    1190             :                  */
    1191   127170000 :                 if ((h -= disp) < 0)
    1192   120616000 :                     h += HSIZE;
    1193   127170000 :                 hp = &sp->enc_hashtab[h];
    1194   127170000 :                 if (hp->hash == fcode)
    1195             :                 {
    1196    94882700 :                     ent = hp->code;
    1197    94882700 :                     goto hit;
    1198             :                 }
    1199    32286800 :             } while (hp->hash >= 0);
    1200             :         }
    1201             :         /*
    1202             :          * New entry, emit code and add to table.
    1203             :          */
    1204             :         /*
    1205             :          * Verify there is space in the buffer for the code
    1206             :          * and any potential Clear code that might be emitted
    1207             :          * below.  The value of limit is setup so that there
    1208             :          * are at least 4 bytes free--room for 2 codes.
    1209             :          */
    1210    25061000 :         if (op > limit)
    1211             :         {
    1212           1 :             tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1213           1 :             if (!TIFFFlushData1(tif))
    1214           0 :                 return 0;
    1215           1 :             op = tif->tif_rawdata;
    1216             :         }
    1217    25061000 :         PutNextCode(op, ent);
    1218    25061000 :         ent = (hcode_t)c;
    1219    25061000 :         hp->code = (hcode_t)(free_ent++);
    1220    25061000 :         hp->hash = fcode;
    1221    25061000 :         if (free_ent == CODE_MAX - 1)
    1222             :         {
    1223             :             /* table is full, emit clear code and reset */
    1224        5597 :             cl_hash(sp);
    1225        5597 :             sp->enc_ratio = 0;
    1226        5597 :             incount = 0;
    1227        5597 :             outcount = 0;
    1228        5597 :             free_ent = CODE_FIRST;
    1229        5597 :             PutNextCode(op, CODE_CLEAR);
    1230        5597 :             nbits = BITS_MIN;
    1231        5597 :             maxcode = MAXCODE(BITS_MIN);
    1232             :         }
    1233             :         else
    1234             :         {
    1235             :             /*
    1236             :              * If the next entry is going to be too big for
    1237             :              * the code size, then increase it, if possible.
    1238             :              */
    1239    25055400 :             if (free_ent > maxcode)
    1240             :             {
    1241       23036 :                 nbits++;
    1242       23036 :                 assert(nbits <= BITS_MAX);
    1243       23036 :                 maxcode = (int)MAXCODE(nbits);
    1244             :             }
    1245    25032400 :             else if (incount >= checkpoint)
    1246             :             {
    1247             :                 tmsize_t rat;
    1248             :                 /*
    1249             :                  * Check compression ratio and, if things seem
    1250             :                  * to be slipping, clear the hash table and
    1251             :                  * reset state.  The compression ratio is a
    1252             :                  * 24+8-bit fractional number.
    1253             :                  */
    1254       37115 :                 checkpoint = incount + CHECK_GAP;
    1255       37115 :                 CALCRATIO(sp, rat);
    1256       37115 :                 if (rat <= sp->enc_ratio)
    1257             :                 {
    1258         111 :                     cl_hash(sp);
    1259         111 :                     sp->enc_ratio = 0;
    1260         111 :                     incount = 0;
    1261         111 :                     outcount = 0;
    1262         111 :                     free_ent = CODE_FIRST;
    1263         111 :                     PutNextCode(op, CODE_CLEAR);
    1264         111 :                     nbits = BITS_MIN;
    1265         111 :                     maxcode = MAXCODE(BITS_MIN);
    1266             :                 }
    1267             :                 else
    1268       37004 :                     sp->enc_ratio = rat;
    1269             :             }
    1270             :         }
    1271   565307000 :     hit:;
    1272             :     }
    1273             : 
    1274             :     /*
    1275             :      * Restore global state.
    1276             :      */
    1277       34914 :     sp->enc_incount = incount;
    1278       34914 :     sp->enc_outcount = outcount;
    1279       34914 :     sp->enc_checkpoint = checkpoint;
    1280       34914 :     sp->enc_oldcode = ent;
    1281       34914 :     sp->lzw_nextdata = nextdata;
    1282       34914 :     sp->lzw_nextbits = nextbits;
    1283       34914 :     sp->lzw_free_ent = (unsigned short)free_ent;
    1284       34914 :     sp->lzw_maxcode = (unsigned short)maxcode;
    1285       34914 :     sp->lzw_nbits = (unsigned short)nbits;
    1286       34914 :     tif->tif_rawcp = op;
    1287       34914 :     return (1);
    1288             : }
    1289             : 
    1290             : /*
    1291             :  * Finish off an encoded strip by flushing the last
    1292             :  * string and tacking on an End Of Information code.
    1293             :  */
    1294       12919 : static int LZWPostEncode(TIFF *tif)
    1295             : {
    1296       12919 :     register LZWCodecState *sp = LZWEncoderState(tif);
    1297       12919 :     uint8_t *op = tif->tif_rawcp;
    1298       12919 :     long nextbits = sp->lzw_nextbits;
    1299       12919 :     WordType nextdata = sp->lzw_nextdata;
    1300       12919 :     tmsize_t outcount = sp->enc_outcount;
    1301       12919 :     int nbits = sp->lzw_nbits;
    1302             : 
    1303       12919 :     if (op > sp->enc_rawlimit)
    1304             :     {
    1305           0 :         tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1306           0 :         if (!TIFFFlushData1(tif))
    1307           0 :             return 0;
    1308           0 :         op = tif->tif_rawdata;
    1309             :     }
    1310       12919 :     if (sp->enc_oldcode != (hcode_t)-1)
    1311             :     {
    1312       12919 :         int free_ent = sp->lzw_free_ent;
    1313             : 
    1314       12919 :         PutNextCode(op, sp->enc_oldcode);
    1315       12919 :         sp->enc_oldcode = (hcode_t)-1;
    1316       12919 :         free_ent++;
    1317             : 
    1318       12919 :         if (free_ent == CODE_MAX - 1)
    1319             :         {
    1320             :             /* table is full, emit clear code and reset */
    1321           0 :             outcount = 0;
    1322           0 :             PutNextCode(op, CODE_CLEAR);
    1323           0 :             nbits = BITS_MIN;
    1324             :         }
    1325             :         else
    1326             :         {
    1327             :             /*
    1328             :              * If the next entry is going to be too big for
    1329             :              * the code size, then increase it, if possible.
    1330             :              */
    1331       12919 :             if (free_ent > sp->lzw_maxcode)
    1332             :             {
    1333           1 :                 nbits++;
    1334           1 :                 assert(nbits <= BITS_MAX);
    1335             :             }
    1336             :         }
    1337             :     }
    1338       12919 :     PutNextCode(op, CODE_EOI);
    1339             :     /* Explicit 0xff masking to make icc -check=conversions happy */
    1340       12919 :     if (nextbits > 0)
    1341       12814 :         *op++ = (unsigned char)((nextdata << (8 - nextbits)) & 0xff);
    1342       12919 :     tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
    1343             :     (void)outcount;
    1344       12919 :     return (1);
    1345             : }
    1346             : 
    1347             : /*
    1348             :  * Reset encoding hash table.
    1349             :  */
    1350       18627 : static void cl_hash(LZWCodecState *sp)
    1351             : {
    1352       18627 :     register hash_t *hp = &sp->enc_hashtab[HSIZE - 1];
    1353       18627 :     register long i = HSIZE - 8;
    1354             : 
    1355             :     do
    1356             :     {
    1357    20933700 :         i -= 8;
    1358    20933700 :         hp[-7].hash = -1;
    1359    20933700 :         hp[-6].hash = -1;
    1360    20933700 :         hp[-5].hash = -1;
    1361    20933700 :         hp[-4].hash = -1;
    1362    20933700 :         hp[-3].hash = -1;
    1363    20933700 :         hp[-2].hash = -1;
    1364    20933700 :         hp[-1].hash = -1;
    1365    20933700 :         hp[0].hash = -1;
    1366    20933700 :         hp -= 8;
    1367    20933700 :     } while (i >= 0);
    1368       37254 :     for (i += 8; i > 0; i--, hp--)
    1369       18627 :         hp->hash = -1;
    1370       18627 : }
    1371             : 
    1372       17617 : static void LZWCleanup(TIFF *tif)
    1373             : {
    1374       17617 :     (void)TIFFPredictorCleanup(tif);
    1375             : 
    1376       17620 :     assert(tif->tif_data != 0);
    1377             : 
    1378       17620 :     if (LZWDecoderState(tif)->dec_codetab)
    1379        2386 :         _TIFFfreeExt(tif, LZWDecoderState(tif)->dec_codetab);
    1380             : 
    1381       17616 :     if (LZWEncoderState(tif)->enc_hashtab)
    1382       11252 :         _TIFFfreeExt(tif, LZWEncoderState(tif)->enc_hashtab);
    1383             : 
    1384       17619 :     _TIFFfreeExt(tif, tif->tif_data);
    1385       17615 :     tif->tif_data = NULL;
    1386             : 
    1387       17615 :     _TIFFSetDefaultCompressionState(tif);
    1388       17616 : }
    1389             : 
    1390       17628 : int TIFFInitLZW(TIFF *tif, int scheme)
    1391             : {
    1392             :     static const char module[] = "TIFFInitLZW";
    1393             :     (void)scheme;
    1394       17628 :     assert(scheme == COMPRESSION_LZW);
    1395             :     /*
    1396             :      * Allocate state block so tag methods have storage to record values.
    1397             :      */
    1398       17628 :     tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
    1399       17629 :     if (tif->tif_data == NULL)
    1400           0 :         goto bad;
    1401       17629 :     LZWDecoderState(tif)->dec_codetab = NULL;
    1402       17629 :     LZWDecoderState(tif)->dec_decode = NULL;
    1403       17629 :     LZWEncoderState(tif)->enc_hashtab = NULL;
    1404       17629 :     LZWState(tif)->rw_mode = tif->tif_mode;
    1405             : 
    1406             :     /*
    1407             :      * Install codec methods.
    1408             :      */
    1409       17629 :     tif->tif_fixuptags = LZWFixupTags;
    1410       17629 :     tif->tif_setupdecode = LZWSetupDecode;
    1411       17629 :     tif->tif_predecode = LZWPreDecode;
    1412       17629 :     tif->tif_decoderow = LZWDecode;
    1413       17629 :     tif->tif_decodestrip = LZWDecode;
    1414       17629 :     tif->tif_decodetile = LZWDecode;
    1415       17629 :     tif->tif_setupencode = LZWSetupEncode;
    1416       17629 :     tif->tif_preencode = LZWPreEncode;
    1417       17629 :     tif->tif_postencode = LZWPostEncode;
    1418       17629 :     tif->tif_encoderow = LZWEncode;
    1419       17629 :     tif->tif_encodestrip = LZWEncode;
    1420       17629 :     tif->tif_encodetile = LZWEncode;
    1421       17629 :     tif->tif_cleanup = LZWCleanup;
    1422             :     /*
    1423             :      * Setup predictor setup.
    1424             :      */
    1425       17629 :     (void)TIFFPredictorInit(tif);
    1426       17628 :     return (1);
    1427           0 : bad:
    1428           0 :     TIFFErrorExtR(tif, module, "No space for LZW state block");
    1429           0 :     return (0);
    1430             : }
    1431             : 
    1432             : /*
    1433             :  * Copyright (c) 1985, 1986 The Regents of the University of California.
    1434             :  * All rights reserved.
    1435             :  *
    1436             :  * This code is derived from software contributed to Berkeley by
    1437             :  * James A. Woods, derived from original work by Spencer Thomas
    1438             :  * and Joseph Orost.
    1439             :  *
    1440             :  * Redistribution and use in source and binary forms are permitted
    1441             :  * provided that the above copyright notice and this paragraph are
    1442             :  * duplicated in all such forms and that any documentation,
    1443             :  * advertising materials, and other materials related to such
    1444             :  * distribution and use acknowledge that the software was developed
    1445             :  * by the University of California, Berkeley.  The name of the
    1446             :  * University may not be used to endorse or promote products derived
    1447             :  * from this software without specific prior written permission.
    1448             :  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
    1449             :  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
    1450             :  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
    1451             :  */
    1452             : #endif /* LZW_SUPPORT */

Generated by: LCOV version 1.14