• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

OSGeo / gdal / 13836648005

13 Mar 2025 02:09PM UTC coverage: 70.436% (-0.01%) from 70.446%
13836648005

push

github

web-flow
New Transform type: Homography (#11949)

Add new transform type, Homography.
Add functions to compute homography from a list of GCPs.
Add functions to serialize and deserialize a homography
Automatically select homography transfrom when there are 4 or 5 GCPs present.

Fixes #11940

231 of 274 new or added lines in 2 files covered. (84.31%)

16257 existing lines in 42 files now uncovered.

553736 of 786159 relevant lines covered (70.44%)

221595.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.26
/frmts/gtiff/libtiff/tif_lzw.c
1
/*
2
 * Copyright (c) 1988-1997 Sam Leffler
3
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4
 * Copyright (c) 2022 Even Rouault
5
 *
6
 * Permission to use, copy, modify, distribute, and sell this software and
7
 * its documentation for any purpose is hereby granted without fee, provided
8
 * that (i) the above copyright notices and this permission notice appear in
9
 * all copies of the software and related documentation, and (ii) the names of
10
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
11
 * publicity relating to the software without the specific, prior written
12
 * permission of Sam Leffler and Silicon Graphics.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
15
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
16
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
17
 *
18
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
19
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
20
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
21
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
22
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
23
 * OF THIS SOFTWARE.
24
 */
25

26
#include "tiffiop.h"
27
#ifdef LZW_SUPPORT
28
/*
29
 * TIFF Library.
30
 * Rev 5.0 Lempel-Ziv & Welch Compression Support
31
 *
32
 * This code is derived from the compress program whose code is
33
 * derived from software contributed to Berkeley by James A. Woods,
34
 * derived from original work by Spencer Thomas and Joseph Orost.
35
 *
36
 * The original Berkeley copyright notice appears below in its entirety.
37
 */
38
#include "tif_predict.h"
39

40
#include <stdbool.h>
41
#include <stdio.h>
42
#include <stdlib.h>
43

44
/* Select the plausible largest natural integer type for the architecture */
45
#define SIZEOF_WORDTYPE SIZEOF_SIZE_T
46
typedef size_t WordType;
47

48
/*
49
 * NB: The 5.0 spec describes a different algorithm than Aldus
50
 *     implements.  Specifically, Aldus does code length transitions
51
 *     one code earlier than should be done (for real LZW).
52
 *     Earlier versions of this library implemented the correct
53
 *     LZW algorithm, but emitted codes in a bit order opposite
54
 *     to the TIFF spec.  Thus, to maintain compatibility w/ Aldus
55
 *     we interpret MSB-LSB ordered codes to be images written w/
56
 *     old versions of this library, but otherwise adhere to the
57
 *     Aldus "off by one" algorithm.
58
 *
59
 * Future revisions to the TIFF spec are expected to "clarify this issue".
60
 */
61
#define LZW_COMPAT /* include backwards compatibility code */
62

63
#define MAXCODE(n) ((1L << (n)) - 1)
64
/*
65
 * The TIFF spec specifies that encoded bit
66
 * strings range from 9 to 12 bits.
67
 */
68
#define BITS_MIN 9  /* start with 9 bits */
69
#define BITS_MAX 12 /* max of 12 bit strings */
70
/* predefined codes */
71
#define CODE_CLEAR 256 /* code to clear string table */
72
#define CODE_EOI 257   /* end-of-information code */
73
#define CODE_FIRST 258 /* first free code entry */
74
#define CODE_MAX MAXCODE(BITS_MAX)
75
#define HSIZE 9001L /* 91% occupancy */
76
#define HSHIFT (13 - 8)
77
#ifdef LZW_COMPAT
78
/* NB: +1024 is for compatibility with old files */
79
#define CSIZE (MAXCODE(BITS_MAX) + 1024L)
80
#else
81
#define CSIZE (MAXCODE(BITS_MAX) + 1L)
82
#endif
83

84
/*
85
 * State block for each open TIFF file using LZW
86
 * compression/decompression.  Note that the predictor
87
 * state block must be first in this data structure.
88
 */
89
typedef struct
90
{
91
    TIFFPredictorState predict; /* predictor super class */
92

93
    unsigned short nbits;    /* # of bits/code */
94
    unsigned short maxcode;  /* maximum code for lzw_nbits */
95
    unsigned short free_ent; /* next free entry in hash table */
96
    WordType nextdata;       /* next bits of i/o */
97
    long nextbits;           /* # of valid bits in lzw_nextdata */
98

99
    int rw_mode; /* preserve rw_mode from init */
100
} LZWBaseState;
101

102
#define lzw_nbits base.nbits
103
#define lzw_maxcode base.maxcode
104
#define lzw_free_ent base.free_ent
105
#define lzw_nextdata base.nextdata
106
#define lzw_nextbits base.nextbits
107

108
/*
109
 * Encoding-specific state.
110
 */
111
typedef uint16_t hcode_t; /* codes fit in 16 bits */
112
typedef struct
113
{
114
    long hash;
115
    hcode_t code;
116
} hash_t;
117

118
/*
119
 * Decoding-specific state.
120
 */
121
typedef struct code_ent
122
{
123
    struct code_ent *next;
124
    unsigned short length; /* string len, including this token */
125
    /* firstchar should be placed immediately before value in this structure */
126
    unsigned char firstchar; /* first token of string */
127
    unsigned char value;     /* data value */
128
    bool repeated;
129
} code_t;
130

131
typedef int (*decodeFunc)(TIFF *, uint8_t *, tmsize_t, uint16_t);
132

133
typedef struct
134
{
135
    LZWBaseState base;
136

137
    /* Decoding specific data */
138
    long dec_nbitsmask;     /* lzw_nbits 1 bits, right adjusted */
139
    tmsize_t dec_restart;   /* restart count */
140
    uint64_t dec_bitsleft;  /* available bits in raw data */
141
    tmsize_t old_tif_rawcc; /* value of tif_rawcc at the end of the previous
142
                               TIFLZWDecode() call */
143
    decodeFunc dec_decode;  /* regular or backwards compatible */
144
    code_t *dec_codep;      /* current recognized code */
145
    code_t *dec_oldcodep;   /* previously recognized code */
146
    code_t *dec_free_entp;  /* next free entry */
147
    code_t *dec_maxcodep;   /* max available entry */
148
    code_t *dec_codetab;    /* kept separate for small machines */
149
    int read_error; /* whether a read error has occurred, and which should cause
150
                       further reads in the same strip/tile to be aborted */
151

152
    /* Encoding specific data */
153
    int enc_oldcode;         /* last code encountered */
154
    tmsize_t enc_checkpoint; /* point at which to clear table */
155
#define CHECK_GAP 10000      /* enc_ratio check interval */
156
    tmsize_t enc_ratio;      /* current compression ratio */
157
    tmsize_t enc_incount;    /* (input) data bytes encoded */
158
    tmsize_t enc_outcount;   /* encoded (output) bytes */
159
    uint8_t *enc_rawlimit;   /* bound on tif_rawdata buffer */
160
    hash_t *enc_hashtab;     /* kept separate for small machines */
161
} LZWCodecState;
162

163
#define LZWState(tif) ((LZWBaseState *)(tif)->tif_data)
164
#define LZWDecoderState(tif) ((LZWCodecState *)LZWState(tif))
165
#define LZWEncoderState(tif) ((LZWCodecState *)LZWState(tif))
166

167
static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
168
#ifdef LZW_COMPAT
169
static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s);
170
#endif
171

172
/*
173
 * LZW Decoder.
174
 */
175

176
static int LZWFixupTags(TIFF *tif)
4,394✔
177
{
178
    (void)tif;
179
    return (1);
4,394✔
180
}
181

182
static int LZWSetupDecode(TIFF *tif)
2,492✔
183
{
184
    static const char module[] = "LZWSetupDecode";
185
    LZWCodecState *sp = LZWDecoderState(tif);
2,492✔
186
    int code;
187

188
    if (sp == NULL)
2,492✔
189
    {
190
        /*
191
         * Allocate state block so tag methods have storage to record
192
         * values.
193
         */
194
        tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
×
195
        if (tif->tif_data == NULL)
×
196
        {
197
            TIFFErrorExtR(tif, module, "No space for LZW state block");
×
198
            return (0);
×
199
        }
200

201
        sp = LZWDecoderState(tif);
×
202
        sp->dec_codetab = NULL;
×
203
        sp->dec_decode = NULL;
×
204

205
        /*
206
         * Setup predictor setup.
207
         */
208
        (void)TIFFPredictorInit(tif);
×
209
    }
210

211
    if (sp->dec_codetab == NULL)
2,490✔
212
    {
213
        sp->dec_codetab = (code_t *)_TIFFmallocExt(tif, CSIZE * sizeof(code_t));
2,488✔
214
        if (sp->dec_codetab == NULL)
2,490✔
215
        {
UNCOV
216
            TIFFErrorExtR(tif, module, "No space for LZW code table");
×
217
            return (0);
×
218
        }
219
        /*
220
         * Pre-load the table.
221
         */
222
        code = 255;
2,491✔
223
        do
19,125✔
224
        {
225
            sp->dec_codetab[code].firstchar = (unsigned char)code;
635,919✔
226
            sp->dec_codetab[code].value = (unsigned char)code;
635,919✔
227
            sp->dec_codetab[code].repeated = true;
635,919✔
228
            sp->dec_codetab[code].length = 1;
635,919✔
229
            sp->dec_codetab[code].next = NULL;
635,919✔
230
        } while (code--);
635,919✔
231
        /*
232
         * Zero-out the unused entries  */
233
        /* Silence false positive */
234
        /* coverity[overrun-buffer-arg] */
235
        memset(&sp->dec_codetab[CODE_CLEAR], 0,
2,491✔
236
               (CODE_FIRST - CODE_CLEAR) * sizeof(code_t));
237
    }
238
    return (1);
2,493✔
239
}
240

241
/*
242
 * Setup state for decoding a strip.
243
 */
244
static int LZWPreDecode(TIFF *tif, uint16_t s)
5,736✔
245
{
246
    static const char module[] = "LZWPreDecode";
247
    LZWCodecState *sp = LZWDecoderState(tif);
5,736✔
248

249
    (void)s;
250
    assert(sp != NULL);
5,736✔
251
    if (sp->dec_codetab == NULL)
5,736✔
252
    {
253
        tif->tif_setupdecode(tif);
108✔
254
        if (sp->dec_codetab == NULL)
108✔
255
            return (0);
×
256
    }
257

258
    /*
259
     * Check for old bit-reversed codes.
260
     */
261
    if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 &&
5,736✔
262
        (tif->tif_rawdata[1] & 0x1))
104✔
263
    {
264
#ifdef LZW_COMPAT
265
        if (!sp->dec_decode)
104✔
266
        {
267
            TIFFWarningExtR(tif, module, "Old-style LZW codes, convert file");
3✔
268
            /*
269
             * Override default decoding methods with
270
             * ones that deal with the old coding.
271
             * Otherwise the predictor versions set
272
             * above will call the compatibility routines
273
             * through the dec_decode method.
274
             */
275
            tif->tif_decoderow = LZWDecodeCompat;
3✔
276
            tif->tif_decodestrip = LZWDecodeCompat;
3✔
277
            tif->tif_decodetile = LZWDecodeCompat;
3✔
278
            /*
279
             * If doing horizontal differencing, must
280
             * re-setup the predictor logic since we
281
             * switched the basic decoder methods...
282
             */
283
            (*tif->tif_setupdecode)(tif);
3✔
284
            sp->dec_decode = LZWDecodeCompat;
3✔
285
        }
286
        sp->lzw_maxcode = MAXCODE(BITS_MIN);
104✔
287
#else  /* !LZW_COMPAT */
288
        if (!sp->dec_decode)
289
        {
290
            TIFFErrorExtR(tif, module, "Old-style LZW codes not supported");
291
            sp->dec_decode = LZWDecode;
292
        }
293
        return (0);
294
#endif /* !LZW_COMPAT */
295
    }
296
    else
297
    {
298
        sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1;
5,632✔
299
        sp->dec_decode = LZWDecode;
5,632✔
300
    }
301
    sp->lzw_nbits = BITS_MIN;
5,736✔
302
    sp->lzw_nextbits = 0;
5,736✔
303
    sp->lzw_nextdata = 0;
5,736✔
304

305
    sp->dec_restart = 0;
5,736✔
306
    sp->dec_nbitsmask = MAXCODE(BITS_MIN);
5,736✔
307
    sp->dec_bitsleft = 0;
5,736✔
308
    sp->old_tif_rawcc = 0;
5,736✔
309
    sp->dec_free_entp = sp->dec_codetab - 1; // + CODE_FIRST;
5,736✔
310
    /*
311
     * Zero entries that are not yet filled in.  We do
312
     * this to guard against bogus input data that causes
313
     * us to index into undefined entries.  If you can
314
     * come up with a way to safely bounds-check input codes
315
     * while decoding then you can remove this operation.
316
     */
317
    sp->dec_oldcodep = &sp->dec_codetab[0];
5,736✔
318
    sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1];
5,736✔
319
    sp->read_error = 0;
5,736✔
320
    return (1);
5,736✔
321
}
322

323
/*
324
 * Decode a "hunk of data".
325
 */
326

327
/* Get the next 32 or 64-bit from the input data */
328
#ifdef WORDS_BIGENDIAN
329
#define GetNextData(nextdata, bp) memcpy(&nextdata, bp, sizeof(nextdata))
330
#elif SIZEOF_WORDTYPE == 8
331
#if defined(_M_X64)
332
#define GetNextData(nextdata, bp) nextdata = _byteswap_uint64(*(uint64_t *)(bp))
333
#elif defined(__GNUC__)
334
#define GetNextData(nextdata, bp)                                              \
335
    memcpy(&nextdata, bp, sizeof(nextdata));                                   \
336
    nextdata = __builtin_bswap64(nextdata)
337
#else
338
#define GetNextData(nextdata, bp)                                              \
339
    nextdata = (((uint64_t)bp[0]) << 56) | (((uint64_t)bp[1]) << 48) |         \
340
               (((uint64_t)bp[2]) << 40) | (((uint64_t)bp[3]) << 32) |         \
341
               (((uint64_t)bp[4]) << 24) | (((uint64_t)bp[5]) << 16) |         \
342
               (((uint64_t)bp[6]) << 8) | (((uint64_t)bp[7]))
343
#endif
344
#elif SIZEOF_WORDTYPE == 4
345
#if defined(_M_X86)
346
#define GetNextData(nextdata, bp)                                              \
347
    nextdata = _byteswap_ulong(*(unsigned long *)(bp))
348
#elif defined(__GNUC__)
349
#define GetNextData(nextdata, bp)                                              \
350
    memcpy(&nextdata, bp, sizeof(nextdata));                                   \
351
    nextdata = __builtin_bswap32(nextdata)
352
#else
353
#define GetNextData(nextdata, bp)                                              \
354
    nextdata = (((uint32_t)bp[0]) << 24) | (((uint32_t)bp[1]) << 16) |         \
355
               (((uint32_t)bp[2]) << 8) | (((uint32_t)bp[3]))
356
#endif
357
#else
358
#error "Unhandled SIZEOF_WORDTYPE"
359
#endif
360

361
#define GetNextCodeLZW()                                                       \
362
    do                                                                         \
363
    {                                                                          \
364
        nextbits -= nbits;                                                     \
365
        if (nextbits < 0)                                                      \
366
        {                                                                      \
367
            if (dec_bitsleft >= 8 * SIZEOF_WORDTYPE)                           \
368
            {                                                                  \
369
                unsigned codetmp = (unsigned)(nextdata << (-nextbits));        \
370
                GetNextData(nextdata, bp);                                     \
371
                bp += SIZEOF_WORDTYPE;                                         \
372
                nextbits += 8 * SIZEOF_WORDTYPE;                               \
373
                dec_bitsleft -= 8 * SIZEOF_WORDTYPE;                           \
374
                code = (WordType)((codetmp | (nextdata >> nextbits)) &         \
375
                                  nbitsmask);                                  \
376
                break;                                                         \
377
            }                                                                  \
378
            else                                                               \
379
            {                                                                  \
380
                if (dec_bitsleft < 8)                                          \
381
                {                                                              \
382
                    goto no_eoi;                                               \
383
                }                                                              \
384
                nextdata = (nextdata << 8) | *(bp)++;                          \
385
                nextbits += 8;                                                 \
386
                dec_bitsleft -= 8;                                             \
387
                if (nextbits < 0)                                              \
388
                {                                                              \
389
                    if (dec_bitsleft < 8)                                      \
390
                    {                                                          \
391
                        goto no_eoi;                                           \
392
                    }                                                          \
393
                    nextdata = (nextdata << 8) | *(bp)++;                      \
394
                    nextbits += 8;                                             \
395
                    dec_bitsleft -= 8;                                         \
396
                }                                                              \
397
            }                                                                  \
398
        }                                                                      \
399
        code = (WordType)((nextdata >> nextbits) & nbitsmask);                 \
400
    } while (0)
401

402
static int LZWDecode(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
113,847✔
403
{
404
    static const char module[] = "LZWDecode";
405
    LZWCodecState *sp = LZWDecoderState(tif);
113,847✔
406
    uint8_t *op = (uint8_t *)op0;
113,847✔
407
    tmsize_t occ = occ0;
113,847✔
408
    uint8_t *bp;
409
    long nbits, nextbits, nbitsmask;
410
    WordType nextdata;
411
    code_t *free_entp, *maxcodep, *oldcodep;
412

413
    (void)s;
414
    assert(sp != NULL);
113,847✔
415
    assert(sp->dec_codetab != NULL);
113,847✔
416

417
    if (sp->read_error)
113,847✔
418
    {
419
        memset(op, 0, (size_t)occ);
×
420
        TIFFErrorExtR(tif, module,
×
421
                      "LZWDecode: Scanline %" PRIu32 " cannot be read due to "
422
                      "previous error",
423
                      tif->tif_row);
424
        return 0;
×
425
    }
426

427
    /*
428
     * Restart interrupted output operation.
429
     */
430
    if (sp->dec_restart)
113,847✔
431
    {
432
        tmsize_t residue;
433

434
        code_t *codep = sp->dec_codep;
104,113✔
435
        residue = codep->length - sp->dec_restart;
104,113✔
436
        if (residue > occ)
104,113✔
437
        {
438
            /*
439
             * Residue from previous decode is sufficient
440
             * to satisfy decode request.  Skip to the
441
             * start of the decoded string, place decoded
442
             * values in the output buffer, and return.
443
             */
444
            sp->dec_restart += occ;
99,868✔
445
            do
×
446
            {
447
                codep = codep->next;
3,160,750✔
448
            } while (--residue > occ && codep);
3,160,750✔
449
            if (codep)
99,868✔
450
            {
451
                uint8_t *tp = op + occ;
99,868✔
452
                do
×
453
                {
454
                    *--tp = codep->value;
176,900✔
455
                    codep = codep->next;
176,900✔
456
                } while (--occ && codep);
176,900✔
457
            }
458
            return (1);
99,868✔
459
        }
460
        /*
461
         * Residue satisfies only part of the decode request.
462
         */
463
        op += residue;
4,245✔
464
        occ -= residue;
4,245✔
465
        uint8_t *tp = op;
4,245✔
466
        do
×
467
        {
468
            *--tp = codep->value;
6,912✔
469
            codep = codep->next;
6,912✔
470
        } while (--residue && codep);
6,912✔
471
        sp->dec_restart = 0;
4,245✔
472
    }
473

474
    bp = (uint8_t *)tif->tif_rawcp;
13,979✔
475
    sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
13,979✔
476
    uint64_t dec_bitsleft = sp->dec_bitsleft;
13,979✔
477
    nbits = sp->lzw_nbits;
13,979✔
478
    nextdata = sp->lzw_nextdata;
13,979✔
479
    nextbits = sp->lzw_nextbits;
13,979✔
480
    nbitsmask = sp->dec_nbitsmask;
13,979✔
481
    oldcodep = sp->dec_oldcodep;
13,979✔
482
    free_entp = sp->dec_free_entp;
13,979✔
483
    maxcodep = sp->dec_maxcodep;
13,979✔
484
    code_t *const dec_codetab = sp->dec_codetab;
13,979✔
485
    code_t *codep;
486

487
    if (occ == 0)
13,979✔
488
    {
489
        goto after_loop;
2,276✔
490
    }
491

492
begin:
11,703✔
493
{
494
    WordType code;
495
    GetNextCodeLZW();
25,495,225✔
496
    codep = dec_codetab + code;
25,495,225✔
497
    if (code >= CODE_FIRST)
25,495,225✔
498
        goto code_above_or_equal_to_258;
21,251,858✔
499
    if (code < 256)
4,243,357✔
500
        goto code_below_256;
4,231,252✔
501
    if (code == CODE_EOI)
12,100✔
502
        goto after_loop;
10✔
503
    goto code_clear;
12,090✔
504

505
code_below_256:
4,231,252✔
506
{
507
    if (codep > free_entp)
4,231,252✔
508
        goto error_code;
×
509
    free_entp->next = oldcodep;
4,231,252✔
510
    free_entp->firstchar = oldcodep->firstchar;
4,231,252✔
511
    free_entp->length = oldcodep->length + 1;
4,231,252✔
512
    free_entp->value = (uint8_t)code;
4,231,252✔
513
    free_entp->repeated =
4,231,252✔
514
        (bool)(oldcodep->repeated & (oldcodep->value == code));
4,231,252✔
515
    if (++free_entp > maxcodep)
4,231,252✔
516
    {
517
        if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
4,320✔
518
            nbits = BITS_MAX;
×
519
        nbitsmask = MAXCODE(nbits);
4,320✔
520
        maxcodep = dec_codetab + nbitsmask - 1;
4,320✔
521
        if (free_entp >= &dec_codetab[CSIZE])
4,320✔
522
        {
523
            /* At that point, the next valid states are either EOI or a */
524
            /* CODE_CLEAR. If a regular code is read, at the next */
525
            /* attempt at registering a new entry, we will error out */
526
            /* due to setting free_entp before any valid code */
527
            free_entp = dec_codetab - 1;
×
528
        }
529
    }
530
    oldcodep = codep;
4,231,252✔
531
    *op++ = (uint8_t)code;
4,231,252✔
532
    occ--;
4,231,252✔
533
    if (occ == 0)
4,231,252✔
534
        goto after_loop;
2,731✔
535
    goto begin;
4,228,526✔
536
}
537

538
code_above_or_equal_to_258:
21,251,858✔
539
{
540
    /*
541
     * Add the new entry to the code table.
542
     */
543

544
    if (codep >= free_entp)
21,251,858✔
545
    {
546
        if (codep != free_entp)
3,359,292✔
547
            goto error_code;
2✔
548
        free_entp->value = oldcodep->firstchar;
3,359,291✔
549
    }
550
    else
551
    {
552
        free_entp->value = codep->firstchar;
17,892,586✔
553
    }
554
    free_entp->repeated =
21,251,857✔
555
        (bool)(oldcodep->repeated & (oldcodep->value == free_entp->value));
21,251,857✔
556
    free_entp->next = oldcodep;
21,251,857✔
557

558
    free_entp->firstchar = oldcodep->firstchar;
21,251,857✔
559
    free_entp->length = oldcodep->length + 1;
21,251,857✔
560
    if (++free_entp > maxcodep)
21,251,857✔
561
    {
562
        if (++nbits > BITS_MAX) /* should not happen for a conformant encoder */
17,599✔
563
            nbits = BITS_MAX;
×
564
        nbitsmask = MAXCODE(nbits);
17,599✔
565
        maxcodep = dec_codetab + nbitsmask - 1;
17,599✔
566
        if (free_entp >= &dec_codetab[CSIZE])
17,599✔
567
        {
568
            /* At that point, the next valid states are either EOI or a */
569
            /* CODE_CLEAR. If a regular code is read, at the next */
570
            /* attempt at registering a new entry, we will error out */
571
            /* due to setting free_entp before any valid code */
572
            free_entp = dec_codetab - 1;
×
573
        }
574
    }
575
    oldcodep = codep;
21,251,857✔
576

577
    /*
578
     * Code maps to a string, copy string
579
     * value to output (written in reverse).
580
     */
581
    /* tiny bit faster on x86_64 to store in unsigned short than int */
582
    unsigned short len = codep->length;
21,251,857✔
583

584
    if (len < 3) /* equivalent to len == 2 given all other conditions */
21,251,857✔
585
    {
586
        if (occ <= 2)
3,353,672✔
587
        {
588
            if (occ == 2)
588✔
589
            {
590
                memcpy(op, &(codep->firstchar), 2);
541✔
591
                op += 2;
541✔
592
                occ -= 2;
541✔
593
                goto after_loop;
541✔
594
            }
595
            goto too_short_buffer;
47✔
596
        }
597

598
        memcpy(op, &(codep->firstchar), 2);
3,353,089✔
599
        op += 2;
3,353,089✔
600
        occ -= 2;
3,353,089✔
601
        goto begin; /* we can save the comparison occ > 0 */
3,353,089✔
602
    }
603

604
    if (len == 3)
17,898,145✔
605
    {
606
        if (occ <= 3)
2,561,178✔
607
        {
608
            if (occ == 3)
338✔
609
            {
610
                op[0] = codep->firstchar;
276✔
611
                op[1] = codep->next->value;
276✔
612
                op[2] = codep->value;
276✔
613
                op += 3;
276✔
614
                occ -= 3;
276✔
615
                goto after_loop;
276✔
616
            }
617
            goto too_short_buffer;
62✔
618
        }
619

620
        op[0] = codep->firstchar;
2,560,847✔
621
        op[1] = codep->next->value;
2,560,847✔
622
        op[2] = codep->value;
2,560,847✔
623
        op += 3;
2,560,847✔
624
        occ -= 3;
2,560,847✔
625
        goto begin; /* we can save the comparison occ > 0 */
2,560,847✔
626
    }
627

628
    if (len > occ)
15,336,977✔
629
    {
630
        goto too_short_buffer;
4,379✔
631
    }
632

633
    if (codep->repeated)
15,332,577✔
634
    {
635
        memset(op, codep->value, len);
866,882✔
636
        op += len;
866,882✔
637
        occ -= len;
866,882✔
638
        if (occ == 0)
866,882✔
639
            goto after_loop;
3,287✔
640
        goto begin;
863,595✔
641
    }
642

643
    uint8_t *tp = op + len;
14,465,769✔
644

645
    assert(len >= 4);
14,465,769✔
646

647
    *--tp = codep->value;
14,465,769✔
648
    codep = codep->next;
14,465,769✔
649
    *--tp = codep->value;
14,465,769✔
650
    codep = codep->next;
14,465,769✔
651
    *--tp = codep->value;
14,465,769✔
652
    codep = codep->next;
14,465,769✔
653
    *--tp = codep->value;
14,465,769✔
654
    if (tp > op)
14,465,769✔
655
    {
656
        do
309,809✔
657
        {
658
            codep = codep->next;
112,717,990✔
659
            *--tp = codep->value;
112,717,990✔
660
        } while (tp > op);
112,717,990✔
661
    }
662

663
    assert(occ >= len);
14,465,769✔
664
    op += len;
14,465,769✔
665
    occ -= len;
14,465,769✔
666
    if (occ == 0)
14,465,769✔
667
        goto after_loop;
339✔
668
    goto begin;
14,465,353✔
669
}
670

671
code_clear:
12,090✔
672
{
673
    free_entp = dec_codetab + CODE_FIRST;
12,090✔
674
    nbits = BITS_MIN;
12,090✔
675
    nbitsmask = MAXCODE(BITS_MIN);
12,090✔
676
    maxcodep = dec_codetab + nbitsmask - 1;
12,090✔
677
    do
550✔
678
    {
679
        GetNextCodeLZW();
11,360✔
680
    } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
11,360✔
681
    if (code == CODE_EOI)
12,090✔
682
        goto after_loop;
×
683
    if (code > CODE_EOI)
12,090✔
684
    {
685
        goto error_code;
×
686
    }
687
    *op++ = (uint8_t)code;
12,090✔
688
    occ--;
12,090✔
689
    oldcodep = dec_codetab + code;
12,090✔
690
    if (occ == 0)
12,090✔
691
        goto after_loop;
29✔
692
    goto begin;
12,061✔
693
}
694
}
695

696
too_short_buffer:
4,488✔
697
{
698
    /*
699
     * String is too long for decode buffer,
700
     * locate portion that will fit, copy to
701
     * the decode buffer, and setup restart
702
     * logic for the next decoding call.
703
     */
704
    sp->dec_codep = codep;
4,488✔
705
    do
×
706
    {
707
        codep = codep->next;
202,645✔
708
    } while (codep->length > occ);
202,645✔
709

710
    sp->dec_restart = occ;
4,488✔
711
    uint8_t *tp = op + occ;
4,488✔
712
    do
×
713
    {
714
        *--tp = codep->value;
24,903✔
715
        codep = codep->next;
24,903✔
716
    } while (--occ);
24,903✔
717
}
718

719
after_loop:
4,488✔
720
    tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
13,977✔
721
    tif->tif_rawcp = (uint8_t *)bp;
13,977✔
722
    sp->old_tif_rawcc = tif->tif_rawcc;
13,977✔
723
    sp->dec_bitsleft = dec_bitsleft;
13,977✔
724
    sp->lzw_nbits = (unsigned short)nbits;
13,977✔
725
    sp->lzw_nextdata = nextdata;
13,977✔
726
    sp->lzw_nextbits = nextbits;
13,977✔
727
    sp->dec_nbitsmask = nbitsmask;
13,977✔
728
    sp->dec_oldcodep = oldcodep;
13,977✔
729
    sp->dec_free_entp = free_entp;
13,977✔
730
    sp->dec_maxcodep = maxcodep;
13,977✔
731

732
    if (occ > 0)
13,977✔
733
    {
734
        memset(op, 0, (size_t)occ);
10✔
735
        TIFFErrorExtR(tif, module,
10✔
736
                      "Not enough data at scanline %" PRIu32 " (short %" PRIu64
737
                      " bytes)",
738
                      tif->tif_row, (uint64_t)occ);
739
        return (0);
10✔
740
    }
741
    return (1);
13,967✔
742

743
no_eoi:
×
744
    memset(op, 0, (size_t)occ);
×
745
    sp->read_error = 1;
×
746
    TIFFErrorExtR(tif, module,
×
747
                  "LZWDecode: Strip %" PRIu32 " not terminated with EOI code",
748
                  tif->tif_curstrip);
749
    return 0;
×
750
error_code:
2✔
751
    memset(op, 0, (size_t)occ);
2✔
752
    sp->read_error = 1;
2✔
753
    TIFFErrorExtR(tif, tif->tif_name, "Using code not yet in table");
2✔
754
    return 0;
2✔
755
}
756

757
#ifdef LZW_COMPAT
758

759
/*
760
 * This check shouldn't be necessary because each
761
 * strip is suppose to be terminated with CODE_EOI.
762
 */
763
#define NextCode(_tif, _sp, _bp, _code, _get, dec_bitsleft)                    \
764
    {                                                                          \
765
        if (dec_bitsleft < (uint64_t)nbits)                                    \
766
        {                                                                      \
767
            TIFFWarningExtR(_tif, module,                                      \
768
                            "LZWDecode: Strip %" PRIu32                        \
769
                            " not terminated with EOI code",                   \
770
                            _tif->tif_curstrip);                               \
771
            _code = CODE_EOI;                                                  \
772
        }                                                                      \
773
        else                                                                   \
774
        {                                                                      \
775
            _get(_sp, _bp, _code);                                             \
776
            dec_bitsleft -= nbits;                                             \
777
        }                                                                      \
778
    }
779

780
/*
781
 * Decode a "hunk of data" for old images.
782
 */
783
#define GetNextCodeCompat(sp, bp, code)                                        \
784
    {                                                                          \
785
        nextdata |= (unsigned long)*(bp)++ << nextbits;                        \
786
        nextbits += 8;                                                         \
787
        if (nextbits < nbits)                                                  \
788
        {                                                                      \
789
            nextdata |= (unsigned long)*(bp)++ << nextbits;                    \
790
            nextbits += 8;                                                     \
791
        }                                                                      \
792
        code = (hcode_t)(nextdata & nbitsmask);                                \
793
        nextdata >>= nbits;                                                    \
794
        nextbits -= nbits;                                                     \
795
    }
796

797
static int LZWDecodeCompat(TIFF *tif, uint8_t *op0, tmsize_t occ0, uint16_t s)
104✔
798
{
799
    static const char module[] = "LZWDecodeCompat";
800
    LZWCodecState *sp = LZWDecoderState(tif);
104✔
801
    uint8_t *op = (uint8_t *)op0;
104✔
802
    tmsize_t occ = occ0;
104✔
803
    uint8_t *tp;
804
    uint8_t *bp;
805
    int code, nbits;
806
    int len;
807
    long nextbits, nbitsmask;
808
    WordType nextdata;
809
    code_t *codep, *free_entp, *maxcodep, *oldcodep;
810

811
    (void)s;
812
    assert(sp != NULL);
104✔
813

814
    /*
815
     * Restart interrupted output operation.
816
     */
817
    if (sp->dec_restart)
104✔
818
    {
819
        tmsize_t residue;
820

821
        codep = sp->dec_codep;
×
822
        residue = codep->length - sp->dec_restart;
×
823
        if (residue > occ)
×
824
        {
825
            /*
826
             * Residue from previous decode is sufficient
827
             * to satisfy decode request.  Skip to the
828
             * start of the decoded string, place decoded
829
             * values in the output buffer, and return.
830
             */
831
            sp->dec_restart += occ;
×
832
            do
×
833
            {
834
                codep = codep->next;
×
835
            } while (--residue > occ);
×
836
            tp = op + occ;
×
837
            do
×
838
            {
839
                *--tp = codep->value;
×
840
                codep = codep->next;
×
841
            } while (--occ);
×
842
            return (1);
×
843
        }
844
        /*
845
         * Residue satisfies only part of the decode request.
846
         */
847
        op += residue;
×
848
        occ -= residue;
×
849
        tp = op;
×
850
        do
×
851
        {
852
            *--tp = codep->value;
×
853
            codep = codep->next;
×
854
        } while (--residue);
×
855
        sp->dec_restart = 0;
×
856
    }
857

858
    bp = (uint8_t *)tif->tif_rawcp;
104✔
859

860
    sp->dec_bitsleft += (((uint64_t)tif->tif_rawcc - sp->old_tif_rawcc) << 3);
104✔
861
    uint64_t dec_bitsleft = sp->dec_bitsleft;
104✔
862

863
    nbits = sp->lzw_nbits;
104✔
864
    nextdata = sp->lzw_nextdata;
104✔
865
    nextbits = sp->lzw_nextbits;
104✔
866
    nbitsmask = sp->dec_nbitsmask;
104✔
867
    oldcodep = sp->dec_oldcodep;
104✔
868
    free_entp = sp->dec_free_entp;
104✔
869
    maxcodep = sp->dec_maxcodep;
104✔
870

871
    while (occ > 0)
208,335✔
872
    {
873
        NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
208,231✔
874
        if (code == CODE_EOI)
208,231✔
875
            break;
×
876
        if (code == CODE_CLEAR)
208,231✔
877
        {
878
            do
×
879
            {
880
                free_entp = sp->dec_codetab + CODE_FIRST;
104✔
881
                _TIFFmemset(free_entp, 0,
104✔
882
                            (CSIZE - CODE_FIRST) * sizeof(code_t));
883
                nbits = BITS_MIN;
104✔
884
                nbitsmask = MAXCODE(BITS_MIN);
104✔
885
                maxcodep = sp->dec_codetab + nbitsmask;
104✔
886
                NextCode(tif, sp, bp, code, GetNextCodeCompat, dec_bitsleft);
104✔
887
            } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */
104✔
888
            if (code == CODE_EOI)
104✔
889
                break;
×
890
            if (code > CODE_CLEAR)
104✔
891
            {
892
                TIFFErrorExtR(
×
893
                    tif, tif->tif_name,
×
894
                    "LZWDecode: Corrupted LZW table at scanline %" PRIu32,
895
                    tif->tif_row);
896
                return (0);
×
897
            }
898
            *op++ = (uint8_t)code;
104✔
899
            occ--;
104✔
900
            oldcodep = sp->dec_codetab + code;
104✔
901
            continue;
104✔
902
        }
903
        codep = sp->dec_codetab + code;
208,127✔
904

905
        /*
906
         * Add the new entry to the code table.
907
         */
908
        if (free_entp < &sp->dec_codetab[0] ||
208,127✔
909
            free_entp >= &sp->dec_codetab[CSIZE])
208,127✔
910
        {
911
            TIFFErrorExtR(tif, module,
×
912
                          "Corrupted LZW table at scanline %" PRIu32,
913
                          tif->tif_row);
914
            return (0);
×
915
        }
916

917
        free_entp->next = oldcodep;
208,127✔
918
        if (free_entp->next < &sp->dec_codetab[0] ||
208,127✔
919
            free_entp->next >= &sp->dec_codetab[CSIZE])
208,127✔
920
        {
921
            TIFFErrorExtR(tif, module,
×
922
                          "Corrupted LZW table at scanline %" PRIu32,
923
                          tif->tif_row);
924
            return (0);
×
925
        }
926
        free_entp->firstchar = free_entp->next->firstchar;
208,127✔
927
        free_entp->length = free_entp->next->length + 1;
208,127✔
928
        free_entp->value =
208,127✔
929
            (codep < free_entp) ? codep->firstchar : free_entp->firstchar;
123✔
930
        if (++free_entp > maxcodep)
208,127✔
931
        {
932
            if (++nbits > BITS_MAX) /* should not happen */
8,825✔
933
                nbits = BITS_MAX;
8,645✔
934
            nbitsmask = MAXCODE(nbits);
8,825✔
935
            maxcodep = sp->dec_codetab + nbitsmask;
8,825✔
936
        }
937
        oldcodep = codep;
208,127✔
938
        if (code >= 256)
208,127✔
939
        {
940
            /*
941
             * Code maps to a string, copy string
942
             * value to output (written in reverse).
943
             */
944
            if (codep->length == 0)
69,239✔
945
            {
946
                TIFFErrorExtR(
×
947
                    tif, module,
948
                    "Wrong length of decoded "
949
                    "string: data probably corrupted at scanline %" PRIu32,
950
                    tif->tif_row);
951
                return (0);
×
952
            }
953
            if (codep->length > occ)
69,239✔
954
            {
955
                /*
956
                 * String is too long for decode buffer,
957
                 * locate portion that will fit, copy to
958
                 * the decode buffer, and setup restart
959
                 * logic for the next decoding call.
960
                 */
961
                sp->dec_codep = codep;
×
962
                do
×
963
                {
964
                    codep = codep->next;
×
965
                } while (codep->length > occ);
×
966
                sp->dec_restart = occ;
×
967
                tp = op + occ;
×
968
                do
×
969
                {
970
                    *--tp = codep->value;
×
971
                    codep = codep->next;
×
972
                } while (--occ);
×
973
                break;
×
974
            }
975
            len = codep->length;
69,239✔
976
            tp = op + len;
69,239✔
977
            do
7,556✔
978
            {
979
                *--tp = codep->value;
658,192✔
980
                codep = codep->next;
658,192✔
981
            } while (codep && tp > op);
658,192✔
982
            assert(occ >= len);
69,239✔
983
            op += len;
69,239✔
984
            occ -= len;
69,239✔
985
        }
986
        else
987
        {
988
            *op++ = (uint8_t)code;
138,888✔
989
            occ--;
138,888✔
990
        }
991
    }
992

993
    tif->tif_rawcc -= (tmsize_t)((uint8_t *)bp - tif->tif_rawcp);
104✔
994
    tif->tif_rawcp = (uint8_t *)bp;
104✔
995

996
    sp->old_tif_rawcc = tif->tif_rawcc;
104✔
997
    sp->dec_bitsleft = dec_bitsleft;
104✔
998

999
    sp->lzw_nbits = (unsigned short)nbits;
104✔
1000
    sp->lzw_nextdata = nextdata;
104✔
1001
    sp->lzw_nextbits = nextbits;
104✔
1002
    sp->dec_nbitsmask = nbitsmask;
104✔
1003
    sp->dec_oldcodep = oldcodep;
104✔
1004
    sp->dec_free_entp = free_entp;
104✔
1005
    sp->dec_maxcodep = maxcodep;
104✔
1006

1007
    if (occ > 0)
104✔
1008
    {
1009
        TIFFErrorExtR(tif, module,
×
1010
                      "Not enough data at scanline %" PRIu32 " (short %" PRIu64
1011
                      " bytes)",
1012
                      tif->tif_row, (uint64_t)occ);
1013
        return (0);
×
1014
    }
1015
    return (1);
104✔
1016
}
1017
#endif /* LZW_COMPAT */
1018

1019
#ifndef LZW_READ_ONLY
1020

1021
static void cl_hash(LZWCodecState *);
1022

1023
/*
1024
 * LZW Encoding.
1025
 */
1026

1027
static int LZWSetupEncode(TIFF *tif)
11,632✔
1028
{
1029
    static const char module[] = "LZWSetupEncode";
1030
    LZWCodecState *sp = LZWEncoderState(tif);
11,632✔
1031

1032
    assert(sp != NULL);
11,632✔
1033
    sp->enc_hashtab = (hash_t *)_TIFFmallocExt(tif, HSIZE * sizeof(hash_t));
11,632✔
1034
    if (sp->enc_hashtab == NULL)
11,632✔
1035
    {
1036
        TIFFErrorExtR(tif, module, "No space for LZW hash table");
×
1037
        return (0);
×
1038
    }
1039
    return (1);
11,632✔
1040
}
1041

1042
/*
1043
 * Reset encoding state at the start of a strip.
1044
 */
1045
static int LZWPreEncode(TIFF *tif, uint16_t s)
13,295✔
1046
{
1047
    LZWCodecState *sp = LZWEncoderState(tif);
13,295✔
1048

1049
    (void)s;
1050
    assert(sp != NULL);
13,295✔
1051

1052
    if (sp->enc_hashtab == NULL)
13,295✔
1053
    {
1054
        tif->tif_setupencode(tif);
×
1055
    }
1056

1057
    sp->lzw_nbits = BITS_MIN;
13,295✔
1058
    sp->lzw_maxcode = MAXCODE(BITS_MIN);
13,295✔
1059
    sp->lzw_free_ent = CODE_FIRST;
13,295✔
1060
    sp->lzw_nextbits = 0;
13,295✔
1061
    sp->lzw_nextdata = 0;
13,295✔
1062
    sp->enc_checkpoint = CHECK_GAP;
13,295✔
1063
    sp->enc_ratio = 0;
13,295✔
1064
    sp->enc_incount = 0;
13,295✔
1065
    sp->enc_outcount = 0;
13,295✔
1066
    /*
1067
     * The 4 here insures there is space for 2 max-sized
1068
     * codes in LZWEncode and LZWPostDecode.
1069
     */
1070
    sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize - 1 - 4;
13,295✔
1071
    cl_hash(sp);                   /* clear hash table */
13,295✔
1072
    sp->enc_oldcode = (hcode_t)-1; /* generates CODE_CLEAR in LZWEncode */
13,295✔
1073
    return (1);
13,295✔
1074
}
1075

1076
#define CALCRATIO(sp, rat)                                                     \
1077
    {                                                                          \
1078
        if (incount > 0x007fffff)                                              \
1079
        { /* NB: shift will overflow */                                        \
1080
            rat = outcount >> 8;                                               \
1081
            rat = (rat == 0 ? 0x7fffffff : incount / rat);                     \
1082
        }                                                                      \
1083
        else                                                                   \
1084
            rat = (incount << 8) / outcount;                                   \
1085
    }
1086

1087
/* Explicit 0xff masking to make icc -check=conversions happy */
1088
#define PutNextCode(op, c)                                                     \
1089
    {                                                                          \
1090
        nextdata = (nextdata << nbits) | c;                                    \
1091
        nextbits += nbits;                                                     \
1092
        *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);          \
1093
        nextbits -= 8;                                                         \
1094
        if (nextbits >= 8)                                                     \
1095
        {                                                                      \
1096
            *op++ = (unsigned char)((nextdata >> (nextbits - 8)) & 0xff);      \
1097
            nextbits -= 8;                                                     \
1098
        }                                                                      \
1099
        outcount += nbits;                                                     \
1100
    }
1101

1102
/*
1103
 * Encode a chunk of pixels.
1104
 *
1105
 * Uses an open addressing double hashing (no chaining) on the
1106
 * prefix code/next character combination.  We do a variant of
1107
 * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
1108
 * relatively-prime secondary probe.  Here, the modular division
1109
 * first probe is gives way to a faster exclusive-or manipulation.
1110
 * Also do block compression with an adaptive reset, whereby the
1111
 * code table is cleared when the compression ratio decreases,
1112
 * but after the table fills.  The variable-length output codes
1113
 * are re-sized at this point, and a CODE_CLEAR is generated
1114
 * for the decoder.
1115
 */
1116
static int LZWEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
35,291✔
1117
{
1118
    register LZWCodecState *sp = LZWEncoderState(tif);
35,291✔
1119
    register long fcode;
1120
    register hash_t *hp;
1121
    register int h, c;
1122
    hcode_t ent;
1123
    long disp;
1124
    tmsize_t incount, outcount, checkpoint;
1125
    WordType nextdata;
1126
    long nextbits;
1127
    int free_ent, maxcode, nbits;
1128
    uint8_t *op;
1129
    uint8_t *limit;
1130

1131
    (void)s;
1132
    if (sp == NULL)
35,291✔
1133
        return (0);
×
1134

1135
    assert(sp->enc_hashtab != NULL);
35,291✔
1136

1137
    /*
1138
     * Load local state.
1139
     */
1140
    incount = sp->enc_incount;
35,291✔
1141
    outcount = sp->enc_outcount;
35,291✔
1142
    checkpoint = sp->enc_checkpoint;
35,291✔
1143
    nextdata = sp->lzw_nextdata;
35,291✔
1144
    nextbits = sp->lzw_nextbits;
35,291✔
1145
    free_ent = sp->lzw_free_ent;
35,291✔
1146
    maxcode = sp->lzw_maxcode;
35,291✔
1147
    nbits = sp->lzw_nbits;
35,291✔
1148
    op = tif->tif_rawcp;
35,291✔
1149
    limit = sp->enc_rawlimit;
35,291✔
1150
    ent = (hcode_t)sp->enc_oldcode;
35,291✔
1151

1152
    if (ent == (hcode_t)-1 && cc > 0)
35,291✔
1153
    {
1154
        /*
1155
         * NB: This is safe because it can only happen
1156
         *     at the start of a strip where we know there
1157
         *     is space in the data buffer.
1158
         */
1159
        PutNextCode(op, CODE_CLEAR);
13,295✔
1160
        ent = *bp++;
13,295✔
1161
        cc--;
13,295✔
1162
        incount++;
13,295✔
1163
    }
1164
    while (cc > 0)
35,291✔
1165
    {
1166
        c = *bp++;
582,410,000✔
1167
        cc--;
582,410,000✔
1168
        incount++;
582,410,000✔
1169
        fcode = ((long)c << BITS_MAX) + ent;
582,410,000✔
1170
        h = (c << HSHIFT) ^ ent; /* xor hashing */
582,410,000✔
1171
#ifdef _WINDOWS
1172
        /*
1173
         * Check hash index for an overflow.
1174
         */
1175
        if (h >= HSIZE)
1176
            h -= HSIZE;
1177
#endif
1178
        hp = &sp->enc_hashtab[h];
582,410,000✔
1179
        if (hp->hash == fcode)
582,410,000✔
1180
        {
1181
            ent = hp->code;
459,146,000✔
1182
            continue;
459,146,000✔
1183
        }
1184
        if (hp->hash >= 0)
123,264,000✔
1185
        {
1186
            /*
1187
             * Primary hash failed, check secondary hash.
1188
             */
1189
            disp = HSIZE - h;
103,683,000✔
1190
            if (h == 0)
103,683,000✔
1191
                disp = 1;
14,931✔
1192
            do
1193
            {
1194
                /*
1195
                 * Avoid pointer arithmetic because of
1196
                 * wraparound problems with segments.
1197
                 */
1198
                if ((h -= disp) < 0)
131,982,000✔
1199
                    h += HSIZE;
124,776,000✔
1200
                hp = &sp->enc_hashtab[h];
131,982,000✔
1201
                if (hp->hash == fcode)
131,982,000✔
1202
                {
1203
                    ent = hp->code;
97,501,500✔
1204
                    goto hit;
97,501,500✔
1205
                }
1206
            } while (hp->hash >= 0);
34,480,700✔
1207
        }
1208
        /*
1209
         * New entry, emit code and add to table.
1210
         */
1211
        /*
1212
         * Verify there is space in the buffer for the code
1213
         * and any potential Clear code that might be emitted
1214
         * below.  The value of limit is setup so that there
1215
         * are at least 4 bytes free--room for 2 codes.
1216
         */
1217
        if (op > limit)
25,762,500✔
1218
        {
1219
            tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
1✔
1220
            if (!TIFFFlushData1(tif))
1✔
1221
                return 0;
×
1222
            op = tif->tif_rawdata;
1✔
1223
        }
1224
        PutNextCode(op, ent);
25,762,500✔
1225
        ent = (hcode_t)c;
25,762,500✔
1226
        hp->code = (hcode_t)(free_ent++);
25,762,500✔
1227
        hp->hash = fcode;
25,762,500✔
1228
        if (free_ent == CODE_MAX - 1)
25,762,500✔
1229
        {
1230
            /* table is full, emit clear code and reset */
1231
            cl_hash(sp);
5,815✔
1232
            sp->enc_ratio = 0;
5,815✔
1233
            incount = 0;
5,815✔
1234
            outcount = 0;
5,815✔
1235
            free_ent = CODE_FIRST;
5,815✔
1236
            PutNextCode(op, CODE_CLEAR);
5,815✔
1237
            nbits = BITS_MIN;
5,815✔
1238
            maxcode = MAXCODE(BITS_MIN);
5,815✔
1239
        }
1240
        else
1241
        {
1242
            /*
1243
             * If the next entry is going to be too big for
1244
             * the code size, then increase it, if possible.
1245
             */
1246
            if (free_ent > maxcode)
25,756,700✔
1247
            {
1248
                nbits++;
24,104✔
1249
                assert(nbits <= BITS_MAX);
24,104✔
1250
                maxcode = (int)MAXCODE(nbits);
24,104✔
1251
            }
1252
            else if (incount >= checkpoint)
25,732,600✔
1253
            {
1254
                tmsize_t rat;
1255
                /*
1256
                 * Check compression ratio and, if things seem
1257
                 * to be slipping, clear the hash table and
1258
                 * reset state.  The compression ratio is a
1259
                 * 24+8-bit fractional number.
1260
                 */
1261
                checkpoint = incount + CHECK_GAP;
38,094✔
1262
                CALCRATIO(sp, rat);
38,094✔
1263
                if (rat <= sp->enc_ratio)
38,094✔
1264
                {
1265
                    cl_hash(sp);
149✔
1266
                    sp->enc_ratio = 0;
149✔
1267
                    incount = 0;
149✔
1268
                    outcount = 0;
149✔
1269
                    free_ent = CODE_FIRST;
149✔
1270
                    PutNextCode(op, CODE_CLEAR);
149✔
1271
                    nbits = BITS_MIN;
149✔
1272
                    maxcode = MAXCODE(BITS_MIN);
149✔
1273
                }
1274
                else
1275
                    sp->enc_ratio = rat;
37,945✔
1276
            }
1277
        }
1278
    hit:;
582,445,000✔
1279
    }
1280

1281
    /*
1282
     * Restore global state.
1283
     */
1284
    sp->enc_incount = incount;
35,291✔
1285
    sp->enc_outcount = outcount;
35,291✔
1286
    sp->enc_checkpoint = checkpoint;
35,291✔
1287
    sp->enc_oldcode = ent;
35,291✔
1288
    sp->lzw_nextdata = nextdata;
35,291✔
1289
    sp->lzw_nextbits = nextbits;
35,291✔
1290
    sp->lzw_free_ent = (unsigned short)free_ent;
35,291✔
1291
    sp->lzw_maxcode = (unsigned short)maxcode;
35,291✔
1292
    sp->lzw_nbits = (unsigned short)nbits;
35,291✔
1293
    tif->tif_rawcp = op;
35,291✔
1294
    return (1);
35,291✔
1295
}
1296

1297
/*
1298
 * Finish off an encoded strip by flushing the last
1299
 * string and tacking on an End Of Information code.
1300
 */
1301
static int LZWPostEncode(TIFF *tif)
13,295✔
1302
{
1303
    register LZWCodecState *sp = LZWEncoderState(tif);
13,295✔
1304
    uint8_t *op = tif->tif_rawcp;
13,295✔
1305
    long nextbits = sp->lzw_nextbits;
13,295✔
1306
    WordType nextdata = sp->lzw_nextdata;
13,295✔
1307
    tmsize_t outcount = sp->enc_outcount;
13,295✔
1308
    int nbits = sp->lzw_nbits;
13,295✔
1309

1310
    if (op > sp->enc_rawlimit)
13,295✔
1311
    {
1312
        tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
×
1313
        if (!TIFFFlushData1(tif))
×
1314
            return 0;
×
1315
        op = tif->tif_rawdata;
×
1316
    }
1317
    if (sp->enc_oldcode != (hcode_t)-1)
13,295✔
1318
    {
1319
        int free_ent = sp->lzw_free_ent;
13,295✔
1320

1321
        PutNextCode(op, sp->enc_oldcode);
13,295✔
1322
        sp->enc_oldcode = (hcode_t)-1;
13,295✔
1323
        free_ent++;
13,295✔
1324

1325
        if (free_ent == CODE_MAX - 1)
13,295✔
1326
        {
1327
            /* table is full, emit clear code and reset */
1328
            outcount = 0;
×
1329
            PutNextCode(op, CODE_CLEAR);
×
1330
            nbits = BITS_MIN;
×
1331
        }
1332
        else
1333
        {
1334
            /*
1335
             * If the next entry is going to be too big for
1336
             * the code size, then increase it, if possible.
1337
             */
1338
            if (free_ent > sp->lzw_maxcode)
13,295✔
1339
            {
1340
                nbits++;
1✔
1341
                assert(nbits <= BITS_MAX);
1✔
1342
            }
1343
        }
1344
    }
1345
    PutNextCode(op, CODE_EOI);
13,295✔
1346
    /* Explicit 0xff masking to make icc -check=conversions happy */
1347
    if (nextbits > 0)
13,295✔
1348
        *op++ = (unsigned char)((nextdata << (8 - nextbits)) & 0xff);
13,184✔
1349
    tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
13,295✔
1350
    (void)outcount;
1351
    return (1);
13,295✔
1352
}
1353

1354
/*
1355
 * Reset encoding hash table.
1356
 */
1357
static void cl_hash(LZWCodecState *sp)
19,259✔
1358
{
1359
    register hash_t *hp = &sp->enc_hashtab[HSIZE - 1];
19,259✔
1360
    register long i = HSIZE - 8;
19,259✔
1361

1362
    do
1363
    {
1364
        i -= 8;
21,659,800✔
1365
        hp[-7].hash = -1;
21,659,800✔
1366
        hp[-6].hash = -1;
21,659,800✔
1367
        hp[-5].hash = -1;
21,659,800✔
1368
        hp[-4].hash = -1;
21,659,800✔
1369
        hp[-3].hash = -1;
21,659,800✔
1370
        hp[-2].hash = -1;
21,659,800✔
1371
        hp[-1].hash = -1;
21,659,800✔
1372
        hp[0].hash = -1;
21,659,800✔
1373
        hp -= 8;
21,659,800✔
1374
    } while (i >= 0);
21,659,800✔
1375
    for (i += 8; i > 0; i--, hp--)
38,518✔
1376
        hp->hash = -1;
19,259✔
1377
}
19,259✔
1378

1379
#endif
1380

1381
static void LZWCleanup(TIFF *tif)
18,420✔
1382
{
1383
    (void)TIFFPredictorCleanup(tif);
18,420✔
1384

1385
    assert(tif->tif_data != NULL);
18,419✔
1386

1387
    if (LZWDecoderState(tif)->dec_codetab)
18,419✔
1388
        _TIFFfreeExt(tif, LZWDecoderState(tif)->dec_codetab);
2,490✔
1389

1390
    if (LZWEncoderState(tif)->enc_hashtab)
18,419✔
1391
        _TIFFfreeExt(tif, LZWEncoderState(tif)->enc_hashtab);
11,630✔
1392

1393
    _TIFFfreeExt(tif, tif->tif_data);
18,421✔
1394
    tif->tif_data = NULL;
18,422✔
1395

1396
    _TIFFSetDefaultCompressionState(tif);
18,422✔
1397
}
18,421✔
1398

1399
int TIFFInitLZW(TIFF *tif, int scheme)
18,422✔
1400
{
1401
    static const char module[] = "TIFFInitLZW";
1402
    (void)scheme;
1403
    assert(scheme == COMPRESSION_LZW);
18,422✔
1404
    /*
1405
     * Allocate state block so tag methods have storage to record values.
1406
     */
1407
    tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(LZWCodecState));
18,422✔
1408
    if (tif->tif_data == NULL)
18,422✔
1409
        goto bad;
×
1410
    LZWDecoderState(tif)->dec_codetab = NULL;
18,422✔
1411
    LZWDecoderState(tif)->dec_decode = NULL;
18,422✔
1412
    LZWEncoderState(tif)->enc_hashtab = NULL;
18,422✔
1413
    LZWState(tif)->rw_mode = tif->tif_mode;
18,422✔
1414

1415
    /*
1416
     * Install codec methods.
1417
     */
1418
    tif->tif_fixuptags = LZWFixupTags;
18,422✔
1419
    tif->tif_setupdecode = LZWSetupDecode;
18,422✔
1420
    tif->tif_predecode = LZWPreDecode;
18,422✔
1421
    tif->tif_decoderow = LZWDecode;
18,422✔
1422
    tif->tif_decodestrip = LZWDecode;
18,422✔
1423
    tif->tif_decodetile = LZWDecode;
18,422✔
1424
#ifndef LZW_READ_ONLY
1425
    tif->tif_setupencode = LZWSetupEncode;
18,347✔
1426
    tif->tif_preencode = LZWPreEncode;
18,347✔
1427
    tif->tif_postencode = LZWPostEncode;
18,347✔
1428
    tif->tif_encoderow = LZWEncode;
18,347✔
1429
    tif->tif_encodestrip = LZWEncode;
18,347✔
1430
    tif->tif_encodetile = LZWEncode;
18,347✔
1431
#endif
1432
    tif->tif_cleanup = LZWCleanup;
18,422✔
1433
    /*
1434
     * Setup predictor setup.
1435
     */
1436
    (void)TIFFPredictorInit(tif);
18,422✔
1437
    return (1);
18,423✔
1438
bad:
×
1439
    TIFFErrorExtR(tif, module, "No space for LZW state block");
×
1440
    return (0);
×
1441
}
1442

1443
/*
1444
 * Copyright (c) 1985, 1986 The Regents of the University of California.
1445
 * All rights reserved.
1446
 *
1447
 * This code is derived from software contributed to Berkeley by
1448
 * James A. Woods, derived from original work by Spencer Thomas
1449
 * and Joseph Orost.
1450
 *
1451
 * Redistribution and use in source and binary forms are permitted
1452
 * provided that the above copyright notice and this paragraph are
1453
 * duplicated in all such forms and that any documentation,
1454
 * advertising materials, and other materials related to such
1455
 * distribution and use acknowledge that the software was developed
1456
 * by the University of California, Berkeley.  The name of the
1457
 * University may not be used to endorse or promote products derived
1458
 * from this software without specific prior written permission.
1459
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1460
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1461
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1462
 */
1463
#endif /* LZW_SUPPORT */
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc