Coverage Report

Created: 2026-07-25 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/gtiff/libtiff/tif_read.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1988-1997 Sam Leffler
3
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22
 * OF THIS SOFTWARE.
23
 */
24
25
/*
26
 * TIFF Library.
27
 * Scanline-oriented Read Support
28
 */
29
#include "tiffiop.h"
30
#include <limits.h>
31
#include <stdio.h>
32
33
int TIFFFillStrip(TIFF *tif, uint32_t strip);
34
int TIFFFillTile(TIFF *tif, uint32_t tile);
35
static int TIFFStartStrip(TIFF *tif, uint32_t strip);
36
static int TIFFStartTile(TIFF *tif, uint32_t tile);
37
static int TIFFCheckRead(TIFF *, int);
38
static tmsize_t TIFFReadRawStrip1(TIFF *tif, uint32_t strip, void *buf,
39
                                  tmsize_t size, const char *module);
40
static tmsize_t TIFFReadRawTile1(TIFF *tif, uint32_t tile, void *buf,
41
                                 tmsize_t size, const char *module);
42
43
0
#define INITIAL_THRESHOLD (1024 * 1024)
44
0
#define THRESHOLD_MULTIPLIER 10
45
#define MAX_THRESHOLD                                                          \
46
0
    (THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER *      \
47
0
     INITIAL_THRESHOLD)
48
49
0
#define TIFF_INT64_MAX ((((int64_t)0x7FFFFFFF) << 32) | 0xFFFFFFFF)
50
51
/* Read 'size' bytes in tif_rawdata buffer starting at offset 'rawdata_offset'
52
 * Returns 1 in case of success, 0 otherwise. */
53
static int TIFFReadAndRealloc(TIFF *tif, tmsize_t size, tmsize_t rawdata_offset,
54
                              int is_strip, uint32_t strip_or_tile,
55
                              const char *module)
56
0
{
57
0
#if SIZEOF_SIZE_T == 8
58
0
    tmsize_t threshold = INITIAL_THRESHOLD;
59
0
#endif
60
0
    tmsize_t already_read = 0;
61
62
#if SIZEOF_SIZE_T != 8
63
    /* On 32 bit processes, if the request is large enough, check against */
64
    /* file size */
65
    if (size > 1000 * 1000 * 1000)
66
    {
67
        uint64_t filesize = TIFFGetFileSize(tif);
68
        if ((uint64_t)size >= filesize)
69
        {
70
            TIFFErrorExtR(tif, module,
71
                          "Chunk size requested is larger than file size.");
72
            return 0;
73
        }
74
    }
75
#endif
76
77
    /* On 64 bit processes, read first a maximum of 1 MB, then 10 MB, etc */
78
    /* so as to avoid allocating too much memory in case the file is too */
79
    /* short. We could ask for the file size, but this might be */
80
    /* expensive with some I/O layers (think of reading a gzipped file) */
81
    /* Restrict to 64 bit processes, so as to avoid reallocs() */
82
    /* on 32 bit processes where virtual memory is scarce.  */
83
0
    while (already_read < size)
84
0
    {
85
0
        tmsize_t bytes_read;
86
0
        tmsize_t to_read = size - already_read;
87
0
#if SIZEOF_SIZE_T == 8
88
0
        if (to_read >= threshold && threshold < MAX_THRESHOLD &&
89
0
            already_read + to_read + rawdata_offset > tif->tif_rawdatasize)
90
0
        {
91
0
            to_read = threshold;
92
0
            threshold *= THRESHOLD_MULTIPLIER;
93
0
        }
94
0
#endif
95
0
        if (already_read + to_read + rawdata_offset > tif->tif_rawdatasize)
96
0
        {
97
0
            uint8_t *new_rawdata;
98
0
            assert((tif->tif_flags & TIFF_MYBUFFER) != 0);
99
0
            tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64(
100
0
                (uint64_t)already_read + (uint64_t)to_read +
101
0
                    (uint64_t)rawdata_offset,
102
0
                1024);
103
0
            if (tif->tif_rawdatasize == 0)
104
0
            {
105
0
                TIFFErrorExtR(tif, module, "Invalid buffer size");
106
0
                return 0;
107
0
            }
108
0
            new_rawdata = (uint8_t *)_TIFFreallocExt(tif, tif->tif_rawdata,
109
0
                                                     tif->tif_rawdatasize);
110
0
            if (new_rawdata == 0)
111
0
            {
112
0
                TIFFErrorExtR(tif, module,
113
0
                              "No space for data buffer at scanline %" PRIu32,
114
0
                              tif->tif_dir.td_row);
115
0
                _TIFFfreeExt(tif, tif->tif_rawdata);
116
0
                tif->tif_rawdata = 0;
117
0
                tif->tif_rawdatasize = 0;
118
0
                return 0;
119
0
            }
120
0
            tif->tif_rawdata = new_rawdata;
121
0
        }
122
0
        if (tif->tif_rawdata == NULL)
123
0
        {
124
            /* should not happen in practice but helps CoverityScan */
125
0
            return 0;
126
0
        }
127
128
0
        bytes_read = TIFFReadFile(
129
0
            tif, tif->tif_rawdata + rawdata_offset + already_read, to_read);
130
0
        if (bytes_read < 0)
131
            /* Treat read errors as short reads before updating offsets. */
132
0
            bytes_read = 0;
133
0
        already_read += bytes_read;
134
0
        if (bytes_read != to_read)
135
0
        {
136
0
            memset(
137
0
                tif->tif_rawdata + rawdata_offset + already_read, 0,
138
0
                (size_t)(tif->tif_rawdatasize - rawdata_offset - already_read));
139
0
            if (is_strip)
140
0
            {
141
0
                TIFFErrorExtR(tif, module,
142
0
                              "Read error at scanline %" PRIu32
143
0
                              "; got %" TIFF_SSIZE_FORMAT " bytes, "
144
0
                              "expected %" TIFF_SSIZE_FORMAT,
145
0
                              tif->tif_dir.td_row, already_read, size);
146
0
            }
147
0
            else
148
0
            {
149
0
                TIFFErrorExtR(tif, module,
150
0
                              "Read error at row %" PRIu32 ", col %" PRIu32
151
0
                              ", tile %" PRIu32 "; "
152
0
                              "got %" TIFF_SSIZE_FORMAT
153
0
                              " bytes, expected %" TIFF_SSIZE_FORMAT "",
154
0
                              tif->tif_dir.td_row, tif->tif_dir.td_col,
155
0
                              strip_or_tile, already_read, size);
156
0
            }
157
0
            return 0;
158
0
        }
159
0
    }
160
0
    return 1;
161
0
}
162
163
static int TIFFFillStripPartial(TIFF *tif, int strip, tmsize_t read_ahead,
164
                                int restart)
165
0
{
166
0
    static const char module[] = "TIFFFillStripPartial";
167
0
    TIFFDirectory *td = &tif->tif_dir;
168
0
    tmsize_t unused_data;
169
0
    uint64_t read_offset;
170
0
    tmsize_t to_read;
171
0
    tmsize_t read_ahead_mod;
172
    /* tmsize_t bytecountm; */
173
174
    /*
175
     * Expand raw data buffer, if needed, to hold data
176
     * strip coming from file (perhaps should set upper
177
     * bound on the size of a buffer we'll use?).
178
     */
179
180
    /* bytecountm=(tmsize_t) TIFFGetStrileByteCount(tif, strip); */
181
182
    /* Not completely sure where the * 2 comes from, but probably for */
183
    /* an exponentional growth strategy of tif_rawdatasize */
184
0
    if (read_ahead < TIFF_TMSIZE_T_MAX / 2)
185
0
        read_ahead_mod = read_ahead * 2;
186
0
    else
187
0
        read_ahead_mod = read_ahead;
188
0
    if (read_ahead_mod > tif->tif_rawdatasize)
189
0
    {
190
0
        assert(restart);
191
192
0
        tif->tif_dir.td_curstrip = NOSTRIP;
193
0
        if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
194
0
        {
195
0
            TIFFErrorExtR(tif, module,
196
0
                          "Data buffer too small to hold part of strip %d",
197
0
                          strip);
198
0
            return (0);
199
0
        }
200
0
    }
201
202
0
    if (restart)
203
0
    {
204
0
        tif->tif_rawdataloaded = 0;
205
0
        tif->tif_rawdataoff = 0;
206
0
    }
207
208
    /*
209
    ** If we are reading more data, move any unused data to the
210
    ** start of the buffer.
211
    */
212
0
    if (tif->tif_rawdataloaded > 0)
213
0
        unused_data =
214
0
            tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata);
215
0
    else
216
0
        unused_data = 0;
217
218
0
    if (unused_data > 0)
219
0
    {
220
0
        assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
221
0
        memmove(tif->tif_rawdata, tif->tif_rawcp, (size_t)unused_data);
222
0
    }
223
224
    /*
225
    ** Seek to the point in the file where more data should be read.
226
    */
227
0
    read_offset = TIFFGetStrileOffset(tif, (uint32_t)strip);
228
0
    if (read_offset > UINT64_MAX - (uint64_t)tif->tif_rawdataoff ||
229
0
        read_offset + (uint64_t)tif->tif_rawdataoff >
230
0
            UINT64_MAX - (uint64_t)tif->tif_rawdataloaded)
231
0
    {
232
0
        TIFFErrorExtR(tif, module,
233
0
                      "Seek error at scanline %" PRIu32 ", strip %d",
234
0
                      tif->tif_dir.td_row, strip);
235
0
        return 0;
236
0
    }
237
0
    read_offset +=
238
0
        (uint64_t)tif->tif_rawdataoff + (uint64_t)tif->tif_rawdataloaded;
239
240
0
    if (!SeekOK(tif, read_offset))
241
0
    {
242
0
        TIFFErrorExtR(tif, module,
243
0
                      "Seek error at scanline %" PRIu32 ", strip %d",
244
0
                      tif->tif_dir.td_row, strip);
245
0
        return 0;
246
0
    }
247
248
    /*
249
    ** How much do we want to read?
250
    */
251
0
    if (read_ahead_mod > tif->tif_rawdatasize)
252
0
        to_read = read_ahead_mod - unused_data;
253
0
    else
254
0
        to_read = tif->tif_rawdatasize - unused_data;
255
0
    if ((uint64_t)to_read > TIFFGetStrileByteCount(tif, (uint32_t)strip) -
256
0
                                (uint64_t)tif->tif_rawdataoff -
257
0
                                (uint64_t)tif->tif_rawdataloaded)
258
0
    {
259
0
        to_read = (tmsize_t)(TIFFGetStrileByteCount(tif, (uint32_t)strip) -
260
0
                             (uint64_t)tif->tif_rawdataoff -
261
0
                             (uint64_t)tif->tif_rawdataloaded);
262
0
    }
263
264
0
    assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
265
0
    if (!TIFFReadAndRealloc(tif, to_read, unused_data, 1, /* is_strip */
266
0
                            0,                            /* strip_or_tile */
267
0
                            module))
268
0
    {
269
0
        return 0;
270
0
    }
271
272
0
    tif->tif_rawdataoff =
273
0
        tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data;
274
0
    tif->tif_rawdataloaded = unused_data + to_read;
275
276
0
    tif->tif_rawcc = tif->tif_rawdataloaded;
277
0
    tif->tif_rawcp = tif->tif_rawdata;
278
279
0
    if (!isFillOrder(tif, td->td_fillorder) &&
280
0
        (tif->tif_flags & TIFF_NOBITREV) == 0)
281
0
    {
282
0
        assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
283
0
        TIFFReverseBits(tif->tif_rawdata + unused_data, to_read);
284
0
    }
285
286
    /*
287
    ** When starting a strip from the beginning we need to
288
    ** restart the decoder.
289
    */
290
0
    if (restart)
291
0
    {
292
293
0
#ifdef JPEG_SUPPORT
294
        /* A bit messy since breaks the codec abstraction. Ultimately */
295
        /* there should be a function pointer for that, but it seems */
296
        /* only JPEG is affected. */
297
        /* For JPEG, if there are multiple scans (can generally be known */
298
        /* with the  read_ahead used), we need to read the whole strip */
299
0
        if (tif->tif_dir.td_compression == COMPRESSION_JPEG &&
300
0
            (uint64_t)tif->tif_rawcc <
301
0
                TIFFGetStrileByteCount(tif, (uint32_t)strip))
302
0
        {
303
0
            if (TIFFJPEGIsFullStripRequired(tif))
304
0
            {
305
0
                return TIFFFillStrip(tif, (uint32_t)strip);
306
0
            }
307
0
        }
308
0
#endif
309
310
0
        return TIFFStartStrip(tif, (uint32_t)strip);
311
0
    }
312
0
    else
313
0
    {
314
0
        return 1;
315
0
    }
316
0
}
317
318
/*
319
 * Seek to a random row+sample in a file.
320
 *
321
 * Only used by TIFFReadScanline, and is only used on
322
 * strip organized files.  We do some tricky stuff to try
323
 * and avoid reading the whole compressed raw data for big
324
 * strips.
325
 */
326
static int TIFFSeek(TIFF *tif, uint32_t row, uint16_t sample)
327
0
{
328
0
    TIFFDirectory *td = &tif->tif_dir;
329
0
    uint32_t strip;
330
0
    int whole_strip;
331
0
    tmsize_t read_ahead = 0;
332
333
    /*
334
    ** Establish what strip we are working from.
335
    */
336
0
    if (row >= td->td_imagelength)
337
0
    { /* out of range */
338
0
        TIFFErrorExtR(tif, tif->tif_name,
339
0
                      "%" PRIu32 ": Row out of range, max %" PRIu32 "", row,
340
0
                      td->td_imagelength);
341
0
        return (0);
342
0
    }
343
0
    if (td->td_rowsperstrip == 0)
344
0
    {
345
0
        TIFFErrorExtR(tif, tif->tif_name,
346
0
                      "Cannot compute strip: RowsPerStrip is zero");
347
0
        return (0);
348
0
    }
349
0
    if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
350
0
    {
351
0
        uint64_t sample_offset;
352
0
        uint64_t strip64;
353
0
        if (sample >= td->td_samplesperpixel)
354
0
        {
355
0
            TIFFErrorExtR(tif, tif->tif_name,
356
0
                          "%" PRIu16 ": Sample out of range, max %" PRIu16 "",
357
0
                          sample, td->td_samplesperpixel);
358
0
            return (0);
359
0
        }
360
0
        sample_offset =
361
0
            _TIFFMultiply64(tif, sample, td->td_stripsperimage, "TIFFSeek");
362
0
        if (sample_offset == 0 && sample != 0 && td->td_stripsperimage != 0)
363
0
            return (0);
364
0
        strip64 = _TIFFAdd64(tif, sample_offset, row / td->td_rowsperstrip,
365
0
                             "TIFFSeek");
366
0
        if (strip64 == 0 &&
367
0
            (sample_offset != 0 || (row / td->td_rowsperstrip) != 0))
368
0
            return (0);
369
0
        strip = _TIFFCastUInt64ToUInt32(tif, strip64, "TIFFSeek");
370
0
        if (strip == 0 && strip64 != 0)
371
0
            return (0);
372
0
    }
373
0
    else
374
0
        strip = row / td->td_rowsperstrip;
375
376
    /*
377
     * Do we want to treat this strip as one whole chunk or
378
     * read it a few lines at a time?
379
     */
380
0
#if defined(CHUNKY_STRIP_READ_SUPPORT)
381
0
    whole_strip = TIFFGetStrileByteCount(tif, strip) < 10 || isMapped(tif);
382
0
    if (td->td_compression == COMPRESSION_LERC ||
383
0
        td->td_compression == COMPRESSION_JBIG)
384
0
    {
385
        /* Ideally plugins should have a way to declare they don't support
386
         * chunk strip */
387
0
        whole_strip = 1;
388
0
    }
389
390
0
    if (!whole_strip)
391
0
    {
392
        /* 16 is for YCbCr mode where we may need to read 16 */
393
        /* lines at a time to get a decompressed line, and 5000 */
394
        /* is some constant value, for example for JPEG tables */
395
396
        /* coverity[dead_error_line:SUPPRESS] */
397
0
        if (tif->tif_dir.td_scanlinesize < TIFF_TMSIZE_T_MAX / 16 &&
398
0
            tif->tif_dir.td_scanlinesize * 16 < TIFF_TMSIZE_T_MAX - 5000)
399
0
        {
400
0
            read_ahead = tif->tif_dir.td_scanlinesize * 16 + 5000;
401
0
        }
402
0
        else
403
0
        {
404
0
            read_ahead = tif->tif_dir.td_scanlinesize;
405
0
        }
406
0
    }
407
#else
408
    whole_strip = 1;
409
#endif
410
411
    /*
412
     * If we haven't loaded this strip, do so now, possibly
413
     * only reading the first part.
414
     */
415
0
    if (strip != tif->tif_dir.td_curstrip)
416
0
    { /* different strip, refill */
417
418
0
        if (whole_strip)
419
0
        {
420
0
            if (!TIFFFillStrip(tif, strip))
421
0
                return (0);
422
0
        }
423
0
#if defined(CHUNKY_STRIP_READ_SUPPORT)
424
0
        else
425
0
        {
426
0
            if (!TIFFFillStripPartial(tif, strip, read_ahead, 1))
427
0
                return 0;
428
0
        }
429
0
#endif
430
0
    }
431
432
0
#if defined(CHUNKY_STRIP_READ_SUPPORT)
433
    /*
434
    ** If we already have some data loaded, do we need to read some more?
435
    */
436
0
    else if (!whole_strip)
437
0
    {
438
        /* coverity[dead_error_line:SUPPRESS] */
439
0
        if (((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) <
440
0
                read_ahead &&
441
0
            (uint64_t)tif->tif_rawdataoff + tif->tif_rawdataloaded <
442
0
                TIFFGetStrileByteCount(tif, strip))
443
0
        {
444
0
            if (!TIFFFillStripPartial(tif, strip, read_ahead, 0))
445
0
                return 0;
446
0
        }
447
0
    }
448
0
#endif
449
450
0
    if (row < tif->tif_dir.td_row)
451
0
    {
452
        /*
453
         * Moving backwards within the same strip: backup
454
         * to the start and then decode forward (below).
455
         *
456
         * NB: If you're planning on lots of random access within a
457
         * strip, it's better to just read and decode the entire
458
         * strip, and then access the decoded data in a random fashion.
459
         */
460
461
0
        if (tif->tif_rawdataoff != 0)
462
0
        {
463
0
            if (!TIFFFillStripPartial(tif, (int)strip, read_ahead, 1))
464
0
                return 0;
465
0
        }
466
0
        else
467
0
        {
468
0
            if (!TIFFStartStrip(tif, strip))
469
0
                return (0);
470
0
        }
471
0
    }
472
473
0
    if (row != tif->tif_dir.td_row)
474
0
    {
475
        /*
476
         * Seek forward to the desired row.
477
         */
478
479
        /* TODO: Will this really work with partial buffers? */
480
481
0
        if (!(*tif->tif_seek)(tif, row - tif->tif_dir.td_row))
482
0
            return (0);
483
0
        tif->tif_dir.td_row = row;
484
0
    }
485
486
0
    return (1);
487
0
}
488
489
int TIFFReadScanline(TIFF *tif, void *buf, uint32_t row, uint16_t sample)
490
0
{
491
0
    int e;
492
493
0
    if (!TIFFCheckRead(tif, 0))
494
0
        return (-1);
495
0
    if ((e = TIFFSeek(tif, row, sample)) != 0)
496
0
    {
497
        /*
498
         * Decompress desired row into user buffer.
499
         */
500
0
        e = (*tif->tif_decoderow)(tif, (uint8_t *)buf,
501
0
                                  tif->tif_dir.td_scanlinesize, sample);
502
503
        /* we are now poised at the beginning of the next row */
504
0
        tif->tif_dir.td_row = row + 1;
505
506
0
        if (e)
507
0
            (*tif->tif_postdecode)(tif, (uint8_t *)buf,
508
0
                                   tif->tif_dir.td_scanlinesize);
509
0
    }
510
0
    else
511
0
    {
512
        /* See TIFFReadEncodedStrip comment regarding TIFFTAG_FAXFILLFUNC. */
513
0
        if (buf)
514
0
            memset(buf, 0, (size_t)tif->tif_dir.td_scanlinesize);
515
0
    }
516
0
    return (e > 0 ? 1 : -1);
517
0
}
518
519
/*
520
 * Calculate the strip size according to the number of
521
 * rows in the strip (check for truncated last strip on any
522
 * of the separations).
523
 */
524
static tmsize_t TIFFReadEncodedStripGetStripSize(TIFF *tif, uint32_t strip,
525
                                                 uint16_t *pplane)
526
0
{
527
0
    static const char module[] = "TIFFReadEncodedStrip";
528
0
    TIFFDirectory *td = &tif->tif_dir;
529
0
    uint32_t rowsperstrip;
530
0
    uint32_t stripsperplane;
531
0
    uint32_t stripinplane;
532
0
    uint32_t rows;
533
0
    tmsize_t stripsize;
534
0
    if (!TIFFCheckRead(tif, 0))
535
0
        return ((tmsize_t)(-1));
536
0
    if (strip >= td->td_nstrips)
537
0
    {
538
0
        TIFFErrorExtR(tif, module,
539
0
                      "%" PRIu32 ": Strip out of range, max %" PRIu32, strip,
540
0
                      td->td_nstrips);
541
0
        return ((tmsize_t)(-1));
542
0
    }
543
544
0
    rowsperstrip = td->td_rowsperstrip;
545
0
    if (rowsperstrip > td->td_imagelength)
546
0
        rowsperstrip = td->td_imagelength;
547
0
    if (rowsperstrip == 0)
548
0
    {
549
0
        TIFFErrorExtR(tif, module, "rowsperstrip is zero");
550
0
        return ((tmsize_t)(-1));
551
0
    }
552
0
    stripsperplane =
553
0
        TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
554
0
    stripinplane = (strip % stripsperplane);
555
0
    if (pplane)
556
0
        *pplane = (uint16_t)(strip / stripsperplane);
557
0
    rows = td->td_imagelength - stripinplane * rowsperstrip;
558
0
    if (rows > rowsperstrip)
559
0
        rows = rowsperstrip;
560
0
    stripsize = TIFFVStripSize(tif, rows);
561
0
    if (stripsize == 0)
562
0
        return ((tmsize_t)(-1));
563
0
    return stripsize;
564
0
}
565
566
/*
567
 * Read a strip of data and decompress the specified
568
 * amount into the user-supplied buffer.
569
 */
570
tmsize_t TIFFReadEncodedStrip(TIFF *tif, uint32_t strip, void *buf,
571
                              tmsize_t size)
572
0
{
573
0
    static const char module[] = "TIFFReadEncodedStrip";
574
0
    TIFFDirectory *td = &tif->tif_dir;
575
0
    tmsize_t stripsize;
576
0
    uint16_t plane;
577
578
0
    stripsize = TIFFReadEncodedStripGetStripSize(tif, strip, &plane);
579
0
    if (stripsize == ((tmsize_t)(-1)))
580
0
        return ((tmsize_t)(-1));
581
582
    /* shortcut to avoid an extra memcpy() */
583
0
    if (td->td_compression == COMPRESSION_NONE && size != (tmsize_t)(-1) &&
584
0
        size >= stripsize && !isMapped(tif) &&
585
0
        ((tif->tif_flags & TIFF_NOREADRAW) == 0))
586
0
    {
587
0
        if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)
588
0
            return ((tmsize_t)(-1));
589
590
0
        if (!isFillOrder(tif, td->td_fillorder) &&
591
0
            (tif->tif_flags & TIFF_NOBITREV) == 0)
592
0
            TIFFReverseBits((uint8_t *)buf, stripsize);
593
594
0
        (*tif->tif_postdecode)(tif, (uint8_t *)buf, stripsize);
595
0
        return (stripsize);
596
0
    }
597
598
0
    if ((size != (tmsize_t)(-1)) && (size < stripsize))
599
0
        stripsize = size;
600
0
    if (!TIFFFillStrip(tif, strip))
601
0
    {
602
        /* The output buf may be NULL, in particular if TIFFTAG_FAXFILLFUNC
603
           is being used. Thus, memset must be conditional on buf not NULL. */
604
0
        if (buf)
605
0
            memset(buf, 0, (size_t)stripsize);
606
0
        return ((tmsize_t)(-1));
607
0
    }
608
0
    if ((*tif->tif_decodestrip)(tif, (uint8_t *)buf, stripsize, plane) <= 0)
609
0
        return ((tmsize_t)(-1));
610
0
    (*tif->tif_postdecode)(tif, (uint8_t *)buf, stripsize);
611
0
    return (stripsize);
612
0
}
613
614
/* Variant of TIFFReadEncodedStrip() that does
615
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
616
 * TIFFFillStrip() has succeeded. This avoid excessive memory allocation in case
617
 * of truncated file.
618
 * * calls regular TIFFReadEncodedStrip() if *buf != NULL
619
 */
620
tmsize_t _TIFFReadEncodedStripAndAllocBuffer(TIFF *tif, uint32_t strip,
621
                                             void **buf,
622
                                             tmsize_t bufsizetoalloc,
623
                                             tmsize_t size_to_read)
624
0
{
625
0
    tmsize_t this_stripsize;
626
0
    uint16_t plane;
627
628
0
    if (*buf != NULL)
629
0
    {
630
0
        return TIFFReadEncodedStrip(tif, strip, *buf, size_to_read);
631
0
    }
632
633
0
    this_stripsize = TIFFReadEncodedStripGetStripSize(tif, strip, &plane);
634
0
    if (this_stripsize == ((tmsize_t)(-1)))
635
0
        return ((tmsize_t)(-1));
636
637
0
    if ((size_to_read != (tmsize_t)(-1)) && (size_to_read < this_stripsize))
638
0
        this_stripsize = size_to_read;
639
0
    if (!TIFFFillStrip(tif, strip))
640
0
        return ((tmsize_t)(-1));
641
642
    /* Sanity checks to avoid excessive memory allocation */
643
    /* Max compression ratio experimentally determined. Might be fragile...
644
     * Only apply this heuristics to situations where the memory allocation
645
     * would be big, to avoid breaking nominal use cases.
646
     */
647
0
    if (bufsizetoalloc > 100 * 1024 * 1024)
648
0
    {
649
0
        const uint64_t maxCompressionRatio = TIFFGetMaxCompressionRatio(tif);
650
0
        if (maxCompressionRatio > 0 &&
651
0
            (uint64_t)tif->tif_rawdatasize <
652
0
                (uint64_t)this_stripsize / maxCompressionRatio)
653
0
        {
654
0
            TIFFErrorExtR(tif, TIFFFileName(tif),
655
0
                          "Likely invalid strip byte count for strip %u. "
656
0
                          "Uncompressed strip size is %" PRIu64 ", "
657
0
                          "compressed one is %" PRIu64,
658
0
                          strip, (uint64_t)this_stripsize,
659
0
                          (uint64_t)tif->tif_rawdatasize);
660
0
            return ((tmsize_t)(-1));
661
0
        }
662
0
    }
663
664
0
    *buf = _TIFFcallocExt(tif, 1, bufsizetoalloc);
665
0
    if (*buf == NULL)
666
0
    {
667
0
        TIFFErrorExtR(tif, TIFFFileName(tif), "No space for strip buffer");
668
0
        return ((tmsize_t)(-1));
669
0
    }
670
671
0
    if ((*tif->tif_decodestrip)(tif, (uint8_t *)*buf, this_stripsize, plane) <=
672
0
        0)
673
0
        return ((tmsize_t)(-1));
674
0
    (*tif->tif_postdecode)(tif, (uint8_t *)*buf, this_stripsize);
675
0
    return (this_stripsize);
676
0
}
677
678
static tmsize_t TIFFReadRawStrip1(TIFF *tif, uint32_t strip, void *buf,
679
                                  tmsize_t size, const char *module)
680
0
{
681
0
    assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
682
0
    if (!isMapped(tif))
683
0
    {
684
0
        tmsize_t cc;
685
686
0
        if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip)))
687
0
        {
688
0
            TIFFErrorExtR(tif, module,
689
0
                          "Seek error at scanline %" PRIu32 ", strip %" PRIu32,
690
0
                          tif->tif_dir.td_row, strip);
691
0
            return ((tmsize_t)(-1));
692
0
        }
693
0
        cc = TIFFReadFile(tif, buf, size);
694
0
        if (cc != size)
695
0
        {
696
0
            TIFFErrorExtR(tif, module,
697
0
                          "Read error at scanline %" PRIu32
698
0
                          "; got %" TIFF_SSIZE_FORMAT
699
0
                          " bytes, expected %" TIFF_SSIZE_FORMAT,
700
0
                          tif->tif_dir.td_row, cc, size);
701
0
            return ((tmsize_t)(-1));
702
0
        }
703
0
    }
704
0
    else
705
0
    {
706
0
        tmsize_t ma = 0;
707
0
        tmsize_t n;
708
0
        if ((TIFFGetStrileOffset(tif, strip) > (uint64_t)TIFF_TMSIZE_T_MAX) ||
709
0
            ((ma = (tmsize_t)TIFFGetStrileOffset(tif, strip)) > tif->tif_size))
710
0
        {
711
0
            n = 0;
712
0
        }
713
0
        else if (ma > TIFF_TMSIZE_T_MAX - size)
714
0
        {
715
0
            n = 0;
716
0
        }
717
0
        else
718
0
        {
719
0
            tmsize_t mb = ma + size;
720
0
            if (mb > tif->tif_size)
721
0
                n = tif->tif_size - ma;
722
0
            else
723
0
                n = size;
724
0
        }
725
0
        if (n != size)
726
0
        {
727
0
            TIFFErrorExtR(tif, module,
728
0
                          "Read error at scanline %" PRIu32 ", strip %" PRIu32
729
0
                          "; got %" TIFF_SSIZE_FORMAT
730
0
                          " bytes, expected %" TIFF_SSIZE_FORMAT,
731
0
                          tif->tif_dir.td_row, strip, n, size);
732
0
            return ((tmsize_t)(-1));
733
0
        }
734
0
        _TIFFmemcpy(buf, tif->tif_base + ma, size);
735
0
    }
736
0
    return (size);
737
0
}
738
739
static tmsize_t TIFFReadRawStripOrTile2(TIFF *tif, uint32_t strip_or_tile,
740
                                        int is_strip, tmsize_t size,
741
                                        const char *module)
742
0
{
743
0
    assert(!isMapped(tif));
744
0
    assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
745
746
0
    if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip_or_tile)))
747
0
    {
748
0
        if (is_strip)
749
0
        {
750
0
            TIFFErrorExtR(tif, module,
751
0
                          "Seek error at scanline %" PRIu32 ", strip %" PRIu32,
752
0
                          tif->tif_dir.td_row, strip_or_tile);
753
0
        }
754
0
        else
755
0
        {
756
0
            TIFFErrorExtR(
757
0
                tif, module,
758
0
                "Seek error at row %" PRIu32 ", col %" PRIu32 ", tile %" PRIu32,
759
0
                tif->tif_dir.td_row, tif->tif_dir.td_col, strip_or_tile);
760
0
        }
761
0
        return ((tmsize_t)(-1));
762
0
    }
763
764
0
    if (!TIFFReadAndRealloc(tif, size, 0, is_strip, strip_or_tile, module))
765
0
    {
766
0
        return ((tmsize_t)(-1));
767
0
    }
768
769
0
    return (size);
770
0
}
771
772
/*
773
 * Read a strip of data from the file.
774
 */
775
tmsize_t TIFFReadRawStrip(TIFF *tif, uint32_t strip, void *buf, tmsize_t size)
776
0
{
777
0
    static const char module[] = "TIFFReadRawStrip";
778
0
    TIFFDirectory *td = &tif->tif_dir;
779
0
    uint64_t bytecount64;
780
0
    tmsize_t bytecountm;
781
782
0
    if (!TIFFCheckRead(tif, 0))
783
0
        return ((tmsize_t)(-1));
784
0
    if (strip >= td->td_nstrips)
785
0
    {
786
0
        TIFFErrorExtR(tif, module,
787
0
                      "%" PRIu32 ": Strip out of range, max %" PRIu32, strip,
788
0
                      td->td_nstrips);
789
0
        return ((tmsize_t)(-1));
790
0
    }
791
0
    if (tif->tif_flags & TIFF_NOREADRAW)
792
0
    {
793
0
        TIFFErrorExtR(tif, module,
794
0
                      "Compression scheme does not support access to raw "
795
0
                      "uncompressed data");
796
0
        return ((tmsize_t)(-1));
797
0
    }
798
0
    bytecount64 = TIFFGetStrileByteCount(tif, strip);
799
0
    if (size != (tmsize_t)(-1) && (uint64_t)size <= bytecount64)
800
0
        bytecountm = size;
801
0
    else
802
0
        bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
803
0
    if (bytecountm == 0)
804
0
    {
805
0
        return ((tmsize_t)(-1));
806
0
    }
807
0
    return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module));
808
0
}
809
810
TIFF_NOSANITIZE_UNSIGNED_INT_OVERFLOW
811
0
static uint64_t NoSanitizeSubUInt64(uint64_t a, uint64_t b) { return a - b; }
812
813
/*
814
 * Read the specified strip and setup for decoding. The data buffer is
815
 * expanded, as necessary, to hold the strip's data.
816
 */
817
int TIFFFillStrip(TIFF *tif, uint32_t strip)
818
0
{
819
0
    static const char module[] = "TIFFFillStrip";
820
0
    TIFFDirectory *td = &tif->tif_dir;
821
822
0
    if ((tif->tif_flags & TIFF_NOREADRAW) == 0)
823
0
    {
824
0
        uint64_t bytecount = TIFFGetStrileByteCount(tif, strip);
825
0
        if (bytecount == 0 || bytecount > (uint64_t)TIFF_INT64_MAX)
826
0
        {
827
0
            TIFFErrorExtR(tif, module,
828
0
                          "Invalid strip byte count %" PRIu64
829
0
                          ", strip %" PRIu32,
830
0
                          bytecount, strip);
831
0
            return (0);
832
0
        }
833
834
        /* To avoid excessive memory allocations: */
835
0
        const tmsize_t stripsize = TIFFStripSize(tif);
836
0
        if (stripsize > 0)
837
0
        {
838
0
            if (bytecount > 1024 * 1024 &&
839
0
                (bytecount - 4096) / 10 > (uint64_t)stripsize)
840
0
            {
841
                /* Byte count should normally not be larger than a number of */
842
                /* times the uncompressed size plus some margin */
843
                /* 10 and 4096 are just values that could be adjusted. */
844
                /* Hopefully they are safe enough for all codecs */
845
                /* What happens next will depend on whether only the bytecount
846
                 */
847
                /* was corrupted to a large value but the strip/tile data is */
848
                /* fine. In that situation most codecs should work fine and */
849
                /* only used part of the tile/strip data. If the strip/tile */
850
                /* data is corrupted too, then codecs will later error out. */
851
0
                uint64_t newbytecount = (uint64_t)stripsize * 10 + 4096;
852
0
                TIFFWarningExtR(tif, module,
853
0
                                "Too large strip byte count %" PRIu64
854
0
                                ", strip %" PRIu32 ". Limiting to %" PRIu64,
855
0
                                bytecount, strip, newbytecount);
856
0
                bytecount = newbytecount;
857
0
            }
858
0
            else if (stripsize > 100 * 1024 * 1024)
859
0
            {
860
                /* Max compression ratio experimentally determined. Might be
861
                 * fragile... Only apply this heuristics to situations where the
862
                 * memory allocation would be big, to avoid breaking nominal use
863
                 * cases.
864
                 */
865
0
                const uint64_t maxCompressionRatio =
866
0
                    TIFFGetMaxCompressionRatio(tif);
867
0
                if (maxCompressionRatio > 0 &&
868
0
                    bytecount < (uint64_t)stripsize / maxCompressionRatio)
869
0
                {
870
0
                    TIFFErrorExtR(
871
0
                        tif, module,
872
0
                        "Likely invalid strip byte count for strip %u. "
873
0
                        "Uncompressed strip size is %" PRIu64 ", "
874
0
                        "compressed one is %" PRIu64,
875
0
                        strip, (uint64_t)stripsize, bytecount);
876
0
                    return 0;
877
0
                }
878
0
            }
879
0
        }
880
881
0
        if (isMapped(tif))
882
0
        {
883
            /*
884
             * We must check for overflow, potentially causing
885
             * an OOB read. Instead of simple
886
             *
887
             *  TIFFGetStrileOffset(tif, strip)+bytecount > tif->tif_size
888
             *
889
             * comparison (which can overflow) we do the following
890
             * two comparisons:
891
             */
892
0
            if (bytecount > (uint64_t)tif->tif_size ||
893
0
                TIFFGetStrileOffset(tif, strip) >
894
0
                    (uint64_t)tif->tif_size - bytecount)
895
0
            {
896
                /*
897
                 * This error message might seem strange, but
898
                 * it's what would happen if a read were done
899
                 * instead.
900
                 */
901
0
                TIFFErrorExtR(
902
0
                    tif, module,
903
904
0
                    "Read error on strip %" PRIu32 "; "
905
0
                    "got %" PRIu64 " bytes, expected %" PRIu64,
906
0
                    strip,
907
0
                    NoSanitizeSubUInt64((uint64_t)tif->tif_size,
908
0
                                        TIFFGetStrileOffset(tif, strip)),
909
0
                    bytecount);
910
0
                tif->tif_dir.td_curstrip = NOSTRIP;
911
0
                return (0);
912
0
            }
913
0
        }
914
915
0
        if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) ||
916
0
                              (tif->tif_flags & TIFF_NOBITREV)))
917
0
        {
918
            /*
919
             * The image is mapped into memory and we either don't
920
             * need to flip bits or the compression routine is
921
             * going to handle this operation itself.  In this
922
             * case, avoid copying the raw data and instead just
923
             * reference the data from the memory mapped file
924
             * image.  This assumes that the decompression
925
             * routines do not modify the contents of the raw data
926
             * buffer (if they try to, the application will get a
927
             * fault since the file is mapped read-only).
928
             */
929
0
            if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
930
0
            {
931
0
                _TIFFfreeExt(tif, tif->tif_rawdata);
932
0
                tif->tif_rawdata = NULL;
933
0
                tif->tif_rawdatasize = 0;
934
0
            }
935
0
            tif->tif_flags &= ~TIFF_MYBUFFER;
936
0
            tif->tif_rawdatasize = (tmsize_t)bytecount;
937
0
            tif->tif_rawdata =
938
0
                tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, strip);
939
0
            tif->tif_rawdataoff = 0;
940
0
            tif->tif_rawdataloaded = (tmsize_t)bytecount;
941
942
            /*
943
             * When we have tif_rawdata reference directly into the memory
944
             * mapped file we need to be pretty careful about how we use the
945
             * rawdata.  It is not a general purpose working buffer as it
946
             * normally otherwise is.  So we keep track of this fact to avoid
947
             * using it improperly.
948
             */
949
0
            tif->tif_flags |= TIFF_BUFFERMMAP;
950
0
        }
951
0
        else
952
0
        {
953
            /*
954
             * Expand raw data buffer, if needed, to hold data
955
             * strip coming from file (perhaps should set upper
956
             * bound on the size of a buffer we'll use?).
957
             */
958
0
            tmsize_t bytecountm;
959
0
            bytecountm = (tmsize_t)bytecount;
960
0
            if ((uint64_t)bytecountm != bytecount)
961
0
            {
962
0
                TIFFErrorExtR(tif, module, "Integer overflow");
963
0
                return (0);
964
0
            }
965
0
            if (bytecountm > tif->tif_rawdatasize)
966
0
            {
967
0
                tif->tif_dir.td_curstrip = NOSTRIP;
968
0
                if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
969
0
                {
970
0
                    TIFFErrorExtR(
971
0
                        tif, module,
972
0
                        "Data buffer too small to hold strip %" PRIu32, strip);
973
0
                    return (0);
974
0
                }
975
0
            }
976
0
            if (tif->tif_flags & TIFF_BUFFERMMAP)
977
0
            {
978
0
                tif->tif_dir.td_curstrip = NOSTRIP;
979
0
                tif->tif_rawdata = NULL;
980
0
                tif->tif_rawdatasize = 0;
981
0
                tif->tif_flags &= ~TIFF_BUFFERMMAP;
982
0
            }
983
984
0
            if (isMapped(tif))
985
0
            {
986
0
                if (bytecountm > tif->tif_rawdatasize &&
987
0
                    !TIFFReadBufferSetup(tif, 0, bytecountm))
988
0
                {
989
0
                    return (0);
990
0
                }
991
0
                if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm,
992
0
                                      module) != bytecountm)
993
0
                {
994
0
                    return (0);
995
0
                }
996
0
            }
997
0
            else
998
0
            {
999
0
                if (TIFFReadRawStripOrTile2(tif, strip, 1, bytecountm,
1000
0
                                            module) != bytecountm)
1001
0
                {
1002
0
                    return (0);
1003
0
                }
1004
0
            }
1005
1006
0
            tif->tif_rawdataoff = 0;
1007
0
            tif->tif_rawdataloaded = bytecountm;
1008
1009
0
            if (!isFillOrder(tif, td->td_fillorder) &&
1010
0
                (tif->tif_flags & TIFF_NOBITREV) == 0)
1011
0
                TIFFReverseBits(tif->tif_rawdata, bytecountm);
1012
0
        }
1013
0
    }
1014
0
    return (TIFFStartStrip(tif, strip));
1015
0
}
1016
1017
/*
1018
 * Tile-oriented Read Support
1019
 * Contributed by Nancy Cam (Silicon Graphics).
1020
 */
1021
1022
/*
1023
 * Read and decompress a tile of data.  The
1024
 * tile is selected by the (x,y,z,s) coordinates.
1025
 */
1026
tmsize_t TIFFReadTile(TIFF *tif, void *buf, uint32_t x, uint32_t y, uint32_t z,
1027
                      uint16_t s)
1028
0
{
1029
0
    if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
1030
0
        return ((tmsize_t)(-1));
1031
0
    return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf,
1032
0
                                (tmsize_t)(-1)));
1033
0
}
1034
1035
/*
1036
 * Read a tile of data and decompress the specified
1037
 * amount into the user-supplied buffer.
1038
 */
1039
tmsize_t TIFFReadEncodedTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
1040
0
{
1041
0
    static const char module[] = "TIFFReadEncodedTile";
1042
0
    TIFFDirectory *td = &tif->tif_dir;
1043
0
    tmsize_t tilesize = tif->tif_dir.td_tilesize;
1044
1045
0
    if (!TIFFCheckRead(tif, 1))
1046
0
        return ((tmsize_t)(-1));
1047
0
    if (tile >= td->td_nstrips)
1048
0
    {
1049
0
        TIFFErrorExtR(tif, module,
1050
0
                      "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1051
0
                      td->td_nstrips);
1052
0
        return ((tmsize_t)(-1));
1053
0
    }
1054
1055
    /* shortcut to avoid an extra memcpy() */
1056
0
    if (td->td_compression == COMPRESSION_NONE && size != (tmsize_t)(-1) &&
1057
0
        size >= tilesize && !isMapped(tif) &&
1058
0
        ((tif->tif_flags & TIFF_NOREADRAW) == 0))
1059
0
    {
1060
0
        if (TIFFReadRawTile1(tif, tile, buf, tilesize, module) != tilesize)
1061
0
            return ((tmsize_t)(-1));
1062
1063
0
        if (!isFillOrder(tif, td->td_fillorder) &&
1064
0
            (tif->tif_flags & TIFF_NOBITREV) == 0)
1065
0
            TIFFReverseBits((uint8_t *)buf, tilesize);
1066
1067
0
        (*tif->tif_postdecode)(tif, (uint8_t *)buf, tilesize);
1068
0
        return (tilesize);
1069
0
    }
1070
1071
0
    if (size == (tmsize_t)(-1))
1072
0
        size = tilesize;
1073
0
    else if (size > tilesize)
1074
0
        size = tilesize;
1075
0
    if (!TIFFFillTile(tif, tile))
1076
0
    {
1077
        /* See TIFFReadEncodedStrip comment regarding TIFFTAG_FAXFILLFUNC. */
1078
0
        if (buf)
1079
0
            memset(buf, 0, (size_t)size);
1080
0
        return ((tmsize_t)(-1));
1081
0
    }
1082
0
    else if ((*tif->tif_decodetile)(tif, (uint8_t *)buf, size,
1083
0
                                    (uint16_t)(tile / td->td_stripsperimage)))
1084
0
    {
1085
0
        (*tif->tif_postdecode)(tif, (uint8_t *)buf, size);
1086
0
        return (size);
1087
0
    }
1088
0
    else
1089
0
        return ((tmsize_t)(-1));
1090
0
}
1091
1092
/* Variant of TIFFReadTile() that does
1093
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
1094
 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
1095
 * of truncated file.
1096
 * * calls regular TIFFReadEncodedTile() if *buf != NULL
1097
 */
1098
tmsize_t _TIFFReadTileAndAllocBuffer(TIFF *tif, void **buf,
1099
                                     tmsize_t bufsizetoalloc, uint32_t x,
1100
                                     uint32_t y, uint32_t z, uint16_t s)
1101
0
{
1102
0
    if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
1103
0
        return ((tmsize_t)(-1));
1104
0
    return (_TIFFReadEncodedTileAndAllocBuffer(
1105
0
        tif, TIFFComputeTile(tif, x, y, z, s), buf, bufsizetoalloc,
1106
0
        (tmsize_t)(-1)));
1107
0
}
1108
1109
/* Variant of TIFFReadEncodedTile() that does
1110
 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
1111
 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
1112
 * of truncated file.
1113
 * * calls regular TIFFReadEncodedTile() if *buf != NULL
1114
 */
1115
tmsize_t _TIFFReadEncodedTileAndAllocBuffer(TIFF *tif, uint32_t tile,
1116
                                            void **buf, tmsize_t bufsizetoalloc,
1117
                                            tmsize_t size_to_read)
1118
0
{
1119
0
    static const char module[] = "_TIFFReadEncodedTileAndAllocBuffer";
1120
0
    TIFFDirectory *td = &tif->tif_dir;
1121
0
    tmsize_t tilesize = tif->tif_dir.td_tilesize;
1122
1123
0
    if (*buf != NULL)
1124
0
    {
1125
0
        return TIFFReadEncodedTile(tif, tile, *buf, size_to_read);
1126
0
    }
1127
1128
0
    if (!TIFFCheckRead(tif, 1))
1129
0
        return ((tmsize_t)(-1));
1130
0
    if (tile >= td->td_nstrips)
1131
0
    {
1132
0
        TIFFErrorExtR(tif, module,
1133
0
                      "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1134
0
                      td->td_nstrips);
1135
0
        return ((tmsize_t)(-1));
1136
0
    }
1137
1138
0
    if (!TIFFFillTile(tif, tile))
1139
0
        return ((tmsize_t)(-1));
1140
1141
    /* Sanity checks to avoid excessive memory allocation */
1142
    /* Cf https://gitlab.com/libtiff/libtiff/-/issues/479 */
1143
0
    if (td->td_compression == COMPRESSION_NONE)
1144
0
    {
1145
0
        if (tif->tif_rawdatasize != tilesize)
1146
0
        {
1147
0
            TIFFErrorExtR(tif, TIFFFileName(tif),
1148
0
                          "Invalid tile byte count for tile %u. "
1149
0
                          "Expected %" PRIu64 ", got %" PRIu64,
1150
0
                          tile, (uint64_t)tilesize,
1151
0
                          (uint64_t)tif->tif_rawdatasize);
1152
0
            return ((tmsize_t)(-1));
1153
0
        }
1154
0
    }
1155
0
    else
1156
0
    {
1157
        /* Max compression ratio experimentally determined. Might be fragile...
1158
         * Only apply this heuristics to situations where the memory allocation
1159
         * would be big, to avoid breaking nominal use cases.
1160
         */
1161
0
        if (bufsizetoalloc > 100 * 1024 * 1024)
1162
0
        {
1163
0
            const uint64_t maxCompressionRatio =
1164
0
                TIFFGetMaxCompressionRatio(tif);
1165
0
            if (maxCompressionRatio > 0 &&
1166
0
                (uint64_t)tif->tif_rawdatasize <
1167
0
                    (uint64_t)tilesize / maxCompressionRatio)
1168
0
            {
1169
0
                TIFFErrorExtR(tif, TIFFFileName(tif),
1170
0
                              "Likely invalid tile byte count for tile %u. "
1171
0
                              "Uncompressed tile size is %" PRIu64 ", "
1172
0
                              "compressed one is %" PRIu64,
1173
0
                              tile, (uint64_t)tilesize,
1174
0
                              (uint64_t)tif->tif_rawdatasize);
1175
0
                return ((tmsize_t)(-1));
1176
0
            }
1177
0
        }
1178
0
    }
1179
1180
0
    *buf = _TIFFmallocExt(tif, bufsizetoalloc);
1181
0
    if (*buf == NULL)
1182
0
    {
1183
0
        TIFFErrorExtR(tif, TIFFFileName(tif), "No space for tile buffer");
1184
0
        return ((tmsize_t)(-1));
1185
0
    }
1186
0
    _TIFFmemset(*buf, 0, bufsizetoalloc);
1187
1188
0
    if (size_to_read == (tmsize_t)(-1))
1189
0
        size_to_read = tilesize;
1190
0
    else if (size_to_read > tilesize)
1191
0
        size_to_read = tilesize;
1192
0
    if ((*tif->tif_decodetile)(tif, (uint8_t *)*buf, size_to_read,
1193
0
                               (uint16_t)(tile / td->td_stripsperimage)))
1194
0
    {
1195
0
        (*tif->tif_postdecode)(tif, (uint8_t *)*buf, size_to_read);
1196
0
        return (size_to_read);
1197
0
    }
1198
0
    else
1199
0
        return ((tmsize_t)(-1));
1200
0
}
1201
1202
static tmsize_t TIFFReadRawTile1(TIFF *tif, uint32_t tile, void *buf,
1203
                                 tmsize_t size, const char *module)
1204
0
{
1205
0
    assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
1206
0
    if (!isMapped(tif))
1207
0
    {
1208
0
        tmsize_t cc;
1209
1210
0
        if (!SeekOK(tif, TIFFGetStrileOffset(tif, tile)))
1211
0
        {
1212
0
            TIFFErrorExtR(tif, module,
1213
0
                          "Seek error at row %" PRIu32 ", col %" PRIu32
1214
0
                          ", tile %" PRIu32,
1215
0
                          tif->tif_dir.td_row, tif->tif_dir.td_col, tile);
1216
0
            return ((tmsize_t)(-1));
1217
0
        }
1218
0
        cc = TIFFReadFile(tif, buf, size);
1219
0
        if (cc != size)
1220
0
        {
1221
0
            TIFFErrorExtR(tif, module,
1222
0
                          "Read error at row %" PRIu32 ", col %" PRIu32
1223
0
                          "; got %" TIFF_SSIZE_FORMAT
1224
0
                          " bytes, expected %" TIFF_SSIZE_FORMAT,
1225
0
                          tif->tif_dir.td_row, tif->tif_dir.td_col, cc, size);
1226
0
            return ((tmsize_t)(-1));
1227
0
        }
1228
0
    }
1229
0
    else
1230
0
    {
1231
0
        tmsize_t ma, mb;
1232
0
        tmsize_t n;
1233
0
        ma = (tmsize_t)TIFFGetStrileOffset(tif, tile);
1234
0
        mb = ma + size;
1235
0
        if ((TIFFGetStrileOffset(tif, tile) > (uint64_t)TIFF_TMSIZE_T_MAX) ||
1236
0
            (ma > tif->tif_size))
1237
0
            n = 0;
1238
0
        else if ((mb < ma) || (mb < size) || (mb > tif->tif_size))
1239
0
            n = tif->tif_size - ma;
1240
0
        else
1241
0
            n = size;
1242
0
        if (n != size)
1243
0
        {
1244
0
            TIFFErrorExtR(tif, module,
1245
0
                          "Read error at row %" PRIu32 ", col %" PRIu32
1246
0
                          ", tile %" PRIu32 "; got %" TIFF_SSIZE_FORMAT
1247
0
                          " bytes, expected %" TIFF_SSIZE_FORMAT,
1248
0
                          tif->tif_dir.td_row, tif->tif_dir.td_col, tile, n,
1249
0
                          size);
1250
0
            return ((tmsize_t)(-1));
1251
0
        }
1252
0
        _TIFFmemcpy(buf, tif->tif_base + ma, size);
1253
0
    }
1254
0
    return (size);
1255
0
}
1256
1257
/*
1258
 * Read a tile of data from the file.
1259
 */
1260
tmsize_t TIFFReadRawTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
1261
0
{
1262
0
    static const char module[] = "TIFFReadRawTile";
1263
0
    TIFFDirectory *td = &tif->tif_dir;
1264
0
    uint64_t bytecount64;
1265
0
    tmsize_t bytecountm;
1266
1267
0
    if (!TIFFCheckRead(tif, 1))
1268
0
        return ((tmsize_t)(-1));
1269
0
    if (tile >= td->td_nstrips)
1270
0
    {
1271
0
        TIFFErrorExtR(tif, module,
1272
0
                      "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1273
0
                      td->td_nstrips);
1274
0
        return ((tmsize_t)(-1));
1275
0
    }
1276
0
    if (tif->tif_flags & TIFF_NOREADRAW)
1277
0
    {
1278
0
        TIFFErrorExtR(tif, module,
1279
0
                      "Compression scheme does not support access to raw "
1280
0
                      "uncompressed data");
1281
0
        return ((tmsize_t)(-1));
1282
0
    }
1283
0
    bytecount64 = TIFFGetStrileByteCount(tif, tile);
1284
0
    if (size != (tmsize_t)(-1) && (uint64_t)size <= bytecount64)
1285
0
        bytecountm = size;
1286
0
    else
1287
0
        bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
1288
0
    if (bytecountm == 0)
1289
0
    {
1290
0
        return ((tmsize_t)(-1));
1291
0
    }
1292
0
    return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module));
1293
0
}
1294
1295
/*
1296
 * Read the specified tile and setup for decoding. The data buffer is
1297
 * expanded, as necessary, to hold the tile's data.
1298
 */
1299
int TIFFFillTile(TIFF *tif, uint32_t tile)
1300
0
{
1301
0
    static const char module[] = "TIFFFillTile";
1302
0
    TIFFDirectory *td = &tif->tif_dir;
1303
1304
0
    if ((tif->tif_flags & TIFF_NOREADRAW) == 0)
1305
0
    {
1306
0
        uint64_t bytecount = TIFFGetStrileByteCount(tif, tile);
1307
0
        if (bytecount == 0 || bytecount > (uint64_t)TIFF_INT64_MAX)
1308
0
        {
1309
0
            TIFFErrorExtR(tif, module,
1310
0
                          "%" PRIu64 ": Invalid tile byte count, tile %" PRIu32,
1311
0
                          bytecount, tile);
1312
0
            return (0);
1313
0
        }
1314
1315
        /* To avoid excessive memory allocations: */
1316
0
        const tmsize_t tilesize = TIFFTileSize(tif);
1317
0
        if (tilesize > 0)
1318
0
        {
1319
0
            if (bytecount > 1024 * 1024 &&
1320
0
                (bytecount - 4096) / 10 > (uint64_t)tilesize)
1321
0
            {
1322
                /* Byte count should normally not be larger than a number of */
1323
                /* times the uncompressed size plus some margin */
1324
                /* 10 and 4096 are just values that could be adjusted. */
1325
                /* Hopefully they are safe enough for all codecs */
1326
                /* What happens next will depend on whether only the bytecount
1327
                 */
1328
                /* was corrupted to a large value but the strip/tile data is */
1329
                /* fine. In that situation most codecs should work fine and */
1330
                /* only used part of the tile/strip data. If the strip/tile */
1331
                /* data is corrupted too, then codecs will later error out. */
1332
0
                uint64_t newbytecount = (uint64_t)tilesize * 10 + 4096;
1333
0
                TIFFWarningExtR(tif, module,
1334
0
                                "Too large tile byte count %" PRIu64
1335
0
                                ", tile %" PRIu32 ". Limiting to %" PRIu64,
1336
0
                                bytecount, tile, newbytecount);
1337
0
                bytecount = newbytecount;
1338
0
            }
1339
0
            else if (tilesize > 100 * 1024 * 1024)
1340
0
            {
1341
                /* Max compression ratio experimentally determined. Might be
1342
                 * fragile... Only apply this heuristics to situations where the
1343
                 * memory allocation would be big, to avoid breaking nominal use
1344
                 * cases.
1345
                 */
1346
0
                const uint64_t maxCompressionRatio =
1347
0
                    TIFFGetMaxCompressionRatio(tif);
1348
0
                if (maxCompressionRatio > 0 &&
1349
0
                    bytecount < (uint64_t)tilesize / maxCompressionRatio)
1350
0
                {
1351
0
                    TIFFErrorExtR(tif, module,
1352
0
                                  "Likely invalid tile byte count for tile %u. "
1353
0
                                  "Uncompressed tile size is %" PRIu64 ", "
1354
0
                                  "compressed one is %" PRIu64,
1355
0
                                  tile, (uint64_t)tilesize, bytecount);
1356
0
                    return 0;
1357
0
                }
1358
0
            }
1359
0
        }
1360
1361
0
        if (isMapped(tif))
1362
0
        {
1363
            /*
1364
             * We must check for overflow, potentially causing
1365
             * an OOB read. Instead of simple
1366
             *
1367
             *  TIFFGetStrileOffset(tif, tile)+bytecount > tif->tif_size
1368
             *
1369
             * comparison (which can overflow) we do the following
1370
             * two comparisons:
1371
             */
1372
0
            if (bytecount > (uint64_t)tif->tif_size ||
1373
0
                TIFFGetStrileOffset(tif, tile) >
1374
0
                    (uint64_t)tif->tif_size - bytecount)
1375
0
            {
1376
0
                tif->tif_dir.td_curtile = NOTILE;
1377
0
                return (0);
1378
0
            }
1379
0
        }
1380
1381
0
        if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) ||
1382
0
                              (tif->tif_flags & TIFF_NOBITREV)))
1383
0
        {
1384
            /*
1385
             * The image is mapped into memory and we either don't
1386
             * need to flip bits or the compression routine is
1387
             * going to handle this operation itself.  In this
1388
             * case, avoid copying the raw data and instead just
1389
             * reference the data from the memory mapped file
1390
             * image.  This assumes that the decompression
1391
             * routines do not modify the contents of the raw data
1392
             * buffer (if they try to, the application will get a
1393
             * fault since the file is mapped read-only).
1394
             */
1395
0
            if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
1396
0
            {
1397
0
                _TIFFfreeExt(tif, tif->tif_rawdata);
1398
0
                tif->tif_rawdata = NULL;
1399
0
                tif->tif_rawdatasize = 0;
1400
0
            }
1401
0
            tif->tif_flags &= ~TIFF_MYBUFFER;
1402
1403
0
            tif->tif_rawdatasize = (tmsize_t)bytecount;
1404
0
            tif->tif_rawdata =
1405
0
                tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, tile);
1406
0
            tif->tif_rawdataoff = 0;
1407
0
            tif->tif_rawdataloaded = (tmsize_t)bytecount;
1408
0
            tif->tif_flags |= TIFF_BUFFERMMAP;
1409
0
        }
1410
0
        else
1411
0
        {
1412
            /*
1413
             * Expand raw data buffer, if needed, to hold data
1414
             * tile coming from file (perhaps should set upper
1415
             * bound on the size of a buffer we'll use?).
1416
             */
1417
0
            tmsize_t bytecountm;
1418
0
            bytecountm = (tmsize_t)bytecount;
1419
0
            if ((uint64_t)bytecountm != bytecount)
1420
0
            {
1421
0
                TIFFErrorExtR(tif, module, "Integer overflow");
1422
0
                return (0);
1423
0
            }
1424
0
            if (bytecountm > tif->tif_rawdatasize)
1425
0
            {
1426
0
                tif->tif_dir.td_curtile = NOTILE;
1427
0
                if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
1428
0
                {
1429
0
                    TIFFErrorExtR(tif, module,
1430
0
                                  "Data buffer too small to hold tile %" PRIu32,
1431
0
                                  tile);
1432
0
                    return (0);
1433
0
                }
1434
0
            }
1435
0
            if (tif->tif_flags & TIFF_BUFFERMMAP)
1436
0
            {
1437
0
                tif->tif_dir.td_curtile = NOTILE;
1438
0
                tif->tif_rawdata = NULL;
1439
0
                tif->tif_rawdatasize = 0;
1440
0
                tif->tif_flags &= ~TIFF_BUFFERMMAP;
1441
0
            }
1442
1443
0
            if (isMapped(tif))
1444
0
            {
1445
0
                if (bytecountm > tif->tif_rawdatasize &&
1446
0
                    !TIFFReadBufferSetup(tif, 0, bytecountm))
1447
0
                {
1448
0
                    return (0);
1449
0
                }
1450
0
                if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm,
1451
0
                                     module) != bytecountm)
1452
0
                {
1453
0
                    return (0);
1454
0
                }
1455
0
            }
1456
0
            else
1457
0
            {
1458
0
                if (TIFFReadRawStripOrTile2(tif, tile, 0, bytecountm, module) !=
1459
0
                    bytecountm)
1460
0
                {
1461
0
                    return (0);
1462
0
                }
1463
0
            }
1464
1465
0
            tif->tif_rawdataoff = 0;
1466
0
            tif->tif_rawdataloaded = bytecountm;
1467
1468
0
            if (tif->tif_rawdata != NULL &&
1469
0
                !isFillOrder(tif, td->td_fillorder) &&
1470
0
                (tif->tif_flags & TIFF_NOBITREV) == 0)
1471
0
                TIFFReverseBits(tif->tif_rawdata, tif->tif_rawdataloaded);
1472
0
        }
1473
0
    }
1474
0
    return (TIFFStartTile(tif, tile));
1475
0
}
1476
1477
/*
1478
 * Setup the raw data buffer in preparation for
1479
 * reading a strip of raw data.  If the buffer
1480
 * is specified as zero, then a buffer of appropriate
1481
 * size is allocated by the library.  Otherwise,
1482
 * the client must guarantee that the buffer is
1483
 * large enough to hold any individual strip of
1484
 * raw data.
1485
 */
1486
int TIFFReadBufferSetup(TIFF *tif, void *bp, tmsize_t size)
1487
0
{
1488
0
    static const char module[] = "TIFFReadBufferSetup";
1489
1490
0
    if (tif->tif_flags & TIFF_NOREADRAW)
1491
0
    {
1492
0
        TIFFErrorExtR(tif, module,
1493
0
                      "Compression scheme does not support access to raw "
1494
0
                      "uncompressed data");
1495
0
        return (0);
1496
0
    }
1497
0
    tif->tif_flags &= ~TIFF_BUFFERMMAP;
1498
1499
0
    if (tif->tif_rawdata)
1500
0
    {
1501
0
        if (tif->tif_flags & TIFF_MYBUFFER)
1502
0
            _TIFFfreeExt(tif, tif->tif_rawdata);
1503
0
        tif->tif_rawdata = NULL;
1504
0
        tif->tif_rawdatasize = 0;
1505
0
    }
1506
0
    if (bp)
1507
0
    {
1508
0
        tif->tif_rawdatasize = size;
1509
0
        tif->tif_rawdata = (uint8_t *)bp;
1510
0
        tif->tif_flags &= ~TIFF_MYBUFFER;
1511
0
    }
1512
0
    else
1513
0
    {
1514
0
        tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64_t)size, 1024);
1515
0
        if (tif->tif_rawdatasize == 0)
1516
0
        {
1517
0
            TIFFErrorExtR(tif, module, "Invalid buffer size");
1518
0
            return (0);
1519
0
        }
1520
        /* Initialize to zero to avoid uninitialized buffers in case of */
1521
        /* short reads (http://bugzilla.maptools.org/show_bug.cgi?id=2651) */
1522
0
        tif->tif_rawdata =
1523
0
            (uint8_t *)_TIFFcallocExt(tif, 1, tif->tif_rawdatasize);
1524
0
        tif->tif_flags |= TIFF_MYBUFFER;
1525
0
    }
1526
0
    if (tif->tif_rawdata == NULL)
1527
0
    {
1528
0
        TIFFErrorExtR(tif, module,
1529
0
                      "No space for data buffer at scanline %" PRIu32,
1530
0
                      tif->tif_dir.td_row);
1531
0
        tif->tif_rawdatasize = 0;
1532
0
        return (0);
1533
0
    }
1534
0
    return (1);
1535
0
}
1536
1537
/*
1538
 * Set state to appear as if a
1539
 * strip has just been read in.
1540
 */
1541
static int TIFFStartStrip(TIFF *tif, uint32_t strip)
1542
0
{
1543
0
    TIFFDirectory *td = &tif->tif_dir;
1544
1545
0
    if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
1546
0
    {
1547
0
        if (!(*tif->tif_setupdecode)(tif))
1548
0
            return (0);
1549
0
        tif->tif_flags |= TIFF_CODERSETUP;
1550
0
    }
1551
0
    if (td->td_stripsperimage == 0)
1552
0
    {
1553
0
        TIFFErrorExtR(tif, "TIFFStartStrip", "Zero strips per image");
1554
0
        return 0;
1555
0
    }
1556
0
    tif->tif_dir.td_curstrip = strip;
1557
0
    tif->tif_dir.td_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
1558
0
    tif->tif_flags &= ~TIFF_BUF4WRITE;
1559
1560
0
    if (tif->tif_flags & TIFF_NOREADRAW)
1561
0
    {
1562
0
        tif->tif_rawcp = NULL;
1563
0
        tif->tif_rawcc = 0;
1564
0
    }
1565
0
    else
1566
0
    {
1567
0
        tif->tif_rawcp = tif->tif_rawdata;
1568
0
        if (tif->tif_rawdataloaded > 0)
1569
0
            tif->tif_rawcc = tif->tif_rawdataloaded;
1570
0
        else
1571
0
            tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, strip);
1572
0
    }
1573
0
    if ((*tif->tif_predecode)(tif, (uint16_t)(strip / td->td_stripsperimage)) ==
1574
0
        0)
1575
0
    {
1576
        /* Needed for example for scanline access, if tif_predecode */
1577
        /* fails, and we try to read the same strip again. Without invalidating
1578
         */
1579
        /* tif_curstrip, we'd call tif_decoderow() on a possibly invalid */
1580
        /* codec state. */
1581
0
        tif->tif_dir.td_curstrip = NOSTRIP;
1582
0
        return 0;
1583
0
    }
1584
0
    return 1;
1585
0
}
1586
1587
/*
1588
 * Set state to appear as if a
1589
 * tile has just been read in.
1590
 */
1591
static int TIFFStartTile(TIFF *tif, uint32_t tile)
1592
0
{
1593
0
    static const char module[] = "TIFFStartTile";
1594
0
    TIFFDirectory *td = &tif->tif_dir;
1595
0
    uint32_t howmany32;
1596
1597
0
    if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
1598
0
    {
1599
0
        if (!(*tif->tif_setupdecode)(tif))
1600
0
            return (0);
1601
0
        tif->tif_flags |= TIFF_CODERSETUP;
1602
0
    }
1603
0
    tif->tif_dir.td_curtile = tile;
1604
0
    if (td->td_tilewidth == 0)
1605
0
    {
1606
0
        TIFFErrorExtR(tif, module, "Zero tilewidth");
1607
0
        return 0;
1608
0
    }
1609
0
    howmany32 = TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
1610
0
    if (howmany32 == 0)
1611
0
    {
1612
0
        TIFFErrorExtR(tif, module, "Zero tiles");
1613
0
        return 0;
1614
0
    }
1615
0
    tif->tif_dir.td_row = (tile % howmany32) * td->td_tilelength;
1616
0
    howmany32 = TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
1617
0
    if (howmany32 == 0)
1618
0
    {
1619
0
        TIFFErrorExtR(tif, module, "Zero tiles");
1620
0
        return 0;
1621
0
    }
1622
0
    tif->tif_dir.td_col = (tile % howmany32) * td->td_tilewidth;
1623
0
    tif->tif_flags &= ~TIFF_BUF4WRITE;
1624
0
    if (tif->tif_flags & TIFF_NOREADRAW)
1625
0
    {
1626
0
        tif->tif_rawcp = NULL;
1627
0
        tif->tif_rawcc = 0;
1628
0
    }
1629
0
    else
1630
0
    {
1631
0
        tif->tif_rawcp = tif->tif_rawdata;
1632
0
        if (tif->tif_rawdataloaded > 0)
1633
0
            tif->tif_rawcc = tif->tif_rawdataloaded;
1634
0
        else
1635
0
            tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, tile);
1636
0
    }
1637
0
    return (
1638
0
        (*tif->tif_predecode)(tif, (uint16_t)(tile / td->td_stripsperimage)));
1639
0
}
1640
1641
static int TIFFCheckRead(TIFF *tif, int tiles)
1642
0
{
1643
0
    if (tif->tif_mode == O_WRONLY)
1644
0
    {
1645
0
        TIFFErrorExtR(tif, tif->tif_name, "File not open for reading");
1646
0
        return (0);
1647
0
    }
1648
0
    if (tiles ^ isTiled(tif))
1649
0
    {
1650
0
        TIFFErrorExtR(tif, tif->tif_name,
1651
0
                      tiles ? "Can not read tiles from a striped image"
1652
0
                            : "Can not read scanlines from a tiled image");
1653
0
        return (0);
1654
0
    }
1655
0
    return (1);
1656
0
}
1657
1658
/* Use the provided input buffer (inbuf, insize) and decompress it into
1659
 * (outbuf, outsize).
1660
 * This function replaces the use of
1661
 * TIFFReadEncodedStrip()/TIFFReadEncodedTile() when the user can provide the
1662
 * buffer for the input data, for example when he wants to avoid libtiff to read
1663
 * the strile offset/count values from the [Strip|Tile][Offsets/ByteCounts]
1664
 * array. inbuf content must be writable (if bit reversal is needed) Returns 1
1665
 * in case of success, 0 otherwise.
1666
 */
1667
int TIFFReadFromUserBuffer(TIFF *tif, uint32_t strile, void *inbuf,
1668
                           tmsize_t insize, void *outbuf, tmsize_t outsize)
1669
0
{
1670
0
    static const char module[] = "TIFFReadFromUserBuffer";
1671
0
    TIFFDirectory *td = &tif->tif_dir;
1672
0
    int ret = 1;
1673
0
    uint32_t old_tif_flags = tif->tif_flags;
1674
0
    tmsize_t old_rawdatasize = tif->tif_rawdatasize;
1675
0
    void *old_rawdata = tif->tif_rawdata;
1676
1677
0
    if (tif->tif_mode == O_WRONLY)
1678
0
    {
1679
0
        TIFFErrorExtR(tif, tif->tif_name, "File not open for reading");
1680
0
        return 0;
1681
0
    }
1682
0
    if (tif->tif_flags & TIFF_NOREADRAW)
1683
0
    {
1684
0
        TIFFErrorExtR(tif, module,
1685
0
                      "Compression scheme does not support access to raw "
1686
0
                      "uncompressed data");
1687
0
        return 0;
1688
0
    }
1689
1690
0
    tif->tif_flags &= ~TIFF_MYBUFFER;
1691
0
    tif->tif_flags |= TIFF_BUFFERMMAP;
1692
0
    tif->tif_rawdatasize = insize;
1693
0
    tif->tif_rawdata = (uint8_t *)inbuf;
1694
0
    tif->tif_rawdataoff = 0;
1695
0
    tif->tif_rawdataloaded = insize;
1696
1697
0
    if (!isFillOrder(tif, td->td_fillorder) &&
1698
0
        (tif->tif_flags & TIFF_NOBITREV) == 0)
1699
0
    {
1700
0
        TIFFReverseBits((uint8_t *)inbuf, insize);
1701
0
    }
1702
1703
0
    if (TIFFIsTiled(tif))
1704
0
    {
1705
0
        if (!TIFFStartTile(tif, strile))
1706
0
        {
1707
0
            ret = 0;
1708
            /* See related TIFFReadEncodedStrip comment. */
1709
0
            if (outbuf)
1710
0
                memset(outbuf, 0, (size_t)outsize);
1711
0
        }
1712
0
        else if (!(*tif->tif_decodetile)(
1713
0
                     tif, (uint8_t *)outbuf, outsize,
1714
0
                     (uint16_t)(strile / td->td_stripsperimage)))
1715
0
        {
1716
0
            ret = 0;
1717
0
        }
1718
0
    }
1719
0
    else
1720
0
    {
1721
0
        uint32_t rowsperstrip = td->td_rowsperstrip;
1722
0
        uint32_t stripsperplane;
1723
0
        if (rowsperstrip > td->td_imagelength)
1724
0
            rowsperstrip = td->td_imagelength;
1725
0
        if (rowsperstrip == 0)
1726
0
        {
1727
0
            TIFFErrorExtR(tif, module, "rowsperstrip is zero");
1728
0
            ret = 0;
1729
0
        }
1730
0
        else
1731
0
        {
1732
0
            stripsperplane =
1733
0
                TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
1734
0
            if (!TIFFStartStrip(tif, strile))
1735
0
            {
1736
0
                ret = 0;
1737
                /* See related TIFFReadEncodedStrip comment. */
1738
0
                if (outbuf)
1739
0
                    memset(outbuf, 0, (size_t)outsize);
1740
0
            }
1741
0
            else if (!(*tif->tif_decodestrip)(
1742
0
                         tif, (uint8_t *)outbuf, outsize,
1743
0
                         (uint16_t)(strile / stripsperplane)))
1744
0
            {
1745
0
                ret = 0;
1746
0
            }
1747
0
        }
1748
0
    }
1749
0
    if (ret)
1750
0
    {
1751
0
        (*tif->tif_postdecode)(tif, (uint8_t *)outbuf, outsize);
1752
0
    }
1753
1754
0
    if (!isFillOrder(tif, td->td_fillorder) &&
1755
0
        (tif->tif_flags & TIFF_NOBITREV) == 0)
1756
0
    {
1757
0
        TIFFReverseBits((uint8_t *)inbuf, insize);
1758
0
    }
1759
1760
0
    tif->tif_flags = (old_tif_flags & (TIFF_MYBUFFER | TIFF_BUFFERMMAP)) |
1761
0
                     (tif->tif_flags & ~(TIFF_MYBUFFER | TIFF_BUFFERMMAP));
1762
0
    tif->tif_rawdatasize = old_rawdatasize;
1763
0
    tif->tif_rawdata = (uint8_t *)old_rawdata;
1764
0
    tif->tif_rawdataoff = 0;
1765
0
    tif->tif_rawdataloaded = 0;
1766
1767
0
    return ret;
1768
0
}
1769
1770
void _TIFFNoPostDecode(TIFF *tif, uint8_t *buf, tmsize_t cc)
1771
0
{
1772
0
    (void)tif;
1773
0
    (void)buf;
1774
0
    (void)cc;
1775
0
}
1776
1777
void _TIFFSwab16BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
1778
0
{
1779
0
    (void)tif;
1780
0
    assert((cc & 1) == 0);
1781
0
    TIFFSwabArrayOfShort((uint16_t *)buf, cc / 2);
1782
0
}
1783
1784
void _TIFFSwab24BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
1785
0
{
1786
0
    (void)tif;
1787
0
    assert((cc % 3) == 0);
1788
0
    TIFFSwabArrayOfTriples((uint8_t *)buf, cc / 3);
1789
0
}
1790
1791
void _TIFFSwab32BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
1792
0
{
1793
0
    (void)tif;
1794
0
    assert((cc & 3) == 0);
1795
0
    TIFFSwabArrayOfLong((uint32_t *)buf, cc / 4);
1796
0
}
1797
1798
void _TIFFSwab64BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
1799
0
{
1800
0
    (void)tif;
1801
0
    assert((cc & 7) == 0);
1802
0
    TIFFSwabArrayOfDouble((double *)buf, cc / 8);
1803
0
}