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