Coverage Report

Created: 2026-07-24 07:44

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