LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_read.c
Go to the documentation of this file.
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 */
34#include "tiffiop.h"
35#include <limits.h>
36#include <stdio.h>
37
38int TIFFFillStrip(TIFF *tif, uint32_t strip);
39int TIFFFillTile(TIFF *tif, uint32_t tile);
40static int TIFFStartStrip(TIFF *tif, uint32_t strip);
41static int TIFFStartTile(TIFF *tif, uint32_t tile);
42static int TIFFCheckRead(TIFF *, int);
43static tmsize_t TIFFReadRawStrip1(TIFF *tif, uint32_t strip, void *buf,
44 tmsize_t size, const char *module);
45static tmsize_t TIFFReadRawTile1(TIFF *tif, uint32_t tile, void *buf,
46 tmsize_t size, const char *module);
47
56#define INITIAL_THRESHOLD (1024 * 1024)
64#define THRESHOLD_MULTIPLIER 10
72#define MAX_THRESHOLD \
73 (THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER * \
74 INITIAL_THRESHOLD)
75
83#define TIFF_INT64_MAX ((((int64_t)0x7FFFFFFF) << 32) | 0xFFFFFFFF)
114/* Read 'size' bytes in tif_rawdata buffer starting at offset 'rawdata_offset'
115 * Returns 1 in case of success, 0 otherwise. */
116static int TIFFReadAndRealloc(TIFF *tif, tmsize_t size, tmsize_t rawdata_offset,
117 int is_strip, uint32_t strip_or_tile,
118 const char *module)
119{
120#if SIZEOF_SIZE_T == 8
121 tmsize_t threshold = INITIAL_THRESHOLD;
122#endif
123 tmsize_t already_read = 0;
124
125#if SIZEOF_SIZE_T != 8
126 /* On 32 bit processes, if the request is large enough, check against */
127 /* file size */
128 if (size > 1000 * 1000 * 1000)
129 {
130 uint64_t filesize = TIFFGetFileSize(tif);
131 if ((uint64_t)size >= filesize)
132 {
133 TIFFErrorExtR(tif, module,
134 "Chunk size requested is larger than file size.");
135 return 0;
136 }
137 }
138#endif
139
140 /* On 64 bit processes, read first a maximum of 1 MB, then 10 MB, etc */
141 /* so as to avoid allocating too much memory in case the file is too */
142 /* short. We could ask for the file size, but this might be */
143 /* expensive with some I/O layers (think of reading a gzipped file) */
144 /* Restrict to 64 bit processes, so as to avoid reallocs() */
145 /* on 32 bit processes where virtual memory is scarce. */
146 while (already_read < size)
147 {
148 tmsize_t bytes_read;
149 tmsize_t to_read = size - already_read;
150#if SIZEOF_SIZE_T == 8
151 if (to_read >= threshold && threshold < MAX_THRESHOLD &&
152 already_read + to_read + rawdata_offset > tif->tif_rawdatasize)
153 {
154 to_read = threshold;
155 threshold *= THRESHOLD_MULTIPLIER;
156 }
157#endif
158 if (already_read + to_read + rawdata_offset > tif->tif_rawdatasize)
159 {
160 uint8_t *new_rawdata;
161 tmsize_t new_rawdatasize;
162 assert((tif->tif_flags & TIFF_MYBUFFER) != 0);
163 new_rawdatasize = (tmsize_t)TIFFroundup_64(
164 (uint64_t)already_read + (uint64_t)to_read +
165 (uint64_t)rawdata_offset,
166 1024);
167 if (new_rawdatasize == 0)
168 {
169 TIFFErrorExtR(tif, module, "Invalid buffer size");
170 return 0;
171 }
172 new_rawdata = (uint8_t *)_TIFFreallocExt(tif, tif->tif_rawdata,
173 new_rawdatasize);
174 if (new_rawdata == 0)
175 {
176 TIFFErrorExtR(tif, module,
177 "No space for data buffer at scanline %" PRIu32,
178 tif->tif_dir.td_row);
179 _TIFFfreeExt(tif, tif->tif_rawdata);
180 tif->tif_rawdata = 0;
181 tif->tif_rawdatasize = 0;
182 return 0;
183 }
184 tif->tif_rawdatasize = new_rawdatasize;
185 tif->tif_rawdata = new_rawdata;
186 }
187 if (tif->tif_rawdata == NULL)
188 {
189 /* should not happen in practice but helps CoverityScan */
190 return 0;
191 }
192
193 bytes_read = TIFFReadFile(
194 tif, tif->tif_rawdata + rawdata_offset + already_read, to_read);
195 if (bytes_read < 0)
196 /* Treat read errors as short reads before updating offsets. */
197 bytes_read = 0;
198 already_read += bytes_read;
199 if (bytes_read != to_read)
200 {
201 memset(
202 tif->tif_rawdata + rawdata_offset + already_read, 0,
203 (size_t)(tif->tif_rawdatasize - rawdata_offset - already_read));
204 if (is_strip)
205 {
206 TIFFErrorExtR(tif, module,
207 "Read error at scanline %" PRIu32
208 "; got %" TIFF_SSIZE_FORMAT " bytes, "
209 "expected %" TIFF_SSIZE_FORMAT,
210 tif->tif_dir.td_row, already_read, size);
211 }
212 else
213 {
214 TIFFErrorExtR(tif, module,
215 "Read error at row %" PRIu32 ", col %" PRIu32
216 ", tile %" PRIu32 "; "
217 "got %" TIFF_SSIZE_FORMAT
218 " bytes, expected %" TIFF_SSIZE_FORMAT "",
219 tif->tif_dir.td_row, tif->tif_dir.td_col,
220 strip_or_tile, already_read, size);
221 }
222 return 0;
223 }
224 }
225 return 1;
226}
254static int TIFFFillStripPartial(TIFF *tif, int strip, tmsize_t read_ahead,
255 int restart)
256{
257 static const char module[] = "TIFFFillStripPartial";
258 TIFFDirectory *td = &tif->tif_dir;
259 tmsize_t unused_data;
260 uint64_t read_offset;
261 tmsize_t to_read;
262 tmsize_t read_ahead_mod;
263 /* tmsize_t bytecountm; */
264
265 /*
266 * Expand raw data buffer, if needed, to hold data
267 * strip coming from file (perhaps should set upper
268 * bound on the size of a buffer we'll use?).
269 */
270
271 /* bytecountm=(tmsize_t) TIFFGetStrileByteCount(tif, strip); */
272
273 /* Not completely sure where the * 2 comes from, but probably for */
274 /* an exponentional growth strategy of tif_rawdatasize */
275 if (read_ahead < TIFF_TMSIZE_T_MAX / 2)
276 read_ahead_mod = read_ahead * 2;
277 else
278 read_ahead_mod = read_ahead;
279 if (read_ahead_mod > tif->tif_rawdatasize)
280 {
281 assert(restart);
282
284 if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
285 {
286 TIFFErrorExtR(tif, module,
287 "Data buffer too small to hold part of strip %d",
288 strip);
289 return (0);
290 }
291 }
292
293 if (restart)
294 {
295 tif->tif_rawdataloaded = 0;
296 tif->tif_rawdataoff = 0;
297 }
298
299 /*
300 ** If we are reading more data, move any unused data to the
301 ** start of the buffer.
302 */
303 if (tif->tif_rawdataloaded > 0)
304 unused_data =
305 tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata);
306 else
307 unused_data = 0;
308
309 if (unused_data > 0)
310 {
311 assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
312 memmove(tif->tif_rawdata, tif->tif_rawcp, (size_t)unused_data);
313 }
314
315 /*
316 ** Seek to the point in the file where more data should be read.
317 */
318 read_offset = TIFFGetStrileOffset(tif, (uint32_t)strip);
319 if (read_offset > UINT64_MAX - (uint64_t)tif->tif_rawdataoff ||
320 read_offset + (uint64_t)tif->tif_rawdataoff >
321 UINT64_MAX - (uint64_t)tif->tif_rawdataloaded)
322 {
323 TIFFErrorExtR(tif, module,
324 "Seek error at scanline %" PRIu32 ", strip %d",
325 tif->tif_dir.td_row, strip);
326 return 0;
327 }
328 read_offset +=
329 (uint64_t)tif->tif_rawdataoff + (uint64_t)tif->tif_rawdataloaded;
330
331 if (!SeekOK(tif, read_offset))
332 {
333 TIFFErrorExtR(tif, module,
334 "Seek error at scanline %" PRIu32 ", strip %d",
335 tif->tif_dir.td_row, strip);
336 return 0;
337 }
338
339 /*
340 ** How much do we want to read?
341 */
342 if (read_ahead_mod > tif->tif_rawdatasize)
343 to_read = read_ahead_mod - unused_data;
344 else
345 to_read = tif->tif_rawdatasize - unused_data;
346 if ((uint64_t)to_read > TIFFGetStrileByteCount(tif, (uint32_t)strip) -
347 (uint64_t)tif->tif_rawdataoff -
348 (uint64_t)tif->tif_rawdataloaded)
349 {
350 to_read = (tmsize_t)(TIFFGetStrileByteCount(tif, (uint32_t)strip) -
351 (uint64_t)tif->tif_rawdataoff -
352 (uint64_t)tif->tif_rawdataloaded);
353 }
354
355 assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
356 if (!TIFFReadAndRealloc(tif, to_read, unused_data, 1, /* is_strip */
357 0, /* strip_or_tile */
358 module))
359 {
360 return 0;
361 }
362
363 tif->tif_rawdataoff =
364 tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data;
365 tif->tif_rawdataloaded = unused_data + to_read;
366
367 tif->tif_rawcc = tif->tif_rawdataloaded;
368 tif->tif_rawcp = tif->tif_rawdata;
369
370 if (!isFillOrder(tif, td->td_fillorder) &&
371 (tif->tif_flags & TIFF_NOBITREV) == 0)
372 {
373 assert((tif->tif_flags & TIFF_BUFFERMMAP) == 0);
374 TIFFReverseBits(tif->tif_rawdata + unused_data, to_read);
375 }
376
377 /*
378 ** When starting a strip from the beginning we need to
379 ** restart the decoder.
380 */
381 if (restart)
382 {
383
384#ifdef JPEG_SUPPORT
385 /* A bit messy since breaks the codec abstraction. Ultimately */
386 /* there should be a function pointer for that, but it seems */
387 /* only JPEG is affected. */
388 /* For JPEG, if there are multiple scans (can generally be known */
389 /* with the read_ahead used), we need to read the whole strip */
391 (uint64_t)tif->tif_rawcc <
392 TIFFGetStrileByteCount(tif, (uint32_t)strip))
393 {
395 {
396 return TIFFFillStrip(tif, (uint32_t)strip);
397 }
398 }
399#endif
400
401 return TIFFStartStrip(tif, (uint32_t)strip);
402 }
403 else
404 {
405 return 1;
406 }
407}
431/*
432 * Seek to a random row+sample in a file.
433 *
434 * Only used by TIFFReadScanline, and is only used on
435 * strip organized files. We do some tricky stuff to try
436 * and avoid reading the whole compressed raw data for big
437 * strips.
438 */
439static int TIFFSeek(TIFF *tif, uint32_t row, uint16_t sample)
440{
441 TIFFDirectory *td = &tif->tif_dir;
442 uint32_t strip;
443 int whole_strip;
444 tmsize_t read_ahead = 0;
445
446 /*
447 ** Establish what strip we are working from.
448 */
449 if (row >= td->td_imagelength)
450 { /* out of range */
451 TIFFErrorExtR(tif, tif->tif_name,
452 "%" PRIu32 ": Row out of range, max %" PRIu32 "", row,
453 td->td_imagelength);
454 return (0);
455 }
456 if (td->td_rowsperstrip == 0)
457 {
458 TIFFErrorExtR(tif, tif->tif_name,
459 "Cannot compute strip: RowsPerStrip is zero");
460 return (0);
461 }
463 {
464 uint64_t sample_offset;
465 uint64_t strip64;
466 if (sample >= td->td_samplesperpixel)
467 {
468 TIFFErrorExtR(tif, tif->tif_name,
469 "%" PRIu16 ": Sample out of range, max %" PRIu16 "",
470 sample, td->td_samplesperpixel);
471 return (0);
472 }
473 sample_offset =
474 _TIFFMultiply64(tif, sample, td->td_stripsperimage, "TIFFSeek");
475 if (sample_offset == 0 && sample != 0 && td->td_stripsperimage != 0)
476 return (0);
477 strip64 = _TIFFAdd64(tif, sample_offset, row / td->td_rowsperstrip,
478 "TIFFSeek");
479 if (strip64 == 0 &&
480 (sample_offset != 0 || (row / td->td_rowsperstrip) != 0))
481 return (0);
482 strip = _TIFFCastUInt64ToUInt32(tif, strip64, "TIFFSeek");
483 if (strip == 0 && strip64 != 0)
484 return (0);
485 }
486 else
487 strip = row / td->td_rowsperstrip;
488
489 /*
490 * Do we want to treat this strip as one whole chunk or
491 * read it a few lines at a time?
492 */
493#if defined(CHUNKY_STRIP_READ_SUPPORT)
494 whole_strip = TIFFGetStrileByteCount(tif, strip) < 10 || isMapped(tif);
495 if (td->td_compression == COMPRESSION_LERC ||
497 {
498 /* Ideally plugins should have a way to declare they don't support
499 * chunk strip */
500 whole_strip = 1;
501 }
502
503 if (!whole_strip)
504 {
505 /* 16 is for YCbCr mode where we may need to read 16 */
506 /* lines at a time to get a decompressed line, and 5000 */
507 /* is some constant value, for example for JPEG tables */
508
509 /* coverity[dead_error_line:SUPPRESS] */
510 if (tif->tif_dir.td_scanlinesize < TIFF_TMSIZE_T_MAX / 16 &&
511 tif->tif_dir.td_scanlinesize * 16 < TIFF_TMSIZE_T_MAX - 5000)
512 {
513 read_ahead = tif->tif_dir.td_scanlinesize * 16 + 5000;
514 }
515 else
516 {
517 read_ahead = tif->tif_dir.td_scanlinesize;
518 }
519 }
520#else
521 whole_strip = 1;
522#endif
523
524 /*
525 * If we haven't loaded this strip, do so now, possibly
526 * only reading the first part.
527 */
528 if (strip != tif->tif_dir.td_curstrip)
529 { /* different strip, refill */
530
531 if (whole_strip)
532 {
533 if (!TIFFFillStrip(tif, strip))
534 return (0);
535 }
536#if defined(CHUNKY_STRIP_READ_SUPPORT)
537 else
538 {
539 if (!TIFFFillStripPartial(tif, strip, read_ahead, 1))
540 return 0;
541 }
542#endif
543 }
544
545#if defined(CHUNKY_STRIP_READ_SUPPORT)
546 /*
547 ** If we already have some data loaded, do we need to read some more?
548 */
549 else if (!whole_strip)
550 {
551 /* coverity[dead_error_line:SUPPRESS] */
552 if (((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) <
553 read_ahead &&
554 (uint64_t)tif->tif_rawdataoff + tif->tif_rawdataloaded <
555 TIFFGetStrileByteCount(tif, strip))
556 {
557 if (!TIFFFillStripPartial(tif, strip, read_ahead, 0))
558 return 0;
559 }
560 }
561#endif
562
563 if (row < tif->tif_dir.td_row)
564 {
565 /*
566 * Moving backwards within the same strip: backup
567 * to the start and then decode forward (below).
568 *
569 * NB: If you're planning on lots of random access within a
570 * strip, it's better to just read and decode the entire
571 * strip, and then access the decoded data in a random fashion.
572 */
573
574 if (tif->tif_rawdataoff != 0)
575 {
576 if (!TIFFFillStripPartial(tif, (int)strip, read_ahead, 1))
577 return 0;
578 }
579 else
580 {
581 if (!TIFFStartStrip(tif, strip))
582 return (0);
583 }
584 }
585
586 if (row != tif->tif_dir.td_row)
587 {
588 /*
589 * Seek forward to the desired row.
590 */
591
592 /* TODO: Will this really work with partial buffers? */
593
594 if (!(*tif->tif_seek)(tif, row - tif->tif_dir.td_row))
595 return (0);
596 tif->tif_dir.td_row = row;
597 }
598
599 return (1);
600}
601
602int TIFFReadScanline(TIFF *tif, void *buf, uint32_t row, uint16_t sample)
603{
604 int e;
605
606 if (!TIFFCheckRead(tif, 0))
607 return (-1);
608 if ((e = TIFFSeek(tif, row, sample)) != 0)
609 {
610 /*
611 * Decompress desired row into user buffer.
612 */
613 e = (*tif->tif_decoderow)(tif, (uint8_t *)buf,
614 tif->tif_dir.td_scanlinesize, sample);
615
616 /* we are now poised at the beginning of the next row */
617 tif->tif_dir.td_row = row + 1;
618
619 if (e > 0)
620 {
623 "TIFFReadScanline");
624 if (e)
625 (*tif->tif_postdecode)(tif, (uint8_t *)buf,
627 }
628 }
629 else
630 {
631 /* See TIFFReadEncodedStrip comment regarding TIFFTAG_FAXFILLFUNC. */
632 if (buf)
633 memset(buf, 0, (size_t)tif->tif_dir.td_scanlinesize);
634 }
635 return (e > 0 ? 1 : -1);
636}
657/*
658 * Calculate the strip size according to the number of
659 * rows in the strip (check for truncated last strip on any
660 * of the separations).
661 */
663 uint16_t *pplane)
664{
665 static const char module[] = "TIFFReadEncodedStrip";
666 TIFFDirectory *td = &tif->tif_dir;
667 uint32_t rowsperstrip;
668 uint32_t stripsperplane;
669 uint32_t stripinplane;
670 uint32_t rows;
671 tmsize_t stripsize;
672 if (!TIFFCheckRead(tif, 0))
673 return ((tmsize_t)(-1));
674 if (strip >= td->td_nstrips)
675 {
676 TIFFErrorExtR(tif, module,
677 "%" PRIu32 ": Strip out of range, max %" PRIu32, strip,
678 td->td_nstrips);
679 return ((tmsize_t)(-1));
680 }
681
682 rowsperstrip = td->td_rowsperstrip;
683 if (rowsperstrip > td->td_imagelength)
684 rowsperstrip = td->td_imagelength;
685 if (rowsperstrip == 0)
686 {
687 TIFFErrorExtR(tif, module, "rowsperstrip is zero");
688 return ((tmsize_t)(-1));
689 }
690 stripsperplane =
691 TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
692 stripinplane = (strip % stripsperplane);
693 if (pplane)
694 *pplane = (uint16_t)(strip / stripsperplane);
695 rows = td->td_imagelength - stripinplane * rowsperstrip;
696 if (rows > rowsperstrip)
697 rows = rowsperstrip;
698 stripsize = TIFFVStripSize(tif, rows);
699 if (stripsize == 0)
700 return ((tmsize_t)(-1));
701 return stripsize;
702}
703
704/*
705 * Read a strip of data and decompress the specified
706 * amount into the user-supplied buffer.
707 */
708tmsize_t TIFFReadEncodedStrip(TIFF *tif, uint32_t strip, void *buf,
709 tmsize_t size)
710{
711 static const char module[] = "TIFFReadEncodedStrip";
712 TIFFDirectory *td = &tif->tif_dir;
713 tmsize_t stripsize;
714 uint16_t plane;
715
716 if ((size < 0) && (size != (tmsize_t)(-1)))
717 {
718 TIFFErrorExtR(tif, module, "Invalid size %" TIFF_SSIZE_FORMAT, size);
719 return ((tmsize_t)(-1));
720 }
721 stripsize = TIFFReadEncodedStripGetStripSize(tif, strip, &plane);
722 if (stripsize == ((tmsize_t)(-1)))
723 return ((tmsize_t)(-1));
724
725 /* shortcut to avoid an extra memcpy() */
726 if (td->td_compression == COMPRESSION_NONE && size != (tmsize_t)(-1) &&
727 size >= stripsize && !isMapped(tif) &&
728 ((tif->tif_flags & TIFF_NOREADRAW) == 0))
729 {
730 if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize)
731 return ((tmsize_t)(-1));
732
733 if (!isFillOrder(tif, td->td_fillorder) &&
734 (tif->tif_flags & TIFF_NOBITREV) == 0)
735 TIFFReverseBits((uint8_t *)buf, stripsize);
736
737 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, stripsize,
738 module))
739 return ((tmsize_t)(-1));
740 (*tif->tif_postdecode)(tif, (uint8_t *)buf, stripsize);
741 return (stripsize);
742 }
743
744 if ((size != (tmsize_t)(-1)) && (size < stripsize))
745 stripsize = size;
746 if (!TIFFFillStrip(tif, strip))
747 {
748 /* The output buf may be NULL, in particular if TIFFTAG_FAXFILLFUNC
749 is being used. Thus, memset must be conditional on buf not NULL. */
750 if (buf)
751 memset(buf, 0, (size_t)stripsize);
752 return ((tmsize_t)(-1));
753 }
754 if ((*tif->tif_decodestrip)(tif, (uint8_t *)buf, stripsize, plane) <= 0)
755 return ((tmsize_t)(-1));
756 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, stripsize,
757 module))
758 return ((tmsize_t)(-1));
759 (*tif->tif_postdecode)(tif, (uint8_t *)buf, stripsize);
760 return (stripsize);
761}
762
763/* Variant of TIFFReadEncodedStrip() that does
764 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
765 * TIFFFillStrip() has succeeded. This avoid excessive memory allocation in case
766 * of truncated file.
767 * * calls regular TIFFReadEncodedStrip() if *buf != NULL
768 */
770 void **buf,
771 tmsize_t bufsizetoalloc,
772 tmsize_t size_to_read)
773{
774 tmsize_t this_stripsize;
775 uint16_t plane;
776
777 if (*buf != NULL)
778 {
779 return TIFFReadEncodedStrip(tif, strip, *buf, size_to_read);
780 }
781
782 this_stripsize = TIFFReadEncodedStripGetStripSize(tif, strip, &plane);
783 if (this_stripsize == ((tmsize_t)(-1)))
784 return ((tmsize_t)(-1));
785
786 if ((size_to_read != (tmsize_t)(-1)) && (size_to_read < this_stripsize))
787 this_stripsize = size_to_read;
788 if (!TIFFFillStrip(tif, strip))
789 return ((tmsize_t)(-1));
790
791 /* Sanity checks to avoid excessive memory allocation */
792 /* Max compression ratio experimentally determined. Might be fragile...
793 * Only apply this heuristics to situations where the memory allocation
794 * would be big, to avoid breaking nominal use cases.
795 */
796 if (bufsizetoalloc > 100 * 1024 * 1024)
797 {
798 const uint64_t maxCompressionRatio = TIFFGetMaxCompressionRatio(tif);
799 if (maxCompressionRatio > 0 &&
800 (uint64_t)tif->tif_rawdatasize <
801 (uint64_t)this_stripsize / maxCompressionRatio)
802 {
803 TIFFErrorExtR(tif, TIFFFileName(tif),
804 "Likely invalid strip byte count for strip %u. "
805 "Uncompressed strip size is %" PRIu64 ", "
806 "compressed one is %" PRIu64,
807 strip, (uint64_t)this_stripsize,
808 (uint64_t)tif->tif_rawdatasize);
809 return ((tmsize_t)(-1));
810 }
811 }
812
813 *buf = _TIFFcallocExt(tif, 1, bufsizetoalloc);
814 if (*buf == NULL)
815 {
816 TIFFErrorExtR(tif, TIFFFileName(tif), "No space for strip buffer");
817 return ((tmsize_t)(-1));
818 }
819
820 if ((*tif->tif_decodestrip)(tif, (uint8_t *)*buf, this_stripsize, plane) <=
821 0)
822 return ((tmsize_t)(-1));
823 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, this_stripsize,
824 "_TIFFReadEncodedStripAndAllocBuffer"))
825 return ((tmsize_t)(-1));
826 (*tif->tif_postdecode)(tif, (uint8_t *)*buf, this_stripsize);
827 return (this_stripsize);
828}
853static tmsize_t TIFFReadRawStrip1(TIFF *tif, uint32_t strip, void *buf,
854 tmsize_t size, const char *module)
855{
856 assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
857 if (!isMapped(tif))
858 {
859 tmsize_t cc;
860
861 if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip)))
862 {
863 TIFFErrorExtR(tif, module,
864 "Seek error at scanline %" PRIu32 ", strip %" PRIu32,
865 tif->tif_dir.td_row, strip);
866 return ((tmsize_t)(-1));
867 }
868 cc = TIFFReadFile(tif, buf, size);
869 if (cc != size)
870 {
871 TIFFErrorExtR(tif, module,
872 "Read error at scanline %" PRIu32
873 "; got %" TIFF_SSIZE_FORMAT
874 " bytes, expected %" TIFF_SSIZE_FORMAT,
875 tif->tif_dir.td_row, cc, size);
876 return ((tmsize_t)(-1));
877 }
878 }
879 else
880 {
881 tmsize_t ma = 0;
882 tmsize_t n;
883 if ((TIFFGetStrileOffset(tif, strip) > (uint64_t)TIFF_TMSIZE_T_MAX) ||
884 ((ma = (tmsize_t)TIFFGetStrileOffset(tif, strip)) > tif->tif_size))
885 {
886 n = 0;
887 }
888 else if (ma > TIFF_TMSIZE_T_MAX - size)
889 {
890 n = 0;
891 }
892 else
893 {
894 tmsize_t mb = ma + size;
895 if (mb > tif->tif_size)
896 n = tif->tif_size - ma;
897 else
898 n = size;
899 }
900 if (n != size)
901 {
902 TIFFErrorExtR(tif, module,
903 "Read error at scanline %" PRIu32 ", strip %" PRIu32
904 "; got %" TIFF_SSIZE_FORMAT
905 " bytes, expected %" TIFF_SSIZE_FORMAT,
906 tif->tif_dir.td_row, strip, n, size);
907 return ((tmsize_t)(-1));
908 }
909 _TIFFmemcpy(buf, tif->tif_base + ma, size);
910 }
911 return (size);
912}
938static tmsize_t TIFFReadRawStripOrTile2(TIFF *tif, uint32_t strip_or_tile,
939 int is_strip, tmsize_t size,
940 const char *module)
941{
942 assert(!isMapped(tif));
943 assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
944
945 if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip_or_tile)))
946 {
947 if (is_strip)
948 {
949 TIFFErrorExtR(tif, module,
950 "Seek error at scanline %" PRIu32 ", strip %" PRIu32,
951 tif->tif_dir.td_row, strip_or_tile);
952 }
953 else
954 {
956 tif, module,
957 "Seek error at row %" PRIu32 ", col %" PRIu32 ", tile %" PRIu32,
958 tif->tif_dir.td_row, tif->tif_dir.td_col, strip_or_tile);
959 }
960 return ((tmsize_t)(-1));
961 }
962
963 if (!TIFFReadAndRealloc(tif, size, 0, is_strip, strip_or_tile, module))
964 {
965 return ((tmsize_t)(-1));
966 }
967
968 return (size);
969}
970
971/*
972 * Read a strip of data from the file.
973 */
974tmsize_t TIFFReadRawStrip(TIFF *tif, uint32_t strip, void *buf, tmsize_t size)
975{
976 static const char module[] = "TIFFReadRawStrip";
977 TIFFDirectory *td = &tif->tif_dir;
978 uint64_t bytecount64;
979 tmsize_t bytecountm;
980
981 if ((size < 0) && (size != (tmsize_t)(-1)))
982 {
983 TIFFErrorExtR(tif, module, "Invalid size %" TIFF_SSIZE_FORMAT, size);
984 return ((tmsize_t)(-1));
985 }
986 if (!TIFFCheckRead(tif, 0))
987 return ((tmsize_t)(-1));
988 if (strip >= td->td_nstrips)
989 {
990 TIFFErrorExtR(tif, module,
991 "%" PRIu32 ": Strip out of range, max %" PRIu32, strip,
992 td->td_nstrips);
993 return ((tmsize_t)(-1));
994 }
995 if (tif->tif_flags & TIFF_NOREADRAW)
996 {
997 TIFFErrorExtR(tif, module,
998 "Compression scheme does not support access to raw "
999 "uncompressed data");
1000 return ((tmsize_t)(-1));
1001 }
1002 bytecount64 = TIFFGetStrileByteCount(tif, strip);
1003 if (size != (tmsize_t)(-1) && (uint64_t)size <= bytecount64)
1004 bytecountm = size;
1005 else
1006 bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
1007 if (bytecountm == 0)
1008 {
1009 return ((tmsize_t)(-1));
1010 }
1011 return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module));
1012}
1027static uint64_t NoSanitizeSubUInt64(uint64_t a, uint64_t b) { return a - b; }
1051/*
1052 * Read the specified strip and setup for decoding. The data buffer is
1053 * expanded, as necessary, to hold the strip's data.
1054 */
1055int TIFFFillStrip(TIFF *tif, uint32_t strip)
1056{
1057 static const char module[] = "TIFFFillStrip";
1058 TIFFDirectory *td = &tif->tif_dir;
1059
1060 if ((tif->tif_flags & TIFF_NOREADRAW) == 0)
1061 {
1062 uint64_t bytecount = TIFFGetStrileByteCount(tif, strip);
1063 if (bytecount == 0 || bytecount > (uint64_t)TIFF_INT64_MAX)
1064 {
1065 TIFFErrorExtR(tif, module,
1066 "Invalid strip byte count %" PRIu64
1067 ", strip %" PRIu32,
1068 bytecount, strip);
1069 return (0);
1070 }
1071
1072 /* To avoid excessive memory allocations: */
1073 const tmsize_t stripsize = TIFFStripSize(tif);
1074 if (stripsize > 0)
1075 {
1076 if (bytecount > 1024 * 1024 &&
1077 (bytecount - 4096) / 10 > (uint64_t)stripsize)
1078 {
1079 /* Byte count should normally not be larger than a number of */
1080 /* times the uncompressed size plus some margin */
1081 /* 10 and 4096 are just values that could be adjusted. */
1082 /* Hopefully they are safe enough for all codecs */
1083 /* What happens next will depend on whether only the bytecount
1084 */
1085 /* was corrupted to a large value but the strip/tile data is */
1086 /* fine. In that situation most codecs should work fine and */
1087 /* only used part of the tile/strip data. If the strip/tile */
1088 /* data is corrupted too, then codecs will later error out. */
1089 uint64_t newbytecount = (uint64_t)stripsize * 10 + 4096;
1090 TIFFWarningExtR(tif, module,
1091 "Too large strip byte count %" PRIu64
1092 ", strip %" PRIu32 ". Limiting to %" PRIu64,
1093 bytecount, strip, newbytecount);
1094 bytecount = newbytecount;
1095 }
1096 else if (stripsize > 100 * 1024 * 1024)
1097 {
1098 /* Max compression ratio experimentally determined. Might be
1099 * fragile... Only apply this heuristics to situations where the
1100 * memory allocation would be big, to avoid breaking nominal use
1101 * cases.
1102 */
1103 const uint64_t maxCompressionRatio =
1105 if (maxCompressionRatio > 0 &&
1106 bytecount < (uint64_t)stripsize / maxCompressionRatio)
1107 {
1109 tif, module,
1110 "Likely invalid strip byte count for strip %u. "
1111 "Uncompressed strip size is %" PRIu64 ", "
1112 "compressed one is %" PRIu64,
1113 strip, (uint64_t)stripsize, bytecount);
1114 return 0;
1115 }
1116 }
1117 }
1118
1119 if (isMapped(tif))
1120 {
1121 /*
1122 * We must check for overflow, potentially causing
1123 * an OOB read. Instead of simple
1124 *
1125 * TIFFGetStrileOffset(tif, strip)+bytecount > tif->tif_size
1126 *
1127 * comparison (which can overflow) we do the following
1128 * two comparisons:
1129 */
1130 if (bytecount > (uint64_t)tif->tif_size ||
1131 TIFFGetStrileOffset(tif, strip) >
1132 (uint64_t)tif->tif_size - bytecount)
1133 {
1134 /*
1135 * This error message might seem strange, but
1136 * it's what would happen if a read were done
1137 * instead.
1138 */
1140 tif, module,
1141
1142 "Read error on strip %" PRIu32 "; "
1143 "got %" PRIu64 " bytes, expected %" PRIu64,
1144 strip,
1145 NoSanitizeSubUInt64((uint64_t)tif->tif_size,
1146 TIFFGetStrileOffset(tif, strip)),
1147 bytecount);
1149 return (0);
1150 }
1151 }
1152
1153 if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) ||
1154 (tif->tif_flags & TIFF_NOBITREV)))
1155 {
1156 /*
1157 * The image is mapped into memory and we either don't
1158 * need to flip bits or the compression routine is
1159 * going to handle this operation itself. In this
1160 * case, avoid copying the raw data and instead just
1161 * reference the data from the memory mapped file
1162 * image. This assumes that the decompression
1163 * routines do not modify the contents of the raw data
1164 * buffer (if they try to, the application will get a
1165 * fault since the file is mapped read-only).
1166 */
1167 if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
1168 {
1169 _TIFFfreeExt(tif, tif->tif_rawdata);
1170 tif->tif_rawdata = NULL;
1171 tif->tif_rawdatasize = 0;
1172 }
1173 tif->tif_flags &= ~TIFF_MYBUFFER;
1174 uint8_t *mapped_rawdata =
1175 tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, strip);
1176 tif->tif_rawdatasize = (tmsize_t)bytecount;
1177 tif->tif_rawdata = mapped_rawdata;
1178 tif->tif_rawdataoff = 0;
1179 tif->tif_rawdataloaded = (tmsize_t)bytecount;
1180
1181 /*
1182 * When we have tif_rawdata reference directly into the memory
1183 * mapped file we need to be pretty careful about how we use the
1184 * rawdata. It is not a general purpose working buffer as it
1185 * normally otherwise is. So we keep track of this fact to avoid
1186 * using it improperly.
1187 */
1188 tif->tif_flags |= TIFF_BUFFERMMAP;
1189 }
1190 else
1191 {
1192 /*
1193 * Expand raw data buffer, if needed, to hold data
1194 * strip coming from file (perhaps should set upper
1195 * bound on the size of a buffer we'll use?).
1196 */
1197 tmsize_t bytecountm;
1198 bytecountm = (tmsize_t)bytecount;
1199 if ((uint64_t)bytecountm != bytecount)
1200 {
1201 TIFFErrorExtR(tif, module, "Integer overflow");
1202 return (0);
1203 }
1204 if (bytecountm > tif->tif_rawdatasize)
1205 {
1207 if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
1208 {
1210 tif, module,
1211 "Data buffer too small to hold strip %" PRIu32, strip);
1212 return (0);
1213 }
1214 }
1215 if (tif->tif_flags & TIFF_BUFFERMMAP)
1216 {
1218 tif->tif_rawdata = NULL;
1219 tif->tif_rawdatasize = 0;
1220 tif->tif_flags &= ~TIFF_BUFFERMMAP;
1221 }
1222
1223 if (isMapped(tif))
1224 {
1225 if (bytecountm > tif->tif_rawdatasize &&
1226 !TIFFReadBufferSetup(tif, 0, bytecountm))
1227 {
1228 return (0);
1229 }
1230 if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm,
1231 module) != bytecountm)
1232 {
1233 return (0);
1234 }
1235 }
1236 else
1237 {
1238 if (TIFFReadRawStripOrTile2(tif, strip, 1, bytecountm,
1239 module) != bytecountm)
1240 {
1241 return (0);
1242 }
1243 }
1244
1245 tif->tif_rawdataoff = 0;
1246 tif->tif_rawdataloaded = bytecountm;
1247
1248 if (!isFillOrder(tif, td->td_fillorder) &&
1249 (tif->tif_flags & TIFF_NOBITREV) == 0)
1250 TIFFReverseBits(tif->tif_rawdata, bytecountm);
1251 }
1252 }
1253 return (TIFFStartStrip(tif, strip));
1254}
1255
1256/*
1257 * Tile-oriented Read Support
1258 * Contributed by Nancy Cam (Silicon Graphics).
1259 */
1260
1261/*
1262 * Read and decompress a tile of data. The
1263 * tile is selected by the (x,y,z,s) coordinates.
1264 */
1265tmsize_t TIFFReadTile(TIFF *tif, void *buf, uint32_t x, uint32_t y, uint32_t z,
1266 uint16_t s)
1267{
1268 bool overflow = false;
1269 uint32_t tile;
1270
1271 if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
1272 return ((tmsize_t)(-1));
1273 /* An overflow returns 0, which is also a valid tile. */
1274 tile = _TIFFComputeTileExt(tif, x, y, z, s, &overflow);
1275 if (overflow)
1276 return ((tmsize_t)(-1));
1277 return (TIFFReadEncodedTile(tif, tile, buf, (tmsize_t)(-1)));
1278}
1279
1280/*
1281 * Read a tile of data and decompress the specified
1282 * amount into the user-supplied buffer.
1283 */
1284tmsize_t TIFFReadEncodedTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
1285{
1286 static const char module[] = "TIFFReadEncodedTile";
1287 TIFFDirectory *td = &tif->tif_dir;
1288 tmsize_t tilesize = tif->tif_dir.td_tilesize;
1289
1290 if ((size < 0) && (size != (tmsize_t)(-1)))
1291 {
1292 TIFFErrorExtR(tif, module, "Invalid size %" TIFF_SSIZE_FORMAT, size);
1293 return ((tmsize_t)(-1));
1294 }
1295 if (!TIFFCheckRead(tif, 1))
1296 return ((tmsize_t)(-1));
1297 if (tile >= td->td_nstrips)
1298 {
1299 TIFFErrorExtR(tif, module,
1300 "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1301 td->td_nstrips);
1302 return ((tmsize_t)(-1));
1303 }
1304
1305 /* shortcut to avoid an extra memcpy() */
1306 if (td->td_compression == COMPRESSION_NONE && size != (tmsize_t)(-1) &&
1307 size >= tilesize && !isMapped(tif) &&
1308 ((tif->tif_flags & TIFF_NOREADRAW) == 0))
1309 {
1310 if (TIFFReadRawTile1(tif, tile, buf, tilesize, module) != tilesize)
1311 return ((tmsize_t)(-1));
1312
1313 if (!isFillOrder(tif, td->td_fillorder) &&
1314 (tif->tif_flags & TIFF_NOBITREV) == 0)
1315 TIFFReverseBits((uint8_t *)buf, tilesize);
1316
1317 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, tilesize,
1318 module))
1319 return ((tmsize_t)(-1));
1320 (*tif->tif_postdecode)(tif, (uint8_t *)buf, tilesize);
1321 return (tilesize);
1322 }
1323
1324 if (size == (tmsize_t)(-1))
1325 size = tilesize;
1326 else if (size > tilesize)
1327 size = tilesize;
1328 if (!TIFFFillTile(tif, tile))
1329 {
1330 /* See TIFFReadEncodedStrip comment regarding TIFFTAG_FAXFILLFUNC. */
1331 if (buf)
1332 memset(buf, 0, (size_t)size);
1333 return ((tmsize_t)(-1));
1334 }
1335 if ((*tif->tif_decodetile)(tif, (uint8_t *)buf, size,
1336 (uint16_t)(tile / td->td_stripsperimage)) <= 0)
1337 return ((tmsize_t)(-1));
1338 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, size, module))
1339 return ((tmsize_t)(-1));
1340 (*tif->tif_postdecode)(tif, (uint8_t *)buf, size);
1341 return (size);
1342}
1343
1344/* Variant of TIFFReadTile() that does
1345 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
1346 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
1347 * of truncated file.
1348 * * calls regular TIFFReadEncodedTile() if *buf != NULL
1349 */
1351 tmsize_t bufsizetoalloc, uint32_t x,
1352 uint32_t y, uint32_t z, uint16_t s)
1353{
1354 bool overflow = false;
1355 uint32_t tile;
1356
1357 if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
1358 return ((tmsize_t)(-1));
1359 /* An overflow returns 0, which is also a valid tile. */
1360 tile = _TIFFComputeTileExt(tif, x, y, z, s, &overflow);
1361 if (overflow)
1362 return ((tmsize_t)(-1));
1363 return (_TIFFReadEncodedTileAndAllocBuffer(tif, tile, buf, bufsizetoalloc,
1364 (tmsize_t)(-1)));
1365}
1366
1367/* Variant of TIFFReadEncodedTile() that does
1368 * * if *buf == NULL, *buf = _TIFFmallocExt(tif, bufsizetoalloc) only after
1369 * TIFFFillTile() has succeeded. This avoid excessive memory allocation in case
1370 * of truncated file.
1371 * * calls regular TIFFReadEncodedTile() if *buf != NULL
1372 */
1374 void **buf, tmsize_t bufsizetoalloc,
1375 tmsize_t size_to_read)
1376{
1377 static const char module[] = "_TIFFReadEncodedTileAndAllocBuffer";
1378 TIFFDirectory *td = &tif->tif_dir;
1379 tmsize_t tilesize = tif->tif_dir.td_tilesize;
1380
1381 if (*buf != NULL)
1382 {
1383 return TIFFReadEncodedTile(tif, tile, *buf, size_to_read);
1384 }
1385
1386 if (!TIFFCheckRead(tif, 1))
1387 return ((tmsize_t)(-1));
1388 if (tile >= td->td_nstrips)
1389 {
1390 TIFFErrorExtR(tif, module,
1391 "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1392 td->td_nstrips);
1393 return ((tmsize_t)(-1));
1394 }
1395
1396 if (!TIFFFillTile(tif, tile))
1397 return ((tmsize_t)(-1));
1398
1399 /* Sanity checks to avoid excessive memory allocation */
1400 /* Cf https://gitlab.com/libtiff/libtiff/-/issues/479 */
1401 if (td->td_compression == COMPRESSION_NONE)
1402 {
1403 const uint64_t bytecount = TIFFGetStrileByteCount(tif, tile);
1404 if (bytecount != (uint64_t)tilesize)
1405 {
1406 TIFFErrorExtR(tif, TIFFFileName(tif),
1407 "Invalid tile byte count for tile %u. "
1408 "Expected %" PRIu64 ", got %" PRIu64,
1409 tile, (uint64_t)tilesize, bytecount);
1410 return ((tmsize_t)(-1));
1411 }
1412 }
1413 else
1414 {
1415 /* Max compression ratio experimentally determined. Might be fragile...
1416 * Only apply this heuristics to situations where the memory allocation
1417 * would be big, to avoid breaking nominal use cases.
1418 */
1419 if (bufsizetoalloc > 100 * 1024 * 1024)
1420 {
1421 const uint64_t maxCompressionRatio =
1423 if (maxCompressionRatio > 0 &&
1424 (uint64_t)tif->tif_rawdatasize <
1425 (uint64_t)tilesize / maxCompressionRatio)
1426 {
1427 TIFFErrorExtR(tif, TIFFFileName(tif),
1428 "Likely invalid tile byte count for tile %u. "
1429 "Uncompressed tile size is %" PRIu64 ", "
1430 "compressed one is %" PRIu64,
1431 tile, (uint64_t)tilesize,
1432 (uint64_t)tif->tif_rawdatasize);
1433 return ((tmsize_t)(-1));
1434 }
1435 }
1436 }
1437
1438 *buf = _TIFFmallocExt(tif, bufsizetoalloc);
1439 if (*buf == NULL)
1440 {
1441 TIFFErrorExtR(tif, TIFFFileName(tif), "No space for tile buffer");
1442 return ((tmsize_t)(-1));
1443 }
1444 _TIFFmemset(*buf, 0, bufsizetoalloc);
1445
1446 if (size_to_read == (tmsize_t)(-1))
1447 size_to_read = tilesize;
1448 else if (size_to_read > tilesize)
1449 size_to_read = tilesize;
1450 if ((*tif->tif_decodetile)(tif, (uint8_t *)*buf, size_to_read,
1451 (uint16_t)(tile / td->td_stripsperimage)) <= 0)
1452 return ((tmsize_t)(-1));
1453 if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, size_to_read,
1454 module))
1455 return ((tmsize_t)(-1));
1456 (*tif->tif_postdecode)(tif, (uint8_t *)*buf, size_to_read);
1457 return (size_to_read);
1458}
1483static tmsize_t TIFFReadRawTile1(TIFF *tif, uint32_t tile, void *buf,
1484 tmsize_t size, const char *module)
1485{
1486 assert((tif->tif_flags & TIFF_NOREADRAW) == 0);
1487 if (!isMapped(tif))
1488 {
1489 tmsize_t cc;
1490
1491 if (!SeekOK(tif, TIFFGetStrileOffset(tif, tile)))
1492 {
1493 TIFFErrorExtR(tif, module,
1494 "Seek error at row %" PRIu32 ", col %" PRIu32
1495 ", tile %" PRIu32,
1496 tif->tif_dir.td_row, tif->tif_dir.td_col, tile);
1497 return ((tmsize_t)(-1));
1498 }
1499 cc = TIFFReadFile(tif, buf, size);
1500 if (cc != size)
1501 {
1502 TIFFErrorExtR(tif, module,
1503 "Read error at row %" PRIu32 ", col %" PRIu32
1504 "; got %" TIFF_SSIZE_FORMAT
1505 " bytes, expected %" TIFF_SSIZE_FORMAT,
1506 tif->tif_dir.td_row, tif->tif_dir.td_col, cc, size);
1507 return ((tmsize_t)(-1));
1508 }
1509 }
1510 else
1511 {
1512 tmsize_t ma = 0; /* assigned in if-condition below */
1513 tmsize_t n;
1514 if ((TIFFGetStrileOffset(tif, tile) > (uint64_t)TIFF_TMSIZE_T_MAX) ||
1515 ((ma = (tmsize_t)TIFFGetStrileOffset(tif, tile)) > tif->tif_size))
1516 {
1517 n = 0;
1518 }
1519 else if (ma > TIFF_TMSIZE_T_MAX - size)
1520 {
1521 n = 0;
1522 }
1523 else
1524 {
1525 tmsize_t mb = ma + size;
1526 if (mb > tif->tif_size)
1527 n = tif->tif_size - ma;
1528 else
1529 n = size;
1530 }
1531 if (n != size)
1532 {
1533 TIFFErrorExtR(tif, module,
1534 "Read error at row %" PRIu32 ", col %" PRIu32
1535 ", tile %" PRIu32 "; got %" TIFF_SSIZE_FORMAT
1536 " bytes, expected %" TIFF_SSIZE_FORMAT,
1537 tif->tif_dir.td_row, tif->tif_dir.td_col, tile, n,
1538 size);
1539 return ((tmsize_t)(-1));
1540 }
1541 _TIFFmemcpy(buf, tif->tif_base + ma, size);
1542 }
1543 return (size);
1544}
1545
1546/*
1547 * Read a tile of data from the file.
1548 */
1549tmsize_t TIFFReadRawTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
1550{
1551 static const char module[] = "TIFFReadRawTile";
1552 TIFFDirectory *td = &tif->tif_dir;
1553 uint64_t bytecount64;
1554 tmsize_t bytecountm;
1555
1556 if ((size < 0) && (size != (tmsize_t)(-1)))
1557 {
1558 TIFFErrorExtR(tif, module, "Invalid size %" TIFF_SSIZE_FORMAT, size);
1559 return ((tmsize_t)(-1));
1560 }
1561 if (!TIFFCheckRead(tif, 1))
1562 return ((tmsize_t)(-1));
1563 if (tile >= td->td_nstrips)
1564 {
1565 TIFFErrorExtR(tif, module,
1566 "%" PRIu32 ": Tile out of range, max %" PRIu32, tile,
1567 td->td_nstrips);
1568 return ((tmsize_t)(-1));
1569 }
1570 if (tif->tif_flags & TIFF_NOREADRAW)
1571 {
1572 TIFFErrorExtR(tif, module,
1573 "Compression scheme does not support access to raw "
1574 "uncompressed data");
1575 return ((tmsize_t)(-1));
1576 }
1577 bytecount64 = TIFFGetStrileByteCount(tif, tile);
1578 if (size != (tmsize_t)(-1) && (uint64_t)size <= bytecount64)
1579 bytecountm = size;
1580 else
1581 bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
1582 if (bytecountm == 0)
1583 {
1584 return ((tmsize_t)(-1));
1585 }
1586 return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module));
1587}
1610/*
1611 * Read the specified tile and setup for decoding. The data buffer is
1612 * expanded, as necessary, to hold the tile's data.
1613 */
1614int TIFFFillTile(TIFF *tif, uint32_t tile)
1615{
1616 static const char module[] = "TIFFFillTile";
1617 TIFFDirectory *td = &tif->tif_dir;
1618
1619 if ((tif->tif_flags & TIFF_NOREADRAW) == 0)
1620 {
1621 uint64_t bytecount = TIFFGetStrileByteCount(tif, tile);
1622 if (bytecount == 0 || bytecount > (uint64_t)TIFF_INT64_MAX)
1623 {
1624 TIFFErrorExtR(tif, module,
1625 "%" PRIu64 ": Invalid tile byte count, tile %" PRIu32,
1626 bytecount, tile);
1627 return (0);
1628 }
1629
1630 /* To avoid excessive memory allocations: */
1631 const tmsize_t tilesize = TIFFTileSize(tif);
1632 if (tilesize > 0)
1633 {
1634 if (bytecount > 1024 * 1024 &&
1635 (bytecount - 4096) / 10 > (uint64_t)tilesize)
1636 {
1637 /* Byte count should normally not be larger than a number of */
1638 /* times the uncompressed size plus some margin */
1639 /* 10 and 4096 are just values that could be adjusted. */
1640 /* Hopefully they are safe enough for all codecs */
1641 /* What happens next will depend on whether only the bytecount
1642 */
1643 /* was corrupted to a large value but the strip/tile data is */
1644 /* fine. In that situation most codecs should work fine and */
1645 /* only used part of the tile/strip data. If the strip/tile */
1646 /* data is corrupted too, then codecs will later error out. */
1647 uint64_t newbytecount = (uint64_t)tilesize * 10 + 4096;
1648 TIFFWarningExtR(tif, module,
1649 "Too large tile byte count %" PRIu64
1650 ", tile %" PRIu32 ". Limiting to %" PRIu64,
1651 bytecount, tile, newbytecount);
1652 bytecount = newbytecount;
1653 }
1654 else if (tilesize > 100 * 1024 * 1024)
1655 {
1656 /* Max compression ratio experimentally determined. Might be
1657 * fragile... Only apply this heuristics to situations where the
1658 * memory allocation would be big, to avoid breaking nominal use
1659 * cases.
1660 */
1661 const uint64_t maxCompressionRatio =
1663 if (maxCompressionRatio > 0 &&
1664 bytecount < (uint64_t)tilesize / maxCompressionRatio)
1665 {
1666 TIFFErrorExtR(tif, module,
1667 "Likely invalid tile byte count for tile %u. "
1668 "Uncompressed tile size is %" PRIu64 ", "
1669 "compressed one is %" PRIu64,
1670 tile, (uint64_t)tilesize, bytecount);
1671 return 0;
1672 }
1673 }
1674 }
1675
1676 if (isMapped(tif))
1677 {
1678 /*
1679 * We must check for overflow, potentially causing
1680 * an OOB read. Instead of simple
1681 *
1682 * TIFFGetStrileOffset(tif, tile)+bytecount > tif->tif_size
1683 *
1684 * comparison (which can overflow) we do the following
1685 * two comparisons:
1686 */
1687 if (bytecount > (uint64_t)tif->tif_size ||
1688 TIFFGetStrileOffset(tif, tile) >
1689 (uint64_t)tif->tif_size - bytecount)
1690 {
1691 tif->tif_dir.td_curtile = NOTILE;
1692 return (0);
1693 }
1694 }
1695
1696 if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) ||
1697 (tif->tif_flags & TIFF_NOBITREV)))
1698 {
1699 /*
1700 * The image is mapped into memory and we either don't
1701 * need to flip bits or the compression routine is
1702 * going to handle this operation itself. In this
1703 * case, avoid copying the raw data and instead just
1704 * reference the data from the memory mapped file
1705 * image. This assumes that the decompression
1706 * routines do not modify the contents of the raw data
1707 * buffer (if they try to, the application will get a
1708 * fault since the file is mapped read-only).
1709 */
1710 if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
1711 {
1712 _TIFFfreeExt(tif, tif->tif_rawdata);
1713 tif->tif_rawdata = NULL;
1714 tif->tif_rawdatasize = 0;
1715 }
1716 tif->tif_flags &= ~TIFF_MYBUFFER;
1717
1718 uint8_t *mapped_rawdata =
1719 tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, tile);
1720 tif->tif_rawdatasize = (tmsize_t)bytecount;
1721 tif->tif_rawdata = mapped_rawdata;
1722 tif->tif_rawdataoff = 0;
1723 tif->tif_rawdataloaded = (tmsize_t)bytecount;
1724 tif->tif_flags |= TIFF_BUFFERMMAP;
1725 }
1726 else
1727 {
1728 /*
1729 * Expand raw data buffer, if needed, to hold data
1730 * tile coming from file (perhaps should set upper
1731 * bound on the size of a buffer we'll use?).
1732 */
1733 tmsize_t bytecountm;
1734 bytecountm = (tmsize_t)bytecount;
1735 if ((uint64_t)bytecountm != bytecount)
1736 {
1737 TIFFErrorExtR(tif, module, "Integer overflow");
1738 return (0);
1739 }
1740 if (bytecountm > tif->tif_rawdatasize)
1741 {
1742 tif->tif_dir.td_curtile = NOTILE;
1743 if ((tif->tif_flags & TIFF_MYBUFFER) == 0)
1744 {
1745 TIFFErrorExtR(tif, module,
1746 "Data buffer too small to hold tile %" PRIu32,
1747 tile);
1748 return (0);
1749 }
1750 }
1751 if (tif->tif_flags & TIFF_BUFFERMMAP)
1752 {
1753 tif->tif_dir.td_curtile = NOTILE;
1754 tif->tif_rawdata = NULL;
1755 tif->tif_rawdatasize = 0;
1756 tif->tif_flags &= ~TIFF_BUFFERMMAP;
1757 }
1758
1759 if (isMapped(tif))
1760 {
1761 if (bytecountm > tif->tif_rawdatasize &&
1762 !TIFFReadBufferSetup(tif, 0, bytecountm))
1763 {
1764 return (0);
1765 }
1766 if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm,
1767 module) != bytecountm)
1768 {
1769 return (0);
1770 }
1771 }
1772 else
1773 {
1774 if (TIFFReadRawStripOrTile2(tif, tile, 0, bytecountm, module) !=
1775 bytecountm)
1776 {
1777 return (0);
1778 }
1779 }
1780
1781 tif->tif_rawdataoff = 0;
1782 tif->tif_rawdataloaded = bytecountm;
1783
1784 if (tif->tif_rawdata != NULL &&
1785 !isFillOrder(tif, td->td_fillorder) &&
1786 (tif->tif_flags & TIFF_NOBITREV) == 0)
1788 }
1789 }
1790 return (TIFFStartTile(tif, tile));
1791}
1792
1793/*
1794 * Setup the raw data buffer in preparation for
1795 * reading a strip of raw data. If the buffer
1796 * is specified as zero, then a buffer of appropriate
1797 * size is allocated by the library. Otherwise,
1798 * the client must guarantee that the buffer is
1799 * large enough to hold any individual strip of
1800 * raw data.
1801 */
1802int TIFFReadBufferSetup(TIFF *tif, void *bp, tmsize_t size)
1803{
1804 static const char module[] = "TIFFReadBufferSetup";
1805
1806 if (tif->tif_flags & TIFF_NOREADRAW)
1807 {
1808 TIFFErrorExtR(tif, module,
1809 "Compression scheme does not support access to raw "
1810 "uncompressed data");
1811 return (0);
1812 }
1813 tif->tif_flags &= ~TIFF_BUFFERMMAP;
1814
1815 if (tif->tif_rawdata)
1816 {
1817 if (tif->tif_flags & TIFF_MYBUFFER)
1818 _TIFFfreeExt(tif, tif->tif_rawdata);
1819 tif->tif_rawdata = NULL;
1820 tif->tif_rawdatasize = 0;
1821 }
1822 /* The decode position pointed into the old buffer; force a reload. */
1823 tif->tif_rawcp = NULL;
1824 tif->tif_rawcc = 0;
1825 tif->tif_rawdataoff = 0;
1826 tif->tif_rawdataloaded = 0;
1828 tif->tif_dir.td_curtile = NOTILE;
1829 if (bp)
1830 {
1831 tif->tif_rawdatasize = size;
1832 tif->tif_rawdata = (uint8_t *)bp;
1833 tif->tif_flags &= ~TIFF_MYBUFFER;
1834 }
1835 else
1836 {
1837 tmsize_t new_rawdatasize =
1838 (tmsize_t)TIFFroundup_64((uint64_t)size, 1024);
1839 uint8_t *new_rawdata;
1840 if (new_rawdatasize == 0)
1841 {
1842 TIFFErrorExtR(tif, module, "Invalid buffer size");
1843 return (0);
1844 }
1845 /* Initialize to zero to avoid uninitialized buffers in case of */
1846 /* short reads (http://bugzilla.maptools.org/show_bug.cgi?id=2651) */
1847 new_rawdata = (uint8_t *)_TIFFcallocExt(tif, 1, new_rawdatasize);
1848 /* Set even on failure, so a later read retries the allocation. */
1849 tif->tif_flags |= TIFF_MYBUFFER;
1850 if (new_rawdata == NULL)
1851 {
1852 TIFFErrorExtR(tif, module,
1853 "No space for data buffer at scanline %" PRIu32,
1854 tif->tif_dir.td_row);
1855 return (0);
1856 }
1857 tif->tif_rawdatasize = new_rawdatasize;
1858 tif->tif_rawdata = new_rawdata;
1859 }
1860 return (1);
1861}
1882/*
1883 * Set state to appear as if a
1884 * strip has just been read in.
1885 */
1886static int TIFFStartStrip(TIFF *tif, uint32_t strip)
1887{
1888 static const char module[] = "TIFFStartStrip";
1889 TIFFDirectory *td = &tif->tif_dir;
1890
1891 if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
1892 {
1893 if (!(*tif->tif_setupdecode)(tif))
1894 return (0);
1895 tif->tif_flags |= TIFF_CODERSETUP;
1896 }
1897 if (td->td_stripsperimage == 0)
1898 {
1899 TIFFErrorExtR(tif, module, "Zero strips per image");
1900 return 0;
1901 }
1902 tif->tif_dir.td_curstrip = strip;
1903 if (TIFFSafeModMul32(tif, module, strip, td->td_stripsperimage,
1904 td->td_rowsperstrip, tif->tif_dir.td_row))
1905 return 0;
1906 tif->tif_flags &= ~TIFF_BUF4WRITE;
1907
1908 if (tif->tif_flags & TIFF_NOREADRAW)
1909 {
1910 tif->tif_rawcp = NULL;
1911 tif->tif_rawcc = 0;
1912 }
1913 else
1914 {
1915 tif->tif_rawcp = tif->tif_rawdata;
1916 if (tif->tif_rawdataloaded > 0)
1917 tif->tif_rawcc = tif->tif_rawdataloaded;
1918 else
1919 tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, strip);
1920 }
1921 if ((*tif->tif_predecode)(tif, (uint16_t)(strip / td->td_stripsperimage)) ==
1922 0)
1923 {
1924 /* Needed for example for scanline access, if tif_predecode */
1925 /* fails, and we try to read the same strip again. Without invalidating
1926 */
1927 /* tif_curstrip, we'd call tif_decoderow() on a possibly invalid */
1928 /* codec state. */
1930 return 0;
1931 }
1932 return 1;
1933}
1955/*
1956 * Set state to appear as if a
1957 * tile has just been read in.
1958 */
1959static int TIFFStartTile(TIFF *tif, uint32_t tile)
1960{
1961 static const char module[] = "TIFFStartTile";
1962 TIFFDirectory *td = &tif->tif_dir;
1963 uint32_t howmany32;
1964
1965 if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
1966 {
1967 if (!(*tif->tif_setupdecode)(tif))
1968 return (0);
1969 tif->tif_flags |= TIFF_CODERSETUP;
1970 }
1971 tif->tif_dir.td_curtile = tile;
1972 if (td->td_tilewidth == 0)
1973 {
1974 TIFFErrorExtR(tif, module, "Zero tilewidth");
1975 return 0;
1976 }
1977 howmany32 = TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
1978 if (howmany32 == 0)
1979 {
1980 TIFFErrorExtR(tif, module, "Zero tiles");
1981 return 0;
1982 }
1983 if (td->td_tilelength == 0)
1984 {
1985 TIFFErrorExtR(tif, module, "Zero tilelength");
1986 return 0;
1987 }
1988 if (TIFFSafeModMul32(tif, module, tile, howmany32, td->td_tilelength,
1989 tif->tif_dir.td_row))
1990 return 0;
1991 howmany32 = TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
1992 if (howmany32 == 0)
1993 {
1994 TIFFErrorExtR(tif, module, "Zero tiles");
1995 return 0;
1996 }
1997 if (TIFFSafeModMul32(tif, module, tile, howmany32, td->td_tilewidth,
1998 tif->tif_dir.td_col))
1999 return 0;
2000 tif->tif_flags &= ~TIFF_BUF4WRITE;
2001 if (tif->tif_flags & TIFF_NOREADRAW)
2002 {
2003 tif->tif_rawcp = NULL;
2004 tif->tif_rawcc = 0;
2005 }
2006 else
2007 {
2008 tif->tif_rawcp = tif->tif_rawdata;
2009 if (tif->tif_rawdataloaded > 0)
2010 tif->tif_rawcc = tif->tif_rawdataloaded;
2011 else
2012 tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, tile);
2013 }
2014 return (
2015 (*tif->tif_predecode)(tif, (uint16_t)(tile / td->td_stripsperimage)));
2016}
2036static int TIFFCheckRead(TIFF *tif, int tiles)
2037{
2038 if (tif->tif_mode == O_WRONLY)
2039 {
2040 TIFFErrorExtR(tif, tif->tif_name, "File not open for reading");
2041 return (0);
2042 }
2043 if (tiles ^ isTiled(tif))
2044 {
2045 TIFFErrorExtR(tif, tif->tif_name,
2046 tiles ? "Can not read tiles from a striped image"
2047 : "Can not read scanlines from a tiled image");
2048 return (0);
2049 }
2050
2051 /*
2052 * A scanline write can leave the encoder holding pointers into the raw
2053 * data buffer until TIFFFlushData() calls its postencode routine. A
2054 * subsequent read may resize that buffer while loading a strile. Finish
2055 * the pending write before the read can invalidate those pointers.
2056 *
2057 * Also invalidate the current strile. In particular, a read of the next
2058 * row in the same strip must reload the strip and run predecode instead of
2059 * continuing from the encoder's row/strile state.
2060 */
2061 if (tif->tif_flags & TIFF_BUF4WRITE)
2062 {
2063 if (!TIFFFlushData(tif))
2064 return (0);
2065 tif->tif_flags &= ~TIFF_BUF4WRITE;
2067 tif->tif_dir.td_curtile = NOTILE;
2068 }
2069 return (1);
2070}
2071
2072/* Use the provided input buffer (inbuf, insize) and decompress it into
2073 * (outbuf, outsize).
2074 * This function replaces the use of
2075 * TIFFReadEncodedStrip()/TIFFReadEncodedTile() when the user can provide the
2076 * buffer for the input data, for example when he wants to avoid libtiff to read
2077 * the strile offset/count values from the [Strip|Tile][Offsets/ByteCounts]
2078 * array. inbuf content must be writable (if bit reversal is needed) Returns 1
2079 * in case of success, 0 otherwise.
2080 */
2081int TIFFReadFromUserBuffer(TIFF *tif, uint32_t strile, void *inbuf,
2082 tmsize_t insize, void *outbuf, tmsize_t outsize)
2083{
2084 static const char module[] = "TIFFReadFromUserBuffer";
2085 TIFFDirectory *td = &tif->tif_dir;
2086 int ret = 1;
2087 uint32_t old_tif_flags = tif->tif_flags;
2088 tmsize_t old_rawdatasize = tif->tif_rawdatasize;
2089 void *old_rawdata = tif->tif_rawdata;
2090
2091 if (outsize < 0)
2092 {
2093 TIFFErrorExtR(tif, module, "Invalid output size %" TIFF_SSIZE_FORMAT,
2094 outsize);
2095 return 0;
2096 }
2097 if (tif->tif_mode == O_WRONLY)
2098 {
2099 TIFFErrorExtR(tif, tif->tif_name, "File not open for reading");
2100 return 0;
2101 }
2102 if (tif->tif_flags & TIFF_NOREADRAW)
2103 {
2104 TIFFErrorExtR(tif, module,
2105 "Compression scheme does not support access to raw "
2106 "uncompressed data");
2107 return 0;
2108 }
2109 if (insize <= 0)
2110 {
2111 TIFFErrorExtR(tif, module, "Invalid input buffer size");
2112 return 0;
2113 }
2114
2115 tif->tif_flags &= ~TIFF_MYBUFFER;
2116 tif->tif_flags |= TIFF_BUFFERMMAP;
2117 tif->tif_rawdatasize = insize;
2118 tif->tif_rawdata = (uint8_t *)inbuf;
2119 tif->tif_rawdataoff = 0;
2120 tif->tif_rawdataloaded = insize;
2121
2122 if (!isFillOrder(tif, td->td_fillorder) &&
2123 (tif->tif_flags & TIFF_NOBITREV) == 0)
2124 {
2125 TIFFReverseBits((uint8_t *)inbuf, insize);
2126 }
2127
2128 if (TIFFIsTiled(tif))
2129 {
2130 if (!TIFFStartTile(tif, strile))
2131 {
2132 ret = 0;
2133 /* See related TIFFReadEncodedStrip comment. */
2134 if (outbuf)
2135 memset(outbuf, 0, (size_t)outsize);
2136 }
2137 else if ((*tif->tif_decodetile)(
2138 tif, (uint8_t *)outbuf, outsize,
2139 (uint16_t)(strile / td->td_stripsperimage)) <= 0)
2140 {
2141 ret = 0;
2142 }
2143 }
2144 else
2145 {
2146 uint32_t rowsperstrip = td->td_rowsperstrip;
2147 uint32_t stripsperplane;
2148 if (rowsperstrip > td->td_imagelength)
2149 rowsperstrip = td->td_imagelength;
2150 if (rowsperstrip == 0)
2151 {
2152 TIFFErrorExtR(tif, module, "rowsperstrip is zero");
2153 ret = 0;
2154 }
2155 else
2156 {
2157 stripsperplane =
2158 TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
2159 if (!TIFFStartStrip(tif, strile))
2160 {
2161 ret = 0;
2162 /* See related TIFFReadEncodedStrip comment. */
2163 if (outbuf)
2164 memset(outbuf, 0, (size_t)outsize);
2165 }
2166 else if ((*tif->tif_decodestrip)(
2167 tif, (uint8_t *)outbuf, outsize,
2168 (uint16_t)(strile / stripsperplane)) <= 0)
2169 {
2170 ret = 0;
2171 }
2172 }
2173 }
2174 if (ret)
2175 {
2176 if (_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, outsize,
2177 module))
2178 (*tif->tif_postdecode)(tif, (uint8_t *)outbuf, outsize);
2179 else
2180 ret = 0;
2181 }
2182
2183 if (!isFillOrder(tif, td->td_fillorder) &&
2184 (tif->tif_flags & TIFF_NOBITREV) == 0)
2185 {
2186 TIFFReverseBits((uint8_t *)inbuf, insize);
2187 }
2188
2189 tif->tif_flags = (old_tif_flags & (TIFF_MYBUFFER | TIFF_BUFFERMMAP)) |
2191 tif->tif_rawdatasize = old_rawdatasize;
2192 tif->tif_rawdata = (uint8_t *)old_rawdata;
2193 tif->tif_rawdataoff = 0;
2194 tif->tif_rawdataloaded = 0;
2195
2196 /*
2197 * The decoder has just operated on caller-owned temporary input data.
2198 * Do not leave pointers or strile state referring to that buffer after
2199 * TIFFReadFromUserBuffer() returns.
2200 */
2201 tif->tif_rawcp = tif->tif_rawdata;
2202 tif->tif_rawcc = 0;
2203 td->td_curstrip = NOSTRIP;
2204 td->td_curtile = NOTILE;
2205
2206 return ret;
2207}
2208
2209void _TIFFNoPostDecode(TIFF *tif, uint8_t *buf, tmsize_t cc)
2210{
2211 (void)tif;
2212 (void)buf;
2213 (void)cc;
2214}
2215
2216void _TIFFSwab16BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
2217{
2218 if ((cc & 1) != 0)
2219 TIFFWarningExtR(tif, "_TIFFSwab16BitData()",
2220 "Number of bytes to swap %" TIFF_SSIZE_FORMAT
2221 " is odd. Result might be incorrect",
2222 cc);
2223 TIFFSwabArrayOfShort((uint16_t *)buf, cc / 2);
2224}
2225
2226void _TIFFSwab24BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
2227{
2228 if ((cc % 3) != 0)
2229 TIFFWarningExtR(tif, "_TIFFSwab24BitData()",
2230 "Number of bytes to swap %" TIFF_SSIZE_FORMAT
2231 " is not a multiple of 3. Result might be incorrect",
2232 cc);
2233 TIFFSwabArrayOfTriples((uint8_t *)buf, cc / 3);
2234}
2235
2236void _TIFFSwab32BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
2237{
2238 if ((cc & 3) != 0)
2239 TIFFWarningExtR(tif, "_TIFFSwab32BitData()",
2240 "Number of bytes to swap %" TIFF_SSIZE_FORMAT
2241 " is not a multiple of 4. Result might be incorrect",
2242 cc);
2243 TIFFSwabArrayOfLong((uint32_t *)buf, cc / 4);
2244}
2245
2246void _TIFFSwab64BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
2247{
2248 if ((cc & 7) != 0)
2249 TIFFWarningExtR(tif, "_TIFFSwab64BitData()",
2250 "Number of bytes to swap %" TIFF_SSIZE_FORMAT
2251 " is not a multiple of 8. Result might be incorrect",
2252 cc);
2253 TIFFSwabArrayOfDouble((double *)buf, cc / 8);
2254}
2255
2256/* Checks that the byte count passed to a byte-swapping postdecode function
2257 * is a multiple of the sample size. Returns 1 if the count is acceptable
2258 * and 0 otherwise, in which case the caller must fail the operation
2259 * instead of swapping. */
2261 tmsize_t cc, const char *modulename)
2262{
2263 int idx = -1;
2264 static const char multiplenumber[] = {2, 3, 4, 8};
2265 static const char *const postdecodename[] = {
2266 "_TIFFSwab16BitData", "_TIFFSwab24BitData", "_TIFFSwab32BitData",
2267 "_TIFFSwab64BitData"};
2268 if (tif_postdecode == _TIFFSwab16BitData && ((cc & 1) != 0))
2269 idx = 0;
2270 else if (tif_postdecode == _TIFFSwab24BitData && ((cc % 3) != 0))
2271 idx = 1;
2272 else if (tif_postdecode == _TIFFSwab32BitData && ((cc & 3) != 0))
2273 idx = 2;
2274 else if (tif_postdecode == _TIFFSwab64BitData && ((cc & 7) != 0))
2275 idx = 3;
2276 else
2277 return 1;
2278
2279 TIFFErrorExtR(tif, modulename,
2280 "Number of bytes (%" TIFF_SSIZE_FORMAT
2281 ") to swap with %s is not a multiple of %d; rejected",
2282 cc, postdecodename[idx], multiplenumber[idx]);
2283 return 0;
2284}
uint32_t _TIFFCastUInt64ToUInt32(TIFF *tif, uint64_t val, const char *module)
Convert an unsigned 64-bit value after checking the destination range.
Definition tif_aux.c:153
uint64_t _TIFFAdd64(TIFF *tif, uint64_t first, uint64_t second, const char *where)
Check and add two unsigned operands.
Definition tif_aux.c:85
tmsize_t _TIFFCastUInt64ToSSize(TIFF *tif, uint64_t val, const char *module)
Convert an unsigned 64-bit value after checking the destination range.
Definition tif_aux.c:140
uint64_t _TIFFMultiply64(TIFF *tif, uint64_t first, uint64_t second, const char *where)
Multiply two unsigned values with an overflow check.
Definition tif_aux.c:46
#define TIFF_SSIZE_FORMAT
Provide the printf conversion fragment for tmsize_t, without a percent sign.
Definition tif_config.h:294
#define NOSTRIP
Represent the absence of a current strip with UINT32_MAX.
Definition tif_dir.h:250
#define NOTILE
Represent the absence of a current tile with UINT32_MAX.
Definition tif_dir.h:264
uint32_t _TIFFComputeTileExt(TIFF *tif, uint32_t x, uint32_t y, uint32_t z, uint16_t s, bool *pOverflowed)
Compute a tile index as TIFFComputeTile() does, and record an index overflow in a caller-provided fla...
Definition tif_tile.c:52
#define TIFF_INT64_MAX
Bound accepted raw strile byte counts to INT64_MAX.
Definition tif_read.c:83
tmsize_t _TIFFReadEncodedTileAndAllocBuffer(TIFF *tif, uint32_t tile, void **buf, tmsize_t bufsizetoalloc, tmsize_t size_to_read)
Decode after deferred allocation of caller-owned output storage.
Definition tif_read.c:1373
#define INITIAL_THRESHOLD
Start progressive raw-buffer reads at one MiB.
Definition tif_read.c:56
int _TIFFCheckPostDecodeLength(TIFF *tif, TIFFPostMethod tif_postdecode, tmsize_t cc, const char *modulename)
Check the byte count for a byte-swapping postdecode method.
Definition tif_read.c:2260
static tmsize_t TIFFReadRawStrip1(TIFF *tif, uint32_t strip, void *buf, tmsize_t size, const char *module)
Read an exact raw-strip byte extent into caller storage.
Definition tif_read.c:853
#define MAX_THRESHOLD
Set the allocation-growth cutoff to 1000 MiB.
Definition tif_read.c:72
void _TIFFNoPostDecode(TIFF *tif, uint8_t *buf, tmsize_t cc)
Leave decoded bytes unchanged.
Definition tif_read.c:2209
tmsize_t _TIFFReadEncodedStripAndAllocBuffer(TIFF *tif, uint32_t strip, void **buf, tmsize_t bufsizetoalloc, tmsize_t size_to_read)
Decode after deferred allocation of caller-owned output storage.
Definition tif_read.c:769
static TIFF_NOSANITIZE_UNSIGNED_INT_OVERFLOW uint64_t NoSanitizeSubUInt64(uint64_t a, uint64_t b)
Subtract unsigned offsets with intentional modular arithmetic.
Definition tif_read.c:1027
tmsize_t _TIFFReadTileAndAllocBuffer(TIFF *tif, void **buf, tmsize_t bufsizetoalloc, uint32_t x, uint32_t y, uint32_t z, uint16_t s)
Decode after deferred allocation of caller-owned output storage.
Definition tif_read.c:1350
static int TIFFSeek(TIFF *tif, uint32_t row, uint16_t sample)
Position strip decoding at a requested scanline.
Definition tif_read.c:439
void(* TIFFPostMethod)(TIFF *tif, uint8_t *buf, tmsize_t size)
Transform image bytes in place after decoding or before encoding.
Definition tiffiop.h:277
static tmsize_t TIFFReadRawStripOrTile2(TIFF *tif, uint32_t strip_or_tile, int is_strip, tmsize_t size, const char *module)
Seek to a strile and read bytes into the expandable raw cache.
Definition tif_read.c:938
static tmsize_t TIFFReadEncodedStripGetStripSize(TIFF *tif, uint32_t strip, uint16_t *pplane)
Validate a strip and compute its effective decoded extent.
Definition tif_read.c:662
void _TIFFSwab24BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
Swap each 3-byte sample in place.
Definition tif_read.c:2226
void _TIFFSwab16BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
Swap each 2-byte sample in place.
Definition tif_read.c:2216
static int TIFFReadAndRealloc(TIFF *tif, tmsize_t size, tmsize_t rawdata_offset, int is_strip, uint32_t strip_or_tile, const char *module)
Grow and fill the raw buffer from the current client position.
Definition tif_read.c:116
#define THRESHOLD_MULTIPLIER
Grow raw-buffer read allocation stages by a factor of ten.
Definition tif_read.c:64
static int TIFFStartStrip(TIFF *tif, uint32_t strip)
Prepare the codec and raw cursor for strip decoding.
Definition tif_read.c:1886
int TIFFFillTile(TIFF *tif, uint32_t tile)
Load raw tile bytes and initialise codec decoding.
Definition tif_read.c:1614
void _TIFFSwab32BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
Swap each 4-byte sample in place.
Definition tif_read.c:2236
static tmsize_t TIFFReadRawTile1(TIFF *tif, uint32_t tile, void *buf, tmsize_t size, const char *module)
Read an exact raw-tile byte extent into caller storage.
Definition tif_read.c:1483
int TIFFFillStrip(TIFF *tif, uint32_t strip)
Load raw strip bytes and initialise codec decoding.
Definition tif_read.c:1055
static int TIFFCheckRead(TIFF *, int)
Check readable mode and expected image organisation.
Definition tif_read.c:2036
void _TIFFSwab64BitData(TIFF *tif, uint8_t *buf, tmsize_t cc)
Swap each 8-byte sample in place.
Definition tif_read.c:2246
static int TIFFStartTile(TIFF *tif, uint32_t tile)
Prepare the codec and raw cursor for tile decoding.
Definition tif_read.c:1959
static int TIFFFillStripPartial(TIFF *tif, int strip, tmsize_t read_ahead, int restart)
Refill a partial raw strip while retaining unconsumed bytes.
Definition tif_read.c:254
int TIFFJPEGIsFullStripRequired(TIFF *tif)
Probe whether cached JPEG input needs whole-strile decoding.
Definition tif_jpeg.c:2410
void _TIFFfreeExt(TIFF *tif, void *p)
Release a handle-aware allocation and its payload charge.
Definition tif_open.c:301
void * _TIFFreallocExt(TIFF *tif, void *p, tmsize_t s)
Resize a handle-aware block or release it for a nonpositive size.
Definition tif_open.c:257
void * _TIFFmallocExt(TIFF *tif, tmsize_t s)
Allocate uninitialised bytes under a handle's allocation policy.
Definition tif_open.c:195
void * _TIFFcallocExt(TIFF *tif, tmsize_t nmemb, tmsize_t siz)
Allocate a zero-filled array under a handle's allocation policy.
Definition tif_open.c:224
#define TIFFroundup_64(x, y)
Round a 64-bit value up to a multiple without overflow checks.
Definition tiffiop.h:1142
#define TIFFReadFile(tif, buf, size)
Invoke the handle's client read callback.
Definition tiffiop.h:885
#define isTiled(tif)
Test whether a handle uses tiled storage.
Definition tiffiop.h:833
#define TIFF_MYBUFFER
Mark a raw buffer owned and released by the handle.
Definition tiffiop.h:451
#define TIFF_NOSANITIZE_UNSIGNED_INT_OVERFLOW
Suppress unsigned-overflow instrumentation on supported Clang functions.
Definition tiffiop.h:1484
#define TIFFhowmany_32_maxuint_compat(x, y)
Compute a 32-bit ceiling quotient without adding x and y first.
Definition tiffiop.h:1074
#define TIFF_CODERSETUP
Mark completed codec setup.
Definition tiffiop.h:431
#define TIFFSafeModMul32(tif, module, index, count, dimension, result)
Compute (index modulo count) times dimension with a checked product.
Definition tiffiop.h:1195
#define TIFF_BUF4WRITE
Interpret the raw buffer and its byte count as pending output.
Definition tiffiop.h:513
#define SeekOK(tif, off)
Test whether an absolute seek reaches the requested file position.
Definition tiffiop.h:1017
#define isMapped(tif)
Test whether TIFF_MAPPED is set on a handle.
Definition tiffiop.h:845
#define isFillOrder(tif, o)
Test whether selected bit-fill-order bits are present in a handle.
Definition tiffiop.h:858
#define TIFFGetFileSize(tif)
Invoke the handle's client size callback.
Definition tiffiop.h:946
#define TIFF_NOREADRAW
Suppress the normal raw-data read path.
Definition tiffiop.h:496
#define TIFFhowmany_32(x, y)
Compute a guarded 32-bit ceiling quotient.
Definition tiffiop.h:1056
#define TIFF_NOBITREV
Suppress automatic bit reversal.
Definition tiffiop.h:446
#define TIFF_BUFFERMMAP
Mark raw data that borrows mapped-file storage.
Definition tiffiop.h:528
void TIFFSwabArrayOfTriples(uint8_t *tp, tmsize_t n)
Reverse the byte order of each array element.
Definition tif_swab.c:105
void TIFFSwabArrayOfDouble(double *dp, tmsize_t n)
Reverse the byte order of each array element.
Definition tif_swab.c:228
void TIFFSwabArrayOfShort(uint16_t *wp, tmsize_t n)
Reverse the byte order of each array element.
Definition tif_swab.c:87
void TIFFSwabArrayOfLong(uint32_t *lp, tmsize_t n)
Reverse the byte order of each array element.
Definition tif_swab.c:123
void TIFFReverseBits(uint8_t *cp, tmsize_t n)
Reverse the bit order within each byte of a buffer.
Definition tif_swab.c:330
void TIFFWarningExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a warning diagnostic to the configured handlers.
Definition tif_warning.c:85
void TIFFErrorExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a error diagnostic to the configured handlers.
Definition tif_error.c:112
int TIFFReadBufferSetup(TIFF *tif, void *bp, tmsize_t size)
Replace the handle's raw reading buffer.
Definition tif_read.c:1802
uint64_t TIFFGetMaxCompressionRatio(TIFF *tif)
Query the codec's allocation-recovery compression-ratio heuristic.
tmsize_t TIFFTileSize(TIFF *tif)
Compute the decoded-size estimate for the configured tile height.
Definition tif_tile.c:307
tmsize_t TIFFStripSize(TIFF *tif)
Compute the decoded-size estimate for a nominal strip.
Definition tif_strip.c:244
tmsize_t TIFFVStripSize(TIFF *tif, uint32_t nrows)
Compute the decoded-size estimate for a requested strip height.
Definition tif_strip.c:182
int TIFFCheckTile(TIFF *tif, uint32_t x, uint32_t y, uint32_t z, uint16_t s)
Check pixel and separate-sample coordinates against image bounds.
Definition tif_tile.c:118
int TIFFReadScanline(TIFF *tif, void *buf, uint32_t row, uint16_t sample)
Decode one image scanline into caller storage.
Definition tif_read.c:602
int TIFFReadFromUserBuffer(TIFF *tif, uint32_t strile, void *inbuf, tmsize_t insize, void *outbuf, tmsize_t outsize)
Decode one strile from caller-provided stored bytes.
Definition tif_read.c:2081
tmsize_t TIFFReadRawStrip(TIFF *tif, uint32_t strip, void *buf, tmsize_t size)
Read stored bytes from one strip.
Definition tif_read.c:974
tmsize_t TIFFReadRawTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
Read stored bytes from one tile.
Definition tif_read.c:1549
tmsize_t TIFFReadEncodedStrip(TIFF *tif, uint32_t strip, void *buf, tmsize_t size)
Read decoded samples from one strip.
Definition tif_read.c:708
tmsize_t TIFFReadTile(TIFF *tif, void *buf, uint32_t x, uint32_t y, uint32_t z, uint16_t s)
Decode the tile containing image coordinates.
Definition tif_read.c:1265
tmsize_t TIFFReadEncodedTile(TIFF *tif, uint32_t tile, void *buf, tmsize_t size)
Read decoded samples from one tile.
Definition tif_read.c:1284
const char * TIFFFileName(TIFF *tif)
Return the handle's diagnostic filename.
Definition tif_open.c:835
int TIFFFlushData(TIFF *tif)
Flush pending encoded image data without committing directory changes.
Definition tif_flush.c:151
int TIFFIsTiled(TIFF *tif)
Test whether the current image uses tiles.
Definition tif_open.c:896
void _TIFFmemset(void *p, int v, tmsize_t c)
Fill a byte range with one repeated byte.
Definition tif_unix.c:495
void _TIFFmemcpy(void *d, const void *s, tmsize_t c)
Copy a non-overlapping byte range.
Definition tif_unix.c:497
uint64_t TIFFGetStrileOffset(TIFF *tif, uint32_t strile)
Query one logical strile file offset.
uint64_t TIFFGetStrileByteCount(TIFF *tif, uint32_t strile)
Query one logical strile byte count.
#define COMPRESSION_NONE
Dump mode.
Definition tiff.h:302
#define PLANARCONFIG_SEPARATE
Separate planes of data.
Definition tiff.h:474
#define COMPRESSION_JBIG
ISO JBIG.
Definition tiff.h:356
#define COMPRESSION_LERC
ESRI LERC compression.
Definition tiff.h:364
#define COMPRESSION_JPEG
JPEG DCT compression (introduced after TIFF 6.0).
Definition tiff.h:318
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
#define TIFF_TMSIZE_T_MAX
Define the largest positive size representable by tmsize_t.
Definition tiffio.h:91
Store the current directory values and image traversal state.
Definition tif_dir.h:143
tmsize_t td_tilesize
Cached decoded tile size in bytes; minus one when invalidated.
Definition tif_dir.h:259
uint32_t td_rowsperstrip
Rows per strip; UINT32_MAX represents one whole-image strip.
Definition tif_dir.h:184
uint16_t td_compression
COMPRESSION_* codec identifier.
Definition tif_dir.h:172
tmsize_t td_scanlinesize
Cached decoded scanline size in bytes; zero when not computed.
Definition tif_dir.h:245
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
uint32_t td_stripsperimage
Strips or tiles per sample plane, despite the historic name.
Definition tif_dir.h:269
uint16_t td_planarconfig
PLANARCONFIG_* sample-plane arrangement.
Definition tif_dir.h:200
uint32_t td_col
Current pixel column; UINT32_MAX before traversal starts.
Definition tif_dir.h:253
uint16_t td_samplesperpixel
Samples per pixel, including extra samples.
Definition tif_dir.h:182
uint32_t td_imagelength
Image length in rows.
Definition tif_dir.h:156
uint32_t td_curtile
Current tile index, or NOTILE.
Definition tif_dir.h:256
uint32_t td_curstrip
Current strip index, or NOSTRIP.
Definition tif_dir.h:242
Hold private state for one open TIFF library instance.
Definition tiffiop.h:389
TIFFSeekMethod tif_seek
Codec callback advancing within a strip.
Definition tiffiop.h:659
tmsize_t tif_rawdataloaded
Number of bytes loaded into the raw-buffer window.
Definition tiffiop.h:690
tmsize_t tif_rawcc
Raw-buffer byte count interpreted according to read/write state.
Definition tiffiop.h:696
TIFFPreMethod tif_predecode
Codec callback preparing a row, strip, or tile decode.
Definition tiffiop.h:630
TIFFCodeMethod tif_decodestrip
Codec callback decoding strip data.
Definition tiffiop.h:647
TIFFPostMethod tif_postdecode
Callback transforming decoded data, for example by byte swapping.
Definition tiffiop.h:727
char * tif_name
Current filename pointer; may refer to inline or client-supplied storage.
Definition tiffiop.h:394
TIFFCodeMethod tif_decoderow
Codec callback decoding a scanline.
Definition tiffiop.h:643
TIFFDirectory tif_dir
Inline representation of the current image directory.
Definition tiffiop.h:572
tmsize_t tif_size
Mapped-file region length in bytes.
Definition tiffiop.h:705
uint8_t * tif_rawcp
Borrowed current-position pointer into the raw buffer.
Definition tiffiop.h:692
TIFFBoolMethod tif_setupdecode
Codec setup callback run before predecode.
Definition tiffiop.h:628
uint8_t * tif_rawdata
Raw buffer; ownership/mapping follow TIFF_MYBUFFER and TIFF_BUFFERMMAP.
Definition tiffiop.h:681
tmsize_t tif_rawdatasize
Raw-buffer capacity in bytes; kept in step with tif_rawdata, including zero whenever tif_rawdata is N...
Definition tiffiop.h:686
tmsize_t tif_rawdataoff
Byte offset of the raw-buffer window within the strip.
Definition tiffiop.h:688
uint32_t tif_flags
Bitmask combining the TIFF_* handle-state flags declared below.
Definition tiffiop.h:404
TIFFCodeMethod tif_decodetile
Codec callback decoding tile data.
Definition tiffiop.h:651
int tif_mode
Current access mode using the O_* constants.
Definition tiffiop.h:400
uint8_t * tif_base
Mapped-file base provided by tif_mapproc; released through tif_unmapproc by TIFFCleanup() only while ...
Definition tiffiop.h:703
Declare private library state, callbacks, and implementation helpers.