xref: /aosp_15_r20/external/pdfium/third_party/libtiff/tif_lzw.c (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
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 DecoderState(tif) ((LZWCodecState *)LZWState(tif))
165 #define EncoderState(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 
LZWFixupTags(TIFF * tif)177 static int LZWFixupTags(TIFF *tif)
178 {
179     (void)tif;
180     return (1);
181 }
182 
LZWSetupDecode(TIFF * tif)183 static int LZWSetupDecode(TIFF *tif)
184 {
185     static const char module[] = "LZWSetupDecode";
186     LZWCodecState *sp = DecoderState(tif);
187     int code;
188 
189     if (sp == NULL)
190     {
191         /*
192          * Allocate state block so tag methods have storage to record
193          * values.
194          */
195         tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
196         if (tif->tif_data == NULL)
197         {
198             TIFFErrorExtR(tif, module, "No space for LZW state block");
199             return (0);
200         }
201 
202         sp = DecoderState(tif);
203         sp->dec_codetab = NULL;
204         sp->dec_decode = NULL;
205 
206         /*
207          * Setup predictor setup.
208          */
209         (void)TIFFPredictorInit(tif);
210     }
211 
212     if (sp->dec_codetab == NULL)
213     {
214         sp->dec_codetab = (code_t *)_TIFFmallocExt(tif, CSIZE * sizeof(code_t));
215         if (sp->dec_codetab == NULL)
216         {
217             TIFFErrorExtR(tif, module, "No space for LZW code table");
218             return (0);
219         }
220         /*
221          * Pre-load the table.
222          */
223         code = 255;
224         do
225         {
226             sp->dec_codetab[code].firstchar = (unsigned char)code;
227             sp->dec_codetab[code].value = (unsigned char)code;
228             sp->dec_codetab[code].repeated = true;
229             sp->dec_codetab[code].length = 1;
230             sp->dec_codetab[code].next = NULL;
231         } while (code--);
232         /*
233          * Zero-out the unused entries  */
234         /* Silence false positive */
235         /* coverity[overrun-buffer-arg] */
236         memset(&sp->dec_codetab[CODE_CLEAR], 0,
237                (CODE_FIRST - CODE_CLEAR) * sizeof(code_t));
238     }
239     return (1);
240 }
241 
242 /*
243  * Setup state for decoding a strip.
244  */
LZWPreDecode(TIFF * tif,uint16_t s)245 static int LZWPreDecode(TIFF *tif, uint16_t s)
246 {
247     static const char module[] = "LZWPreDecode";
248     LZWCodecState *sp = DecoderState(tif);
249 
250     (void)s;
251     assert(sp != NULL);
252     if (sp->dec_codetab == NULL)
253     {
254         tif->tif_setupdecode(tif);
255         if (sp->dec_codetab == NULL)
256             return (0);
257     }
258 
259     /*
260      * Check for old bit-reversed codes.
261      */
262     if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 &&
263         (tif->tif_rawdata[1] & 0x1))
264     {
265 #ifdef LZW_COMPAT
266         if (!sp->dec_decode)
267         {
268             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             tif->tif_decoderow = LZWDecodeCompat;
277             tif->tif_decodestrip = LZWDecodeCompat;
278             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             (*tif->tif_setupdecode)(tif);
285             sp->dec_decode = LZWDecodeCompat;
286         }
287         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         sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1;
300         sp->dec_decode = LZWDecode;
301     }
302     sp->lzw_nbits = BITS_MIN;
303     sp->lzw_nextbits = 0;
304     sp->lzw_nextdata = 0;
305 
306     sp->dec_restart = 0;
307     sp->dec_nbitsmask = MAXCODE(BITS_MIN);
308     sp->dec_bitsleft = 0;
309     sp->old_tif_rawcc = 0;
310     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     sp->dec_oldcodep = &sp->dec_codetab[0];
319     sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1];
320     sp->read_error = 0;
321     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(__GNUC__) && defined(__x86_64__)
333 #define GetNextData(nextdata, bp)                                              \
334     nextdata = __builtin_bswap64(*(uint64_t *)(bp))
335 #elif defined(_M_X64)
336 #define GetNextData(nextdata, bp) nextdata = _byteswap_uint64(*(uint64_t *)(bp))
337 #elif defined(__GNUC__)
338 #define GetNextData(nextdata, bp)                                              \
339     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
340     nextdata = __builtin_bswap64(nextdata)
341 #else
342 #define GetNextData(nextdata, bp)                                              \
343     nextdata = (((uint64_t)bp[0]) << 56) | (((uint64_t)bp[1]) << 48) |         \
344                (((uint64_t)bp[2]) << 40) | (((uint64_t)bp[3]) << 32) |         \
345                (((uint64_t)bp[4]) << 24) | (((uint64_t)bp[5]) << 16) |         \
346                (((uint64_t)bp[6]) << 8) | (((uint64_t)bp[7]))
347 #endif
348 #elif SIZEOF_WORDTYPE == 4
349 #if defined(__GNUC__) && defined(__i386__)
350 #define GetNextData(nextdata, bp)                                              \
351     nextdata = __builtin_bswap32(*(uint32_t *)(bp))
352 #elif defined(_M_X86)
353 #define GetNextData(nextdata, bp)                                              \
354     nextdata = _byteswap_ulong(*(unsigned long *)(bp))
355 #elif defined(__GNUC__)
356 #define GetNextData(nextdata, bp)                                              \
357     memcpy(&nextdata, bp, sizeof(nextdata));                                   \
358     nextdata = __builtin_bswap32(nextdata)
359 #else
360 #define GetNextData(nextdata, bp)                                              \
361     nextdata = (((uint32_t)bp[0]) << 24) | (((uint32_t)bp[1]) << 16) |         \
362                (((uint32_t)bp[2]) << 8) | (((uint32_t)bp[3]))
363 #endif
364 #else
365 #error "Unhandled SIZEOF_WORDTYPE"
366 #endif
367 
368 #define GetNextCodeLZW()                                                       \
369     do                                                                         \
370     {                                                                          \
371         nextbits -= nbits;                                                     \
372         if (nextbits < 0)                                                      \
373         {                                                                      \
374             if (dec_bitsleft >= 8 * SIZEOF_WORDTYPE)                           \
375             {                                                                  \
376                 unsigned codetmp = (unsigned)(nextdata << (-nextbits));        \
377                 GetNextData(nextdata, bp);                                     \
378                 bp += SIZEOF_WORDTYPE;                                         \
379                 nextbits += 8 * SIZEOF_WORDTYPE;                               \
380                 dec_bitsleft -= 8 * SIZEOF_WORDTYPE;                           \
381                 code = (WordType)((codetmp | (nextdata >> nextbits)) &         \
382                                   nbitsmask);                                  \
383                 break;                                                         \
384             }                                                                  \
385             else                                                               \
386             {                                                                  \
387                 if (dec_bitsleft < 8)                                          \
388                 {                                                              \
389                     goto no_eoi;                                               \
390                 }                                                              \
391                 nextdata = (nextdata << 8) | *(bp)++;                          \
392                 nextbits += 8;                                                 \
393                 dec_bitsleft -= 8;                                             \
394                 if (nextbits < 0)                                              \
395                 {                                                              \
396                     if (dec_bitsleft < 8)                                      \
397                     {                                                          \
398                         goto no_eoi;                                           \
399                     }                                                          \
400                     nextdata = (nextdata << 8) | *(bp)++;                      \
401                     nextbits += 8;                                             \
402                     dec_bitsleft -= 8;                                         \
403                 }                                                              \
404             }                                                                  \
405         }                                                                      \
406         code = (WordType)((nextdata >> nextbits) & nbitsmask);                 \
407     } while (0)
408 
LZWDecode(TIFF * tif,uint8_t * op0,tmsize_t occ0,uint16_t s)409 static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
410 {
411     static const char module[] = "LZWDecode";
412     LZWCodecState *sp = DecoderState(tif);
413     uint8_t *op = (uint8_t *)op0;
414     tmsize_t occ = occ0;
415     uint8_t *bp;
416     long nbits, nextbits, nbitsmask;
417     WordType nextdata;
418     code_t *free_entp, *maxcodep, *oldcodep;
419 
420     (void)s;
421     assert(sp != NULL);
422     assert(sp->dec_codetab != NULL);
423 
424     if (sp->read_error)
425     {
426         TIFFErrorExtR(tif, module,
427                       "LZWDecode: Scanline %" PRIu32 " cannot be read due to "
428                       "previous error",
429                       tif->tif_row);
430         return 0;
431     }
432 
433     /*
434      * Restart interrupted output operation.
435      */
436     if (sp->dec_restart)
437     {
438         tmsize_t residue;
439 
440         code_t *codep = sp->dec_codep;
441         residue = codep->length - sp->dec_restart;
442         if (residue > occ)
443         {
444             /*
445              * Residue from previous decode is sufficient
446              * to satisfy decode request.  Skip to the
447              * start of the decoded string, place decoded
448              * values in the output buffer, and return.
449              */
450             sp->dec_restart += occ;
451             do
452             {
453                 codep = codep->next;
454             } while (--residue > occ && codep);
455             if (codep)
456             {
457                 uint8_t *tp = op + occ;
458                 do
459                 {
460                     *--tp = codep->value;
461                     codep = codep->next;
462                 } while (--occ && codep);
463             }
464             return (1);
465         }
466         /*
467          * Residue satisfies only part of the decode request.
468          */
469         op += residue;
470         occ -= residue;
471         uint8_t *tp = op;
472         do
473         {
474             *--tp = codep->value;
475             codep = codep->next;
476         } while (--residue && codep);
477         sp->dec_restart = 0;
478     }
479 
480     bp = (uint8_t *)tif->tif_rawcp;
481     sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
482     uint64_t dec_bitsleft = sp->dec_bitsleft;
483     nbits = sp->lzw_nbits;
484     nextdata = sp->lzw_nextdata;
485     nextbits = sp->lzw_nextbits;
486     nbitsmask = sp->dec_nbitsmask;
487     oldcodep = sp->dec_oldcodep;
488     free_entp = sp->dec_free_entp;
489     maxcodep = sp->dec_maxcodep;
490     code_t *const dec_codetab = sp->dec_codetab;
491     code_t *codep;
492 
493     if (occ == 0)
494     {
495         goto after_loop;
496     }
497 
498 begin:
499 {
500     WordType code;
501     GetNextCodeLZW();
502     codep = dec_codetab + code;
503     if (code >= CODE_FIRST)
504         goto code_above_or_equal_to_258;
505     if (code < 256)
506         goto code_below_256;
507     if (code == CODE_EOI)
508         goto after_loop;
509     goto code_clear;
510 
511 code_below_256:
512 {
513     if (codep > free_entp)
514         goto error_code;
515     free_entp->next = oldcodep;
516     free_entp->firstchar = oldcodep->firstchar;
517     free_entp->length = oldcodep->length + 1;
518     free_entp->value = (uint8_t)code;
519     free_entp->repeated =
520         (bool)(oldcodep->repeated & (oldcodep->value == code));
521     if (++free_entp > maxcodep)
522     {
523         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
524             nbits = BITS_MAX;
525         nbitsmask = MAXCODE(nbits);
526         maxcodep = dec_codetab + nbitsmask - 1;
527         if (free_entp >= &dec_codetab[CSIZE])
528         {
529             /* At that point, the next valid states are either EOI or a */
530             /* CODE_CLEAR. If a regular code is read, at the next */
531             /* attempt at registering a new entry, we will error out */
532             /* due to setting free_entp before any valid code */
533             free_entp = dec_codetab - 1;
534         }
535     }
536     oldcodep = codep;
537     *op++ = (uint8_t)code;
538     occ--;
539     if (occ == 0)
540         goto after_loop;
541     goto begin;
542 }
543 
544 code_above_or_equal_to_258:
545 {
546     /*
547      * Add the new entry to the code table.
548      */
549 
550     if (codep >= free_entp)
551     {
552         if (codep != free_entp)
553             goto error_code;
554         free_entp->value = oldcodep->firstchar;
555     }
556     else
557     {
558         free_entp->value = codep->firstchar;
559     }
560     free_entp->repeated =
561         (bool)(oldcodep->repeated & (oldcodep->value == free_entp->value));
562     free_entp->next = oldcodep;
563 
564     free_entp->firstchar = oldcodep->firstchar;
565     free_entp->length = oldcodep->length + 1;
566     if (++free_entp > maxcodep)
567     {
568         if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
569             nbits = BITS_MAX;
570         nbitsmask = MAXCODE(nbits);
571         maxcodep = dec_codetab + nbitsmask - 1;
572         if (free_entp >= &dec_codetab[CSIZE])
573         {
574             /* At that point, the next valid states are either EOI or a */
575             /* CODE_CLEAR. If a regular code is read, at the next */
576             /* attempt at registering a new entry, we will error out */
577             /* due to setting free_entp before any valid code */
578             free_entp = dec_codetab - 1;
579         }
580     }
581     oldcodep = codep;
582 
583     /*
584      * Code maps to a string, copy string
585      * value to output (written in reverse).
586      */
587     /* tiny bit faster on x86_64 to store in unsigned short than int */
588     unsigned short len = codep->length;
589 
590     if (len < 3) /* equivalent to len == 2 given all other conditions */
591     {
592         if (occ <= 2)
593         {
594             if (occ == 2)
595             {
596                 memcpy(op, &(codep->firstchar), 2);
597                 op += 2;
598                 occ -= 2;
599                 goto after_loop;
600             }
601             goto too_short_buffer;
602         }
603 
604         memcpy(op, &(codep->firstchar), 2);
605         op += 2;
606         occ -= 2;
607         goto begin; /* we can save the comparison occ > 0 */
608     }
609 
610     if (len == 3)
611     {
612         if (occ <= 3)
613         {
614             if (occ == 3)
615             {
616                 op[0] = codep->firstchar;
617                 op[1] = codep->next->value;
618                 op[2] = codep->value;
619                 op += 3;
620                 occ -= 3;
621                 goto after_loop;
622             }
623             goto too_short_buffer;
624         }
625 
626         op[0] = codep->firstchar;
627         op[1] = codep->next->value;
628         op[2] = codep->value;
629         op += 3;
630         occ -= 3;
631         goto begin; /* we can save the comparison occ > 0 */
632     }
633 
634     if (len > occ)
635     {
636         goto too_short_buffer;
637     }
638 
639     if (codep->repeated)
640     {
641         memset(op, codep->value, len);
642         op += len;
643         occ -= len;
644         if (occ == 0)
645             goto after_loop;
646         goto begin;
647     }
648 
649     uint8_t *tp = op + len;
650 
651     assert(len >= 4);
652 
653     *--tp = codep->value;
654     codep = codep->next;
655     *--tp = codep->value;
656     codep = codep->next;
657     *--tp = codep->value;
658     codep = codep->next;
659     *--tp = codep->value;
660     if (tp > op)
661     {
662         do
663         {
664             codep = codep->next;
665             *--tp = codep->value;
666         } while (tp > op);
667     }
668 
669     assert(occ >= len);
670     op += len;
671     occ -= len;
672     if (occ == 0)
673         goto after_loop;
674     goto begin;
675 }
676 
677 code_clear:
678 {
679     free_entp = dec_codetab + CODE_FIRST;
680     nbits = BITS_MIN;
681     nbitsmask = MAXCODE(BITS_MIN);
682     maxcodep = dec_codetab + nbitsmask - 1;
683     do
684     {
685         GetNextCodeLZW();
686     } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
687     if (code == CODE_EOI)
688         goto after_loop;
689     if (code > CODE_EOI)
690     {
691         goto error_code;
692     }
693     *op++ = (uint8_t)code;
694     occ--;
695     oldcodep = dec_codetab + code;
696     if (occ == 0)
697         goto after_loop;
698     goto begin;
699 }
700 }
701 
702 too_short_buffer:
703 {
704     /*
705      * String is too long for decode buffer,
706      * locate portion that will fit, copy to
707      * the decode buffer, and setup restart
708      * logic for the next decoding call.
709      */
710     sp->dec_codep = codep;
711     do
712     {
713         codep = codep->next;
714     } while (codep->length > occ);
715 
716     sp->dec_restart = occ;
717     uint8_t *tp = op + occ;
718     do
719     {
720         *--tp = codep->value;
721         codep = codep->next;
722     } while (--occ);
723 }
724 
725 after_loop:
726     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
727     tif->tif_rawcp = (uint8_t *)bp;
728     sp->old_tif_rawcc = tif->tif_rawcc;
729     sp->dec_bitsleft = dec_bitsleft;
730     sp->lzw_nbits = (unsigned short)nbits;
731     sp->lzw_nextdata = nextdata;
732     sp->lzw_nextbits = nextbits;
733     sp->dec_nbitsmask = nbitsmask;
734     sp->dec_oldcodep = oldcodep;
735     sp->dec_free_entp = free_entp;
736     sp->dec_maxcodep = maxcodep;
737 
738     if (occ > 0)
739     {
740         TIFFErrorExtR(tif, module,
741                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
742                       " bytes)",
743                       tif->tif_row, (uint64_t)occ);
744         return (0);
745     }
746     return (1);
747 
748 no_eoi:
749     sp->read_error = 1;
750     TIFFErrorExtR(tif, module,
751                   "LZWDecode: Strip %" PRIu32 " not terminated with EOI code",
752                   tif->tif_curstrip);
753     return 0;
754 error_code:
755     sp->read_error = 1;
756     TIFFErrorExtR(tif, tif->tif_name, "Using code not yet in table");
757     return 0;
758 }
759 
760 #ifdef LZW_COMPAT
761 
762 /*
763  * This check shouldn't be necessary because each
764  * strip is suppose to be terminated with CODE_EOI.
765  */
766 #define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)                    \
767     {                                                                          \
768         if (dec_bitsleft < (uint64_t)nbits)                                    \
769         {                                                                      \
770             TIFFWarningExtR(_tif, module,                                      \
771                             "LZWDecode: Strip %" PRIu32                        \
772                             " not terminated with EOI code",                   \
773                             _tif->tif_curstrip);                               \
774             _code = CODE_EOI;                                                  \
775         }                                                                      \
776         else                                                                   \
777         {                                                                      \
778             _get(_sp, _bp, _code);                                             \
779             dec_bitsleft -= nbits;                                             \
780         }                                                                      \
781     }
782 
783 /*
784  * Decode a "hunk of data" for old images.
785  */
786 #define GetNextCodeCompat(sp, bp, code)                                        \
787     {                                                                          \
788         nextdata |= (unsigned long)*(bp)++ << nextbits;                        \
789         nextbits += 8;                                                         \
790         if (nextbits < nbits)                                                  \
791         {                                                                      \
792             nextdata |= (unsigned long)*(bp)++ << nextbits;                    \
793             nextbits += 8;                                                     \
794         }                                                                      \
795         code = (hcode_t)(nextdata & nbitsmask);                                \
796         nextdata >>= nbits;                                                    \
797         nextbits -= nbits;                                                     \
798     }
799 
LZWDecodeCompat(TIFF * tif,uint8_t * op0,tmsize_t occ0,uint16_t s)800 static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
801 {
802     static const char module[] = "LZWDecodeCompat";
803     LZWCodecState *sp = DecoderState(tif);
804     uint8_t *op = (uint8_t *)op0;
805     tmsize_t occ = occ0;
806     uint8_t *tp;
807     uint8_t *bp;
808     int code, nbits;
809     int len;
810     long nextbits, nbitsmask;
811     WordType nextdata;
812     code_t *codep, *free_entp, *maxcodep, *oldcodep;
813 
814     (void)s;
815     assert(sp != NULL);
816 
817     /*
818      * Restart interrupted output operation.
819      */
820     if (sp->dec_restart)
821     {
822         tmsize_t residue;
823 
824         codep = sp->dec_codep;
825         residue = codep->length - sp->dec_restart;
826         if (residue > occ)
827         {
828             /*
829              * Residue from previous decode is sufficient
830              * to satisfy decode request.  Skip to the
831              * start of the decoded string, place decoded
832              * values in the output buffer, and return.
833              */
834             sp->dec_restart += occ;
835             do
836             {
837                 codep = codep->next;
838             } while (--residue > occ);
839             tp = op + occ;
840             do
841             {
842                 *--tp = codep->value;
843                 codep = codep->next;
844             } while (--occ);
845             return (1);
846         }
847         /*
848          * Residue satisfies only part of the decode request.
849          */
850         op += residue;
851         occ -= residue;
852         tp = op;
853         do
854         {
855             *--tp = codep->value;
856             codep = codep->next;
857         } while (--residue);
858         sp->dec_restart = 0;
859     }
860 
861     bp = (uint8_t *)tif->tif_rawcp;
862 
863     sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
864     uint64_t dec_bitsleft = sp->dec_bitsleft;
865 
866     nbits = sp->lzw_nbits;
867     nextdata = sp->lzw_nextdata;
868     nextbits = sp->lzw_nextbits;
869     nbitsmask = sp->dec_nbitsmask;
870     oldcodep = sp->dec_oldcodep;
871     free_entp = sp->dec_free_entp;
872     maxcodep = sp->dec_maxcodep;
873 
874     while (occ > 0)
875     {
876         NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
877         if (code == CODE_EOI)
878             break;
879         if (code == CODE_CLEAR)
880         {
881             do
882             {
883                 free_entp = sp->dec_codetab + CODE_FIRST;
884                 _TIFFmemset(free_entp, 0,
885                             (CSIZE - CODE_FIRST) * sizeof(code_t));
886                 nbits = BITS_MIN;
887                 nbitsmask = MAXCODE(BITS_MIN);
888                 maxcodep = sp->dec_codetab + nbitsmask;
889                 NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
890             } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
891             if (code == CODE_EOI)
892                 break;
893             if (code > CODE_CLEAR)
894             {
895                 TIFFErrorExtR(
896                     tif, tif->tif_name,
897                     "LZWDecode: Corrupted LZW table at scanline %" PRIu32,
898                     tif->tif_row);
899                 return (0);
900             }
901             *op++ = (uint8_t)code;
902             occ--;
903             oldcodep = sp->dec_codetab + code;
904             continue;
905         }
906         codep = sp->dec_codetab + code;
907 
908         /*
909          * Add the new entry to the code table.
910          */
911         if (free_entp < &sp->dec_codetab[0] ||
912             free_entp >= &sp->dec_codetab[CSIZE])
913         {
914             TIFFErrorExtR(tif, module,
915                           "Corrupted LZW table at scanline %" PRIu32,
916                           tif->tif_row);
917             return (0);
918         }
919 
920         free_entp->next = oldcodep;
921         if (free_entp->next < &sp->dec_codetab[0] ||
922             free_entp->next >= &sp->dec_codetab[CSIZE])
923         {
924             TIFFErrorExtR(tif, module,
925                           "Corrupted LZW table at scanline %" PRIu32,
926                           tif->tif_row);
927             return (0);
928         }
929         free_entp->firstchar = free_entp->next->firstchar;
930         free_entp->length = free_entp->next->length + 1;
931         free_entp->value =
932             (codep < free_entp) ? codep->firstchar : free_entp->firstchar;
933         if (++free_entp > maxcodep)
934         {
935             if (++nbits > BITS_MAX) /* should not happen */
936                 nbits = BITS_MAX;
937             nbitsmask = MAXCODE(nbits);
938             maxcodep = sp->dec_codetab + nbitsmask;
939         }
940         oldcodep = codep;
941         if (code >= 256)
942         {
943             /*
944              * Code maps to a string, copy string
945              * value to output (written in reverse).
946              */
947             if (codep->length == 0)
948             {
949                 TIFFErrorExtR(
950                     tif, module,
951                     "Wrong length of decoded "
952                     "string: data probably corrupted at scanline %" PRIu32,
953                     tif->tif_row);
954                 return (0);
955             }
956             if (codep->length > occ)
957             {
958                 /*
959                  * String is too long for decode buffer,
960                  * locate portion that will fit, copy to
961                  * the decode buffer, and setup restart
962                  * logic for the next decoding call.
963                  */
964                 sp->dec_codep = codep;
965                 do
966                 {
967                     codep = codep->next;
968                 } while (codep->length > occ);
969                 sp->dec_restart = occ;
970                 tp = op + occ;
971                 do
972                 {
973                     *--tp = codep->value;
974                     codep = codep->next;
975                 } while (--occ);
976                 break;
977             }
978             len = codep->length;
979             tp = op + len;
980             do
981             {
982                 *--tp = codep->value;
983                 codep = codep->next;
984             } while (codep && tp > op);
985             assert(occ >= len);
986             op += len;
987             occ -= len;
988         }
989         else
990         {
991             *op++ = (uint8_t)code;
992             occ--;
993         }
994     }
995 
996     tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
997     tif->tif_rawcp = (uint8_t *)bp;
998 
999     sp->old_tif_rawcc = tif->tif_rawcc;
1000     sp->dec_bitsleft = dec_bitsleft;
1001 
1002     sp->lzw_nbits = (unsigned short)nbits;
1003     sp->lzw_nextdata = nextdata;
1004     sp->lzw_nextbits = nextbits;
1005     sp->dec_nbitsmask = nbitsmask;
1006     sp->dec_oldcodep = oldcodep;
1007     sp->dec_free_entp = free_entp;
1008     sp->dec_maxcodep = maxcodep;
1009 
1010     if (occ > 0)
1011     {
1012         TIFFErrorExtR(tif, module,
1013                       "Not enough data at scanline %" PRIu32 " (short %" PRIu64
1014                       " bytes)",
1015                       tif->tif_row, (uint64_t)occ);
1016         return (0);
1017     }
1018     return (1);
1019 }
1020 #endif /* LZW_COMPAT */
1021 
1022 /*
1023  * LZW Encoding.
1024  */
1025 
LZWSetupEncode(TIFF * tif)1026 static int LZWSetupEncode(TIFF *tif)
1027 {
1028     static const char module[] = "LZWSetupEncode";
1029     LZWCodecState *sp = EncoderState(tif);
1030 
1031     assert(sp != NULL);
1032     sp->enc_hashtab = (hash_t *)_TIFFmallocExt(tif, HSIZE * sizeof(hash_t));
1033     if (sp->enc_hashtab == NULL)
1034     {
1035         TIFFErrorExtR(tif, module, "No space for LZW hash table");
1036         return (0);
1037     }
1038     return (1);
1039 }
1040 
1041 /*
1042  * Reset encoding state at the start of a strip.
1043  */
LZWPreEncode(TIFF * tif,uint16_t s)1044 static int LZWPreEncode(TIFF *tif, uint16_t s)
1045 {
1046     LZWCodecState *sp = EncoderState(tif);
1047 
1048     (void)s;
1049     assert(sp != NULL);
1050 
1051     if (sp->enc_hashtab == NULL)
1052     {
1053         tif->tif_setupencode(tif);
1054     }
1055 
1056     sp->lzw_nbits = BITS_MIN;
1057     sp->lzw_maxcode = MAXCODE(BITS_MIN);
1058     sp->lzw_free_ent = CODE_FIRST;
1059     sp->lzw_nextbits = 0;
1060     sp->lzw_nextdata = 0;
1061     sp->enc_checkpoint = CHECK_GAP;
1062     sp->enc_ratio = 0;
1063     sp->enc_incount = 0;
1064     sp->enc_outcount = 0;
1065     /*
1066      * The 4 here insures there is space for 2 max-sized
1067      * codes in LZWEncode and LZWPostDecode.
1068      */
1069     sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize - 1 - 4;
1070     cl_hash(sp);                   /* clear hash table */
1071     sp->enc_oldcode = (hcode_t)-1; /* generates CODE_CLEAR in LZWEncode */
1072     return (1);
1073 }
1074 
1075 #define CALCRATIO(sp, rat)                                                     \
1076     {                                                                          \
1077         if (incount > 0x007fffff)                                              \
1078         { /* NB: shift will overflow */                                        \
1079             rat = outcount >> 8;                                               \
1080             rat = (rat == 0 ? 0x7fffffff : incount / rat);                     \
1081         }                                                                      \
1082         else                                                                   \
1083             rat = (incount << 8) / outcount;                                   \
1084     }
1085 
1086 /* Explicit 0xff masking to make icc -check=conversions happy */
1087 #define PutNextCode(op, c)                                                     \
1088     {                                                                          \
1089         nextdata = (nextdata << nbits) | c;                                    \
1090         nextbits += nbits;                                                     \
1091         *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);          \
1092         nextbits -= 8;                                                         \
1093         if (nextbits >= 8)                                                     \
1094         {                                                                      \
1095             *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);      \
1096             nextbits -= 8;                                                     \
1097         }                                                                      \
1098         outcount += nbits;                                                     \
1099     }
1100 
1101 /*
1102  * Encode a chunk of pixels.
1103  *
1104  * Uses an open addressing double hashing (no chaining) on the
1105  * prefix code/next character combination.  We do a variant of
1106  * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
1107  * relatively-prime secondary probe.  Here, the modular division
1108  * first probe is gives way to a faster exclusive-or manipulation.
1109  * Also do block compression with an adaptive reset, whereby the
1110  * code table is cleared when the compression ratio decreases,
1111  * but after the table fills.  The variable-length output codes
1112  * are re-sized at this point, and a CODE_CLEAR is generated
1113  * for the decoder.
1114  */
LZWEncode(TIFF * tif,uint8_t * bp,tmsize_t cc,uint16_t s)1115 static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1116 {
1117     register LZWCodecState *sp = EncoderState(tif);
1118     register long fcode;
1119     register hash_t *hp;
1120     register int h, c;
1121     hcode_t ent;
1122     long disp;
1123     tmsize_t incount, outcount, checkpoint;
1124     WordType nextdata;
1125     long nextbits;
1126     int free_ent, maxcode, nbits;
1127     uint8_t *op;
1128     uint8_t *limit;
1129 
1130     (void)s;
1131     if (sp == NULL)
1132         return (0);
1133 
1134     assert(sp->enc_hashtab != NULL);
1135 
1136     /*
1137      * Load local state.
1138      */
1139     incount = sp->enc_incount;
1140     outcount = sp->enc_outcount;
1141     checkpoint = sp->enc_checkpoint;
1142     nextdata = sp->lzw_nextdata;
1143     nextbits = sp->lzw_nextbits;
1144     free_ent = sp->lzw_free_ent;
1145     maxcode = sp->lzw_maxcode;
1146     nbits = sp->lzw_nbits;
1147     op = tif->tif_rawcp;
1148     limit = sp->enc_rawlimit;
1149     ent = (hcode_t)sp->enc_oldcode;
1150 
1151     if (ent == (hcode_t)-1 && cc > 0)
1152     {
1153         /*
1154          * NB: This is safe because it can only happen
1155          *     at the start of a strip where we know there
1156          *     is space in the data buffer.
1157          */
1158         PutNextCode(op, CODE_CLEAR);
1159         ent = *bp++;
1160         cc--;
1161         incount++;
1162     }
1163     while (cc > 0)
1164     {
1165         c = *bp++;
1166         cc--;
1167         incount++;
1168         fcode = ((long)c << BITS_MAX) + ent;
1169         h = (c << HSHIFT) ^ ent; /* xor hashing */
1170 #ifdef _WINDOWS
1171         /*
1172          * Check hash index for an overflow.
1173          */
1174         if (h >= HSIZE)
1175             h -= HSIZE;
1176 #endif
1177         hp = &sp->enc_hashtab[h];
1178         if (hp->hash == fcode)
1179         {
1180             ent = hp->code;
1181             continue;
1182         }
1183         if (hp->hash >= 0)
1184         {
1185             /*
1186              * Primary hash failed, check secondary hash.
1187              */
1188             disp = HSIZE - h;
1189             if (h == 0)
1190                 disp = 1;
1191             do
1192             {
1193                 /*
1194                  * Avoid pointer arithmetic because of
1195                  * wraparound problems with segments.
1196                  */
1197                 if ((h -= disp) < 0)
1198                     h += HSIZE;
1199                 hp = &sp->enc_hashtab[h];
1200                 if (hp->hash == fcode)
1201                 {
1202                     ent = hp->code;
1203                     goto hit;
1204                 }
1205             } while (hp->hash >= 0);
1206         }
1207         /*
1208          * New entry, emit code and add to table.
1209          */
1210         /*
1211          * Verify there is space in the buffer for the code
1212          * and any potential Clear code that might be emitted
1213          * below.  The value of limit is setup so that there
1214          * are at least 4 bytes free--room for 2 codes.
1215          */
1216         if (op > limit)
1217         {
1218             tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1219             if (!TIFFFlushData1(tif))
1220                 return 0;
1221             op = tif->tif_rawdata;
1222         }
1223         PutNextCode(op, ent);
1224         ent = (hcode_t)c;
1225         hp->code = (hcode_t)(free_ent++);
1226         hp->hash = fcode;
1227         if (free_ent == CODE_MAX - 1)
1228         {
1229             /* table is full, emit clear code and reset */
1230             cl_hash(sp);
1231             sp->enc_ratio = 0;
1232             incount = 0;
1233             outcount = 0;
1234             free_ent = CODE_FIRST;
1235             PutNextCode(op, CODE_CLEAR);
1236             nbits = BITS_MIN;
1237             maxcode = MAXCODE(BITS_MIN);
1238         }
1239         else
1240         {
1241             /*
1242              * If the next entry is going to be too big for
1243              * the code size, then increase it, if possible.
1244              */
1245             if (free_ent > maxcode)
1246             {
1247                 nbits++;
1248                 assert(nbits <= BITS_MAX);
1249                 maxcode = (int)MAXCODE(nbits);
1250             }
1251             else if (incount >= checkpoint)
1252             {
1253                 tmsize_t rat;
1254                 /*
1255                  * Check compression ratio and, if things seem
1256                  * to be slipping, clear the hash table and
1257                  * reset state.  The compression ratio is a
1258                  * 24+8-bit fractional number.
1259                  */
1260                 checkpoint = incount + CHECK_GAP;
1261                 CALCRATIO(sp, rat);
1262                 if (rat <= sp->enc_ratio)
1263                 {
1264                     cl_hash(sp);
1265                     sp->enc_ratio = 0;
1266                     incount = 0;
1267                     outcount = 0;
1268                     free_ent = CODE_FIRST;
1269                     PutNextCode(op, CODE_CLEAR);
1270                     nbits = BITS_MIN;
1271                     maxcode = MAXCODE(BITS_MIN);
1272                 }
1273                 else
1274                     sp->enc_ratio = rat;
1275             }
1276         }
1277     hit:;
1278     }
1279 
1280     /*
1281      * Restore global state.
1282      */
1283     sp->enc_incount = incount;
1284     sp->enc_outcount = outcount;
1285     sp->enc_checkpoint = checkpoint;
1286     sp->enc_oldcode = ent;
1287     sp->lzw_nextdata = nextdata;
1288     sp->lzw_nextbits = nextbits;
1289     sp->lzw_free_ent = (unsigned short)free_ent;
1290     sp->lzw_maxcode = (unsigned short)maxcode;
1291     sp->lzw_nbits = (unsigned short)nbits;
1292     tif->tif_rawcp = op;
1293     return (1);
1294 }
1295 
1296 /*
1297  * Finish off an encoded strip by flushing the last
1298  * string and tacking on an End Of Information code.
1299  */
LZWPostEncode(TIFF * tif)1300 static int LZWPostEncode(TIFF *tif)
1301 {
1302     register LZWCodecState *sp = EncoderState(tif);
1303     uint8_t *op = tif->tif_rawcp;
1304     long nextbits = sp->lzw_nextbits;
1305     WordType nextdata = sp->lzw_nextdata;
1306     tmsize_t outcount = sp->enc_outcount;
1307     int nbits = sp->lzw_nbits;
1308 
1309     if (op > sp->enc_rawlimit)
1310     {
1311         tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1312         if (!TIFFFlushData1(tif))
1313             return 0;
1314         op = tif->tif_rawdata;
1315     }
1316     if (sp->enc_oldcode != (hcode_t)-1)
1317     {
1318         int free_ent = sp->lzw_free_ent;
1319 
1320         PutNextCode(op, sp->enc_oldcode);
1321         sp->enc_oldcode = (hcode_t)-1;
1322         free_ent++;
1323 
1324         if (free_ent == CODE_MAX - 1)
1325         {
1326             /* table is full, emit clear code and reset */
1327             outcount = 0;
1328             PutNextCode(op, CODE_CLEAR);
1329             nbits = BITS_MIN;
1330         }
1331         else
1332         {
1333             /*
1334              * If the next entry is going to be too big for
1335              * the code size, then increase it, if possible.
1336              */
1337             if (free_ent > sp->lzw_maxcode)
1338             {
1339                 nbits++;
1340                 assert(nbits <= BITS_MAX);
1341             }
1342         }
1343     }
1344     PutNextCode(op, CODE_EOI);
1345     /* Explicit 0xff masking to make icc -check=conversions happy */
1346     if (nextbits > 0)
1347         *op++ = (unsigned char)((nextdata << (8 - nextbits)) & 0xff);
1348     tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1349     (void)outcount;
1350     return (1);
1351 }
1352 
1353 /*
1354  * Reset encoding hash table.
1355  */
cl_hash(LZWCodecState * sp)1356 static void cl_hash(LZWCodecState *sp)
1357 {
1358     register hash_t *hp = &sp->enc_hashtab[HSIZE - 1];
1359     register long i = HSIZE - 8;
1360 
1361     do
1362     {
1363         i -= 8;
1364         hp[-7].hash = -1;
1365         hp[-6].hash = -1;
1366         hp[-5].hash = -1;
1367         hp[-4].hash = -1;
1368         hp[-3].hash = -1;
1369         hp[-2].hash = -1;
1370         hp[-1].hash = -1;
1371         hp[0].hash = -1;
1372         hp -= 8;
1373     } while (i >= 0);
1374     for (i += 8; i > 0; i--, hp--)
1375         hp->hash = -1;
1376 }
1377 
LZWCleanup(TIFF * tif)1378 static void LZWCleanup(TIFF *tif)
1379 {
1380     (void)TIFFPredictorCleanup(tif);
1381 
1382     assert(tif->tif_data != 0);
1383 
1384     if (DecoderState(tif)->dec_codetab)
1385         _TIFFfreeExt(tif, DecoderState(tif)->dec_codetab);
1386 
1387     if (EncoderState(tif)->enc_hashtab)
1388         _TIFFfreeExt(tif, EncoderState(tif)->enc_hashtab);
1389 
1390     _TIFFfreeExt(tif, tif->tif_data);
1391     tif->tif_data = NULL;
1392 
1393     _TIFFSetDefaultCompressionState(tif);
1394 }
1395 
TIFFInitLZW(TIFF * tif,int scheme)1396 int TIFFInitLZW(TIFF *tif, int scheme)
1397 {
1398     static const char module[] = "TIFFInitLZW";
1399     (void)scheme;
1400     assert(scheme == COMPRESSION_LZW);
1401     /*
1402      * Allocate state block so tag methods have storage to record values.
1403      */
1404     tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
1405     if (tif->tif_data == NULL)
1406         goto bad;
1407     DecoderState(tif)->dec_codetab = NULL;
1408     DecoderState(tif)->dec_decode = NULL;
1409     EncoderState(tif)->enc_hashtab = NULL;
1410     LZWState(tif)->rw_mode = tif->tif_mode;
1411 
1412     /*
1413      * Install codec methods.
1414      */
1415     tif->tif_fixuptags = LZWFixupTags;
1416     tif->tif_setupdecode = LZWSetupDecode;
1417     tif->tif_predecode = LZWPreDecode;
1418     tif->tif_decoderow = LZWDecode;
1419     tif->tif_decodestrip = LZWDecode;
1420     tif->tif_decodetile = LZWDecode;
1421     tif->tif_setupencode = LZWSetupEncode;
1422     tif->tif_preencode = LZWPreEncode;
1423     tif->tif_postencode = LZWPostEncode;
1424     tif->tif_encoderow = LZWEncode;
1425     tif->tif_encodestrip = LZWEncode;
1426     tif->tif_encodetile = LZWEncode;
1427     tif->tif_cleanup = LZWCleanup;
1428     /*
1429      * Setup predictor setup.
1430      */
1431     (void)TIFFPredictorInit(tif);
1432     return (1);
1433 bad:
1434     TIFFErrorExtR(tif, module, "No space for LZW state block");
1435     return (0);
1436 }
1437 
1438 /*
1439  * Copyright (c) 1985, 1986 The Regents of the University of California.
1440  * All rights reserved.
1441  *
1442  * This code is derived from software contributed to Berkeley by
1443  * James A. Woods, derived from original work by Spencer Thomas
1444  * and Joseph Orost.
1445  *
1446  * Redistribution and use in source and binary forms are permitted
1447  * provided that the above copyright notice and this paragraph are
1448  * duplicated in all such forms and that any documentation,
1449  * advertising materials, and other materials related to such
1450  * distribution and use acknowledge that the software was developed
1451  * by the University of California, Berkeley.  The name of the
1452  * University may not be used to endorse or promote products derived
1453  * from this software without specific prior written permission.
1454  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1455  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1456  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1457  */
1458 #endif /* LZW_SUPPORT */
1459