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     tmsize_t this_stripsize;
577     uint16 plane;
578 
579     if( *buf != NULL )
580     {
581         return TIFFReadEncodedStrip(tif, strip, *buf, size_to_read);
582     }
583 
584     this_stripsize=TIFFReadEncodedStripGetStripSize(tif, strip, &plane);
585     if (this_stripsize==((tmsize_t)(-1)))
586             return((tmsize_t)(-1));
587 
588     if ((size_to_read!=(tmsize_t)(-1))&&(size_to_read<this_stripsize))
589             this_stripsize=size_to_read;
590     if (!TIFFFillStrip(tif,strip))
591             return((tmsize_t)(-1));
592 
593     *buf = _TIFFmalloc(bufsizetoalloc);
594     if (*buf == NULL) {
595             TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "No space for strip buffer");
596             return((tmsize_t)(-1));
597     }
598     _TIFFmemset(*buf, 0, bufsizetoalloc);
599 
600     if ((*tif->tif_decodestrip)(tif,*buf,this_stripsize,plane)<=0)
601             return((tmsize_t)(-1));
602     (*tif->tif_postdecode)(tif,*buf,this_stripsize);
603     return(this_stripsize);
604 
605 
606 }
607 
608 static tmsize_t
TIFFReadRawStrip1(TIFF * tif,uint32 strip,void * buf,tmsize_t size,const char * module)609 TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,
610     const char* module)
611 {
612 	assert((tif->tif_flags&TIFF_NOREADRAW)==0);
613 	if (!isMapped(tif)) {
614 		tmsize_t cc;
615 
616 		if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip))) {
617 			TIFFErrorExt(tif->tif_clientdata, module,
618 			    "Seek error at scanline %lu, strip %lu",
619 			    (unsigned long) tif->tif_row, (unsigned long) strip);
620 			return ((tmsize_t)(-1));
621 		}
622 		cc = TIFFReadFile(tif, buf, size);
623 		if (cc != size) {
624 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
625 			TIFFErrorExt(tif->tif_clientdata, module,
626 		"Read error at scanline %lu; got %I64u bytes, expected %I64u",
627 				     (unsigned long) tif->tif_row,
628 				     (unsigned __int64) cc,
629 				     (unsigned __int64) size);
630 #else
631 			TIFFErrorExt(tif->tif_clientdata, module,
632 		"Read error at scanline %lu; got %llu bytes, expected %llu",
633 				     (unsigned long) tif->tif_row,
634 				     (unsigned long long) cc,
635 				     (unsigned long long) size);
636 #endif
637 			return ((tmsize_t)(-1));
638 		}
639 	} else {
640 		tmsize_t ma = 0;
641 		tmsize_t n;
642 		if ((TIFFGetStrileOffset(tif, strip) > (uint64)TIFF_TMSIZE_T_MAX)||
643                     ((ma=(tmsize_t)TIFFGetStrileOffset(tif, strip))>tif->tif_size))
644                 {
645                     n=0;
646                 }
647                 else if( ma > TIFF_TMSIZE_T_MAX - size )
648                 {
649                     n=0;
650                 }
651                 else
652                 {
653                     tmsize_t mb=ma+size;
654                     if (mb>tif->tif_size)
655                             n=tif->tif_size-ma;
656                     else
657                             n=size;
658                 }
659 		if (n!=size) {
660 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
661 			TIFFErrorExt(tif->tif_clientdata, module,
662 	"Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u",
663 				     (unsigned long) tif->tif_row,
664 				     (unsigned long) strip,
665 				     (unsigned __int64) n,
666 				     (unsigned __int64) size);
667 #else
668 			TIFFErrorExt(tif->tif_clientdata, module,
669 	"Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu",
670 				     (unsigned long) tif->tif_row,
671 				     (unsigned long) strip,
672 				     (unsigned long long) n,
673 				     (unsigned long long) size);
674 #endif
675 			return ((tmsize_t)(-1));
676 		}
677 		_TIFFmemcpy(buf, tif->tif_base + ma,
678 			    size);
679 	}
680 	return (size);
681 }
682 
683 static tmsize_t
TIFFReadRawStripOrTile2(TIFF * tif,uint32 strip_or_tile,int is_strip,tmsize_t size,const char * module)684 TIFFReadRawStripOrTile2(TIFF* tif, uint32 strip_or_tile, int is_strip,
685                         tmsize_t size, const char* module)
686 {
687         assert( !isMapped(tif) );
688         assert((tif->tif_flags&TIFF_NOREADRAW)==0);
689 
690         if (!SeekOK(tif, TIFFGetStrileOffset(tif, strip_or_tile))) {
691             if( is_strip )
692             {
693                 TIFFErrorExt(tif->tif_clientdata, module,
694                     "Seek error at scanline %lu, strip %lu",
695                     (unsigned long) tif->tif_row,
696                     (unsigned long) strip_or_tile);
697             }
698             else
699             {
700                 TIFFErrorExt(tif->tif_clientdata, module,
701                     "Seek error at row %lu, col %lu, tile %lu",
702                     (unsigned long) tif->tif_row,
703                     (unsigned long) tif->tif_col,
704                     (unsigned long) strip_or_tile);
705             }
706             return ((tmsize_t)(-1));
707         }
708 
709         if( !TIFFReadAndRealloc( tif, size, 0, is_strip,
710                                  strip_or_tile, module ) )
711         {
712             return ((tmsize_t)(-1));
713         }
714 
715         return (size);
716 }
717 
718 /*
719  * Read a strip of data from the file.
720  */
721 tmsize_t
TIFFReadRawStrip(TIFF * tif,uint32 strip,void * buf,tmsize_t size)722 TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
723 {
724 	static const char module[] = "TIFFReadRawStrip";
725 	TIFFDirectory *td = &tif->tif_dir;
726 	uint64 bytecount64;
727 	tmsize_t bytecountm;
728 
729 	if (!TIFFCheckRead(tif, 0))
730 		return ((tmsize_t)(-1));
731 	if (strip >= td->td_nstrips) {
732 		TIFFErrorExt(tif->tif_clientdata, module,
733 		     "%lu: Strip out of range, max %lu",
734 		     (unsigned long) strip,
735 		     (unsigned long) td->td_nstrips);
736 		return ((tmsize_t)(-1));
737 	}
738 	if (tif->tif_flags&TIFF_NOREADRAW)
739 	{
740 		TIFFErrorExt(tif->tif_clientdata, module,
741 		    "Compression scheme does not support access to raw uncompressed data");
742 		return ((tmsize_t)(-1));
743 	}
744 	bytecount64 = TIFFGetStrileByteCount(tif, strip);
745 	if (size != (tmsize_t)(-1) && (uint64)size <= bytecount64)
746 		bytecountm = size;
747 	else
748 		bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
749 	if( bytecountm == 0 ) {
750 		return ((tmsize_t)(-1));
751 	}
752 	return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module));
753 }
754 
755 TIFF_NOSANITIZE_UNSIGNED_INT_OVERFLOW
NoSantizeSubUInt64(uint64 a,uint64 b)756 static uint64 NoSantizeSubUInt64(uint64 a, uint64 b)
757 {
758     return a - b;
759 }
760 
761 /*
762  * Read the specified strip and setup for decoding. The data buffer is
763  * expanded, as necessary, to hold the strip's data.
764  */
765 int
TIFFFillStrip(TIFF * tif,uint32 strip)766 TIFFFillStrip(TIFF* tif, uint32 strip)
767 {
768 	static const char module[] = "TIFFFillStrip";
769 	TIFFDirectory *td = &tif->tif_dir;
770 
771 	if ((tif->tif_flags&TIFF_NOREADRAW)==0)
772 	{
773 		uint64 bytecount = TIFFGetStrileByteCount(tif, strip);
774 		if( bytecount == 0 || bytecount > (uint64)TIFF_INT64_MAX ) {
775 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
776 			TIFFErrorExt(tif->tif_clientdata, module,
777 				"Invalid strip byte count %I64u, strip %lu",
778 				     (unsigned __int64) bytecount,
779 				     (unsigned long) strip);
780 #else
781 			TIFFErrorExt(tif->tif_clientdata, module,
782 				"Invalid strip byte count %llu, strip %lu",
783 				     (unsigned long long) bytecount,
784 				     (unsigned long) strip);
785 #endif
786 			return (0);
787 		}
788 
789 		/* To avoid excessive memory allocations: */
790 		/* Byte count should normally not be larger than a number of */
791 		/* times the uncompressed size plus some margin */
792                 if( bytecount > 1024 * 1024 )
793                 {
794 			/* 10 and 4096 are just values that could be adjusted. */
795 			/* Hopefully they are safe enough for all codecs */
796 			tmsize_t stripsize = TIFFStripSize(tif);
797 			if( stripsize != 0 &&
798 			    (bytecount - 4096) / 10 > (uint64)stripsize  )
799 			{
800 				uint64 newbytecount = (uint64)stripsize * 10 + 4096;
801 				if( newbytecount == 0 || newbytecount > (uint64)TIFF_INT64_MAX )
802 				{
803 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
804 					TIFFWarningExt(tif->tif_clientdata, module,
805 					  "Too large strip byte count %I64u, strip %lu. Limiting to %I64u",
806 					     (unsigned __int64) bytecount,
807 					     (unsigned long) strip,
808 					     (unsigned __int64) newbytecount);
809 #else
810 					TIFFErrorExt(tif->tif_clientdata, module,
811 					  "Too large strip byte count %llu, strip %lu. Limiting to %llu",
812 					     (unsigned long long) bytecount,
813 					     (unsigned long) strip,
814 					     (unsigned long long) newbytecount);
815 #endif
816 					bytecount = newbytecount;
817 				}
818 			}
819 		}
820 
821 		if (isMapped(tif)) {
822 			/*
823 			 * We must check for overflow, potentially causing
824 			 * an OOB read. Instead of simple
825 			 *
826 			 *  TIFFGetStrileOffset(tif, strip)+bytecount > tif->tif_size
827 			 *
828 			 * comparison (which can overflow) we do the following
829 			 * two comparisons:
830 			 */
831 			if (bytecount > (uint64)tif->tif_size ||
832 			    TIFFGetStrileOffset(tif, strip) > (uint64)tif->tif_size - bytecount) {
833 				/*
834 				 * This error message might seem strange, but
835 				 * it's what would happen if a read were done
836 				 * instead.
837 				 */
838 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
839 				TIFFErrorExt(tif->tif_clientdata, module,
840 
841 					"Read error on strip %lu; "
842 					"got %I64u bytes, expected %I64u",
843 					(unsigned long) strip,
844 					(unsigned __int64) NoSantizeSubUInt64(tif->tif_size, TIFFGetStrileOffset(tif, strip)),
845 					(unsigned __int64) bytecount);
846 #else
847 				TIFFErrorExt(tif->tif_clientdata, module,
848 
849 					"Read error on strip %lu; "
850 					"got %llu bytes, expected %llu",
851 					(unsigned long) strip,
852 					(unsigned long long) NoSantizeSubUInt64(tif->tif_size, TIFFGetStrileOffset(tif, strip)),
853 					(unsigned long long) bytecount);
854 #endif
855 				tif->tif_curstrip = NOSTRIP;
856 				return (0);
857 			}
858 		}
859 
860 		if (isMapped(tif) &&
861 		    (isFillOrder(tif, td->td_fillorder)
862 		    || (tif->tif_flags & TIFF_NOBITREV))) {
863 			/*
864 			 * The image is mapped into memory and we either don't
865 			 * need to flip bits or the compression routine is
866 			 * going to handle this operation itself.  In this
867 			 * case, avoid copying the raw data and instead just
868 			 * reference the data from the memory mapped file
869 			 * image.  This assumes that the decompression
870 			 * routines do not modify the contents of the raw data
871 			 * buffer (if they try to, the application will get a
872 			 * fault since the file is mapped read-only).
873 			 */
874 			if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
875 				_TIFFfree(tif->tif_rawdata);
876 				tif->tif_rawdata = NULL;
877 				tif->tif_rawdatasize = 0;
878 			}
879 			tif->tif_flags &= ~TIFF_MYBUFFER;
880 			tif->tif_rawdatasize = (tmsize_t)bytecount;
881 			tif->tif_rawdata = tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, strip);
882                         tif->tif_rawdataoff = 0;
883                         tif->tif_rawdataloaded = (tmsize_t) bytecount;
884 
885 			/*
886 			 * When we have tif_rawdata reference directly into the memory mapped file
887 			 * we need to be pretty careful about how we use the rawdata.  It is not
888 			 * a general purpose working buffer as it normally otherwise is.  So we
889 			 * keep track of this fact to avoid using it improperly.
890 			 */
891 			tif->tif_flags |= TIFF_BUFFERMMAP;
892 		} else {
893 			/*
894 			 * Expand raw data buffer, if needed, to hold data
895 			 * strip coming from file (perhaps should set upper
896 			 * bound on the size of a buffer we'll use?).
897 			 */
898 			tmsize_t bytecountm;
899 			bytecountm=(tmsize_t)bytecount;
900 			if ((uint64)bytecountm!=bytecount)
901 			{
902 				TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
903 				return(0);
904 			}
905 			if (bytecountm > tif->tif_rawdatasize) {
906 				tif->tif_curstrip = NOSTRIP;
907 				if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
908 					TIFFErrorExt(tif->tif_clientdata, module,
909 					    "Data buffer too small to hold strip %lu",
910 					    (unsigned long) strip);
911 					return (0);
912 				}
913 			}
914 			if (tif->tif_flags&TIFF_BUFFERMMAP) {
915 				tif->tif_curstrip = NOSTRIP;
916 				tif->tif_rawdata = NULL;
917 				tif->tif_rawdatasize = 0;
918 				tif->tif_flags &= ~TIFF_BUFFERMMAP;
919 			}
920 
921 			if( isMapped(tif) )
922 			{
923 				if (bytecountm > tif->tif_rawdatasize &&
924 				    !TIFFReadBufferSetup(tif, 0, bytecountm))
925 				{
926 					return (0);
927 				}
928 				if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata,
929 				    bytecountm, module) != bytecountm)
930 				{
931 					return (0);
932 				}
933 			}
934 			else
935 			{
936 				if (TIFFReadRawStripOrTile2(tif, strip, 1,
937 				    bytecountm, module) != bytecountm)
938 				{
939 					return (0);
940 				}
941 			}
942 
943 
944                         tif->tif_rawdataoff = 0;
945                         tif->tif_rawdataloaded = bytecountm;
946 
947 			if (!isFillOrder(tif, td->td_fillorder) &&
948 			    (tif->tif_flags & TIFF_NOBITREV) == 0)
949 				TIFFReverseBits(tif->tif_rawdata, bytecountm);
950                 }
951 	}
952 	return (TIFFStartStrip(tif, strip));
953 }
954 
955 /*
956  * Tile-oriented Read Support
957  * Contributed by Nancy Cam (Silicon Graphics).
958  */
959 
960 /*
961  * Read and decompress a tile of data.  The
962  * tile is selected by the (x,y,z,s) coordinates.
963  */
964 tmsize_t
TIFFReadTile(TIFF * tif,void * buf,uint32 x,uint32 y,uint32 z,uint16 s)965 TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
966 {
967 	if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
968 		return ((tmsize_t)(-1));
969 	return (TIFFReadEncodedTile(tif,
970 	    TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
971 }
972 
973 /*
974  * Read a tile of data and decompress the specified
975  * amount into the user-supplied buffer.
976  */
977 tmsize_t
TIFFReadEncodedTile(TIFF * tif,uint32 tile,void * buf,tmsize_t size)978 TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
979 {
980 	static const char module[] = "TIFFReadEncodedTile";
981 	TIFFDirectory *td = &tif->tif_dir;
982 	tmsize_t tilesize = tif->tif_tilesize;
983 
984 	if (!TIFFCheckRead(tif, 1))
985 		return ((tmsize_t)(-1));
986 	if (tile >= td->td_nstrips) {
987 		TIFFErrorExt(tif->tif_clientdata, module,
988 		    "%lu: Tile out of range, max %lu",
989 		    (unsigned long) tile, (unsigned long) td->td_nstrips);
990 		return ((tmsize_t)(-1));
991 	}
992 
993     /* shortcut to avoid an extra memcpy() */
994     if( td->td_compression == COMPRESSION_NONE &&
995         size!=(tmsize_t)(-1) && size >= tilesize &&
996         !isMapped(tif) &&
997         ((tif->tif_flags&TIFF_NOREADRAW)==0) )
998     {
999         if (TIFFReadRawTile1(tif, tile, buf, tilesize, module) != tilesize)
1000             return ((tmsize_t)(-1));
1001 
1002         if (!isFillOrder(tif, td->td_fillorder) &&
1003             (tif->tif_flags & TIFF_NOBITREV) == 0)
1004             TIFFReverseBits(buf,tilesize);
1005 
1006         (*tif->tif_postdecode)(tif,buf,tilesize);
1007         return (tilesize);
1008     }
1009 
1010 	if (size == (tmsize_t)(-1))
1011 		size = tilesize;
1012 	else if (size > tilesize)
1013 		size = tilesize;
1014 	if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif,
1015 	    (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) {
1016 		(*tif->tif_postdecode)(tif, (uint8*) buf, size);
1017 		return (size);
1018 	} else
1019 		return ((tmsize_t)(-1));
1020 }
1021 
1022 /* Variant of TIFFReadTile() that does
1023  * * if *buf == NULL, *buf = _TIFFmalloc(bufsizetoalloc) only after TIFFFillTile() has
1024  *   succeeded. This avoid excessive memory allocation in case of truncated
1025  *   file.
1026  * * calls regular TIFFReadEncodedTile() if *buf != NULL
1027  */
1028 tmsize_t
_TIFFReadTileAndAllocBuffer(TIFF * tif,void ** buf,tmsize_t bufsizetoalloc,uint32 x,uint32 y,uint32 z,uint16 s)1029 _TIFFReadTileAndAllocBuffer(TIFF* tif,
1030                             void **buf, tmsize_t bufsizetoalloc,
1031                             uint32 x, uint32 y, uint32 z, uint16 s)
1032 {
1033     if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
1034             return ((tmsize_t)(-1));
1035     return (_TIFFReadEncodedTileAndAllocBuffer(tif,
1036                                                TIFFComputeTile(tif, x, y, z, s),
1037                                                buf, bufsizetoalloc,
1038                                                (tmsize_t)(-1)));
1039 }
1040 
1041 /* Variant of TIFFReadEncodedTile() that does
1042  * * if *buf == NULL, *buf = _TIFFmalloc(bufsizetoalloc) only after TIFFFillTile() has
1043  *   succeeded. This avoid excessive memory allocation in case of truncated
1044  *   file.
1045  * * calls regular TIFFReadEncodedTile() if *buf != NULL
1046  */
1047 tmsize_t
_TIFFReadEncodedTileAndAllocBuffer(TIFF * tif,uint32 tile,void ** buf,tmsize_t bufsizetoalloc,tmsize_t size_to_read)1048 _TIFFReadEncodedTileAndAllocBuffer(TIFF* tif, uint32 tile,
1049                                     void **buf, tmsize_t bufsizetoalloc,
1050                                     tmsize_t size_to_read)
1051 {
1052     static const char module[] = "_TIFFReadEncodedTileAndAllocBuffer";
1053     TIFFDirectory *td = &tif->tif_dir;
1054     tmsize_t tilesize = tif->tif_tilesize;
1055 
1056     if( *buf != NULL )
1057     {
1058         return TIFFReadEncodedTile(tif, tile, *buf, size_to_read);
1059     }
1060 
1061     if (!TIFFCheckRead(tif, 1))
1062             return ((tmsize_t)(-1));
1063     if (tile >= td->td_nstrips) {
1064             TIFFErrorExt(tif->tif_clientdata, module,
1065                 "%lu: Tile out of range, max %lu",
1066                 (unsigned long) tile, (unsigned long) td->td_nstrips);
1067             return ((tmsize_t)(-1));
1068     }
1069 
1070     if (!TIFFFillTile(tif,tile))
1071             return((tmsize_t)(-1));
1072 
1073     *buf = _TIFFmalloc(bufsizetoalloc);
1074     if (*buf == NULL) {
1075             TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif),
1076                          "No space for tile buffer");
1077             return((tmsize_t)(-1));
1078     }
1079     _TIFFmemset(*buf, 0, bufsizetoalloc);
1080 
1081     if (size_to_read == (tmsize_t)(-1))
1082         size_to_read = tilesize;
1083     else if (size_to_read > tilesize)
1084         size_to_read = tilesize;
1085     if( (*tif->tif_decodetile)(tif,
1086         (uint8*) *buf, size_to_read, (uint16)(tile/td->td_stripsperimage))) {
1087         (*tif->tif_postdecode)(tif, (uint8*) *buf, size_to_read);
1088         return (size_to_read);
1089     } else
1090         return ((tmsize_t)(-1));
1091 }
1092 
1093 static tmsize_t
TIFFReadRawTile1(TIFF * tif,uint32 tile,void * buf,tmsize_t size,const char * module)1094 TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module)
1095 {
1096 	assert((tif->tif_flags&TIFF_NOREADRAW)==0);
1097 	if (!isMapped(tif)) {
1098 		tmsize_t cc;
1099 
1100 		if (!SeekOK(tif, TIFFGetStrileOffset(tif, tile))) {
1101 			TIFFErrorExt(tif->tif_clientdata, module,
1102 			    "Seek error at row %lu, col %lu, tile %lu",
1103 			    (unsigned long) tif->tif_row,
1104 			    (unsigned long) tif->tif_col,
1105 			    (unsigned long) tile);
1106 			return ((tmsize_t)(-1));
1107 		}
1108 		cc = TIFFReadFile(tif, buf, size);
1109 		if (cc != size) {
1110 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
1111 			TIFFErrorExt(tif->tif_clientdata, module,
1112 	"Read error at row %lu, col %lu; got %I64u bytes, expected %I64u",
1113 				     (unsigned long) tif->tif_row,
1114 				     (unsigned long) tif->tif_col,
1115 				     (unsigned __int64) cc,
1116 				     (unsigned __int64) size);
1117 #else
1118 			TIFFErrorExt(tif->tif_clientdata, module,
1119 	"Read error at row %lu, col %lu; got %llu bytes, expected %llu",
1120 				     (unsigned long) tif->tif_row,
1121 				     (unsigned long) tif->tif_col,
1122 				     (unsigned long long) cc,
1123 				     (unsigned long long) size);
1124 #endif
1125 			return ((tmsize_t)(-1));
1126 		}
1127 	} else {
1128 		tmsize_t ma,mb;
1129 		tmsize_t n;
1130 		ma=(tmsize_t)TIFFGetStrileOffset(tif, tile);
1131 		mb=ma+size;
1132 		if ((TIFFGetStrileOffset(tif, tile) > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size))
1133 			n=0;
1134 		else if ((mb<ma)||(mb<size)||(mb>tif->tif_size))
1135 			n=tif->tif_size-ma;
1136 		else
1137 			n=size;
1138 		if (n!=size) {
1139 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
1140 			TIFFErrorExt(tif->tif_clientdata, module,
1141 "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u",
1142 				     (unsigned long) tif->tif_row,
1143 				     (unsigned long) tif->tif_col,
1144 				     (unsigned long) tile,
1145 				     (unsigned __int64) n,
1146 				     (unsigned __int64) size);
1147 #else
1148 			TIFFErrorExt(tif->tif_clientdata, module,
1149 "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu",
1150 				     (unsigned long) tif->tif_row,
1151 				     (unsigned long) tif->tif_col,
1152 				     (unsigned long) tile,
1153 				     (unsigned long long) n,
1154 				     (unsigned long long) size);
1155 #endif
1156 			return ((tmsize_t)(-1));
1157 		}
1158 		_TIFFmemcpy(buf, tif->tif_base + ma, size);
1159 	}
1160 	return (size);
1161 }
1162 
1163 /*
1164  * Read a tile of data from the file.
1165  */
1166 tmsize_t
TIFFReadRawTile(TIFF * tif,uint32 tile,void * buf,tmsize_t size)1167 TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
1168 {
1169 	static const char module[] = "TIFFReadRawTile";
1170 	TIFFDirectory *td = &tif->tif_dir;
1171 	uint64 bytecount64;
1172 	tmsize_t bytecountm;
1173 
1174 	if (!TIFFCheckRead(tif, 1))
1175 		return ((tmsize_t)(-1));
1176 	if (tile >= td->td_nstrips) {
1177 		TIFFErrorExt(tif->tif_clientdata, module,
1178 		    "%lu: Tile out of range, max %lu",
1179 		    (unsigned long) tile, (unsigned long) td->td_nstrips);
1180 		return ((tmsize_t)(-1));
1181 	}
1182 	if (tif->tif_flags&TIFF_NOREADRAW)
1183 	{
1184 		TIFFErrorExt(tif->tif_clientdata, module,
1185 		"Compression scheme does not support access to raw uncompressed data");
1186 		return ((tmsize_t)(-1));
1187 	}
1188 	bytecount64 = TIFFGetStrileByteCount(tif, tile);
1189 	if (size != (tmsize_t)(-1) && (uint64)size <= bytecount64)
1190 		bytecountm = size;
1191 	else
1192 		bytecountm = _TIFFCastUInt64ToSSize(tif, bytecount64, module);
1193 	if( bytecountm == 0 ) {
1194 		return ((tmsize_t)(-1));
1195 	}
1196 	return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module));
1197 }
1198 
1199 /*
1200  * Read the specified tile and setup for decoding. The data buffer is
1201  * expanded, as necessary, to hold the tile's data.
1202  */
1203 int
TIFFFillTile(TIFF * tif,uint32 tile)1204 TIFFFillTile(TIFF* tif, uint32 tile)
1205 {
1206 	static const char module[] = "TIFFFillTile";
1207 	TIFFDirectory *td = &tif->tif_dir;
1208 
1209 	if ((tif->tif_flags&TIFF_NOREADRAW)==0)
1210 	{
1211 		uint64 bytecount = TIFFGetStrileByteCount(tif, tile);
1212 		if( bytecount == 0 || bytecount > (uint64)TIFF_INT64_MAX ) {
1213 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
1214 			TIFFErrorExt(tif->tif_clientdata, module,
1215 				"%I64u: Invalid tile byte count, tile %lu",
1216 				     (unsigned __int64) bytecount,
1217 				     (unsigned long) tile);
1218 #else
1219 			TIFFErrorExt(tif->tif_clientdata, module,
1220 				"%llu: Invalid tile byte count, tile %lu",
1221 				     (unsigned long long) bytecount,
1222 				     (unsigned long) tile);
1223 #endif
1224 			return (0);
1225 		}
1226 
1227 		/* To avoid excessive memory allocations: */
1228 		/* Byte count should normally not be larger than a number of */
1229 		/* times the uncompressed size plus some margin */
1230                 if( bytecount > 1024 * 1024 )
1231                 {
1232 			/* 10 and 4096 are just values that could be adjusted. */
1233 			/* Hopefully they are safe enough for all codecs */
1234 			tmsize_t stripsize = TIFFTileSize(tif);
1235 			if( stripsize != 0 &&
1236 			    (bytecount - 4096) / 10 > (uint64)stripsize  )
1237 			{
1238 				uint64 newbytecount = (uint64)stripsize * 10 + 4096;
1239 				if( newbytecount == 0 || newbytecount > (uint64)TIFF_INT64_MAX )
1240 				{
1241 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
1242 					TIFFWarningExt(tif->tif_clientdata, module,
1243 					  "Too large tile byte count %I64u, tile %lu. Limiting to %I64u",
1244 					     (unsigned __int64) bytecount,
1245 					     (unsigned long) tile,
1246 					     (unsigned __int64) newbytecount);
1247 #else
1248 					TIFFErrorExt(tif->tif_clientdata, module,
1249 					  "Too large tile byte count %llu, tile %lu. Limiting to %llu",
1250 					     (unsigned long long) bytecount,
1251 					     (unsigned long) tile,
1252 					     (unsigned long long) newbytecount);
1253 #endif
1254 					bytecount = newbytecount;
1255 				}
1256 			}
1257 		}
1258 
1259 		if (isMapped(tif)) {
1260 			/*
1261 			 * We must check for overflow, potentially causing
1262 			 * an OOB read. Instead of simple
1263 			 *
1264 			 *  TIFFGetStrileOffset(tif, tile)+bytecount > tif->tif_size
1265 			 *
1266 			 * comparison (which can overflow) we do the following
1267 			 * two comparisons:
1268 			 */
1269 			if (bytecount > (uint64)tif->tif_size ||
1270 			    TIFFGetStrileOffset(tif, tile) > (uint64)tif->tif_size - bytecount) {
1271 				tif->tif_curtile = NOTILE;
1272 				return (0);
1273 			}
1274 		}
1275 
1276 		if (isMapped(tif) &&
1277 		    (isFillOrder(tif, td->td_fillorder)
1278 		     || (tif->tif_flags & TIFF_NOBITREV))) {
1279 			/*
1280 			 * The image is mapped into memory and we either don't
1281 			 * need to flip bits or the compression routine is
1282 			 * going to handle this operation itself.  In this
1283 			 * case, avoid copying the raw data and instead just
1284 			 * reference the data from the memory mapped file
1285 			 * image.  This assumes that the decompression
1286 			 * routines do not modify the contents of the raw data
1287 			 * buffer (if they try to, the application will get a
1288 			 * fault since the file is mapped read-only).
1289 			 */
1290 			if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
1291 				_TIFFfree(tif->tif_rawdata);
1292 				tif->tif_rawdata = NULL;
1293 				tif->tif_rawdatasize = 0;
1294 			}
1295 			tif->tif_flags &= ~TIFF_MYBUFFER;
1296 
1297 			tif->tif_rawdatasize = (tmsize_t)bytecount;
1298 			tif->tif_rawdata =
1299 				tif->tif_base + (tmsize_t)TIFFGetStrileOffset(tif, tile);
1300                         tif->tif_rawdataoff = 0;
1301                         tif->tif_rawdataloaded = (tmsize_t) bytecount;
1302 			tif->tif_flags |= TIFF_BUFFERMMAP;
1303 		} else {
1304 			/*
1305 			 * Expand raw data buffer, if needed, to hold data
1306 			 * tile coming from file (perhaps should set upper
1307 			 * bound on the size of a buffer we'll use?).
1308 			 */
1309 			tmsize_t bytecountm;
1310 			bytecountm=(tmsize_t)bytecount;
1311 			if ((uint64)bytecountm!=bytecount)
1312 			{
1313 				TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
1314 				return(0);
1315 			}
1316 			if (bytecountm > tif->tif_rawdatasize) {
1317 				tif->tif_curtile = NOTILE;
1318 				if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
1319 					TIFFErrorExt(tif->tif_clientdata, module,
1320 					    "Data buffer too small to hold tile %lu",
1321 					    (unsigned long) tile);
1322 					return (0);
1323 				}
1324 			}
1325 			if (tif->tif_flags&TIFF_BUFFERMMAP) {
1326 				tif->tif_curtile = NOTILE;
1327 				tif->tif_rawdata = NULL;
1328 				tif->tif_rawdatasize = 0;
1329 				tif->tif_flags &= ~TIFF_BUFFERMMAP;
1330 			}
1331 
1332 			if( isMapped(tif) )
1333 			{
1334 				if (bytecountm > tif->tif_rawdatasize &&
1335 				    !TIFFReadBufferSetup(tif, 0, bytecountm))
1336 				{
1337 					return (0);
1338 				}
1339 				if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata,
1340 				    bytecountm, module) != bytecountm)
1341 				{
1342 					return (0);
1343 				}
1344 			}
1345 			else
1346 			{
1347 				if (TIFFReadRawStripOrTile2(tif, tile, 0,
1348 				    bytecountm, module) != bytecountm)
1349 				{
1350 					return (0);
1351 				}
1352 			}
1353 
1354 
1355                         tif->tif_rawdataoff = 0;
1356                         tif->tif_rawdataloaded = bytecountm;
1357 
1358 			if (tif->tif_rawdata != NULL &&
1359                             !isFillOrder(tif, td->td_fillorder) &&
1360 			    (tif->tif_flags & TIFF_NOBITREV) == 0)
1361 				TIFFReverseBits(tif->tif_rawdata,
1362                                                 tif->tif_rawdataloaded);
1363 		}
1364 	}
1365 	return (TIFFStartTile(tif, tile));
1366 }
1367 
1368 /*
1369  * Setup the raw data buffer in preparation for
1370  * reading a strip of raw data.  If the buffer
1371  * is specified as zero, then a buffer of appropriate
1372  * size is allocated by the library.  Otherwise,
1373  * the client must guarantee that the buffer is
1374  * large enough to hold any individual strip of
1375  * raw data.
1376  */
1377 int
TIFFReadBufferSetup(TIFF * tif,void * bp,tmsize_t size)1378 TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size)
1379 {
1380 	static const char module[] = "TIFFReadBufferSetup";
1381 
1382 	assert((tif->tif_flags&TIFF_NOREADRAW)==0);
1383 	tif->tif_flags &= ~TIFF_BUFFERMMAP;
1384 
1385 	if (tif->tif_rawdata) {
1386 		if (tif->tif_flags & TIFF_MYBUFFER)
1387 			_TIFFfree(tif->tif_rawdata);
1388 		tif->tif_rawdata = NULL;
1389 		tif->tif_rawdatasize = 0;
1390 	}
1391 	if (bp) {
1392 		tif->tif_rawdatasize = size;
1393 		tif->tif_rawdata = (uint8*) bp;
1394 		tif->tif_flags &= ~TIFF_MYBUFFER;
1395 	} else {
1396 		tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024);
1397 		if (tif->tif_rawdatasize==0) {
1398 		    TIFFErrorExt(tif->tif_clientdata, module,
1399 				 "Invalid buffer size");
1400 		    return (0);
1401 		}
1402 		/* Initialize to zero to avoid uninitialized buffers in case of */
1403                 /* short reads (http://bugzilla.maptools.org/show_bug.cgi?id=2651) */
1404 		tif->tif_rawdata = (uint8*) _TIFFcalloc(1, tif->tif_rawdatasize);
1405 		tif->tif_flags |= TIFF_MYBUFFER;
1406 	}
1407 	if (tif->tif_rawdata == NULL) {
1408 		TIFFErrorExt(tif->tif_clientdata, module,
1409 		    "No space for data buffer at scanline %lu",
1410 		    (unsigned long) tif->tif_row);
1411 		tif->tif_rawdatasize = 0;
1412 		return (0);
1413 	}
1414 	return (1);
1415 }
1416 
1417 /*
1418  * Set state to appear as if a
1419  * strip has just been read in.
1420  */
1421 static int
TIFFStartStrip(TIFF * tif,uint32 strip)1422 TIFFStartStrip(TIFF* tif, uint32 strip)
1423 {
1424 	TIFFDirectory *td = &tif->tif_dir;
1425 
1426 	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
1427 		if (!(*tif->tif_setupdecode)(tif))
1428 			return (0);
1429 		tif->tif_flags |= TIFF_CODERSETUP;
1430 	}
1431 	tif->tif_curstrip = strip;
1432 	tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
1433         tif->tif_flags &= ~TIFF_BUF4WRITE;
1434 
1435 	if (tif->tif_flags&TIFF_NOREADRAW)
1436 	{
1437 		tif->tif_rawcp = NULL;
1438 		tif->tif_rawcc = 0;
1439 	}
1440 	else
1441 	{
1442 		tif->tif_rawcp = tif->tif_rawdata;
1443 		if( tif->tif_rawdataloaded > 0 )
1444 			tif->tif_rawcc = tif->tif_rawdataloaded;
1445 		else
1446 			tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, strip);
1447 	}
1448 	return ((*tif->tif_predecode)(tif,
1449 			(uint16)(strip / td->td_stripsperimage)));
1450 }
1451 
1452 /*
1453  * Set state to appear as if a
1454  * tile has just been read in.
1455  */
1456 static int
TIFFStartTile(TIFF * tif,uint32 tile)1457 TIFFStartTile(TIFF* tif, uint32 tile)
1458 {
1459         static const char module[] = "TIFFStartTile";
1460 	TIFFDirectory *td = &tif->tif_dir;
1461         uint32 howmany32;
1462 
1463 	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
1464 		if (!(*tif->tif_setupdecode)(tif))
1465 			return (0);
1466 		tif->tif_flags |= TIFF_CODERSETUP;
1467 	}
1468 	tif->tif_curtile = tile;
1469         howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
1470         if (howmany32 == 0) {
1471                  TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
1472                 return 0;
1473         }
1474 	tif->tif_row = (tile % howmany32) * td->td_tilelength;
1475         howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
1476         if (howmany32 == 0) {
1477                 TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
1478                 return 0;
1479         }
1480 	tif->tif_col = (tile % howmany32) * td->td_tilewidth;
1481         tif->tif_flags &= ~TIFF_BUF4WRITE;
1482 	if (tif->tif_flags&TIFF_NOREADRAW)
1483 	{
1484 		tif->tif_rawcp = NULL;
1485 		tif->tif_rawcc = 0;
1486 	}
1487 	else
1488 	{
1489 		tif->tif_rawcp = tif->tif_rawdata;
1490 		if( tif->tif_rawdataloaded > 0 )
1491 			tif->tif_rawcc = tif->tif_rawdataloaded;
1492 		else
1493 			tif->tif_rawcc = (tmsize_t)TIFFGetStrileByteCount(tif, tile);
1494 	}
1495 	return ((*tif->tif_predecode)(tif,
1496 			(uint16)(tile/td->td_stripsperimage)));
1497 }
1498 
1499 static int
TIFFCheckRead(TIFF * tif,int tiles)1500 TIFFCheckRead(TIFF* tif, int tiles)
1501 {
1502 	if (tif->tif_mode == O_WRONLY) {
1503 		TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading");
1504 		return (0);
1505 	}
1506 	if (tiles ^ isTiled(tif)) {
1507 		TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ?
1508 		    "Can not read tiles from a striped image" :
1509 		    "Can not read scanlines from a tiled image");
1510 		return (0);
1511 	}
1512 	return (1);
1513 }
1514 
1515 /* Use the provided input buffer (inbuf, insize) and decompress it into
1516  * (outbuf, outsize).
1517  * This function replaces the use of TIFFReadEncodedStrip()/TIFFReadEncodedTile()
1518  * when the user can provide the buffer for the input data, for example when
1519  * he wants to avoid libtiff to read the strile offset/count values from the
1520  * [Strip|Tile][Offsets/ByteCounts] array.
1521  * inbuf content must be writable (if bit reversal is needed)
1522  * Returns 1 in case of success, 0 otherwise.
1523  */
TIFFReadFromUserBuffer(TIFF * tif,uint32 strile,void * inbuf,tmsize_t insize,void * outbuf,tmsize_t outsize)1524 int      TIFFReadFromUserBuffer(TIFF* tif, uint32 strile,
1525                                 void* inbuf, tmsize_t insize,
1526                                 void* outbuf, tmsize_t outsize)
1527 {
1528     static const char module[] = "TIFFReadFromUserBuffer";
1529     TIFFDirectory *td = &tif->tif_dir;
1530     int ret = 1;
1531     uint32 old_tif_flags = tif->tif_flags;
1532     tmsize_t old_rawdatasize = tif->tif_rawdatasize;
1533     void* old_rawdata = tif->tif_rawdata;
1534 
1535     if (tif->tif_mode == O_WRONLY) {
1536         TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading");
1537         return 0;
1538     }
1539     if (tif->tif_flags&TIFF_NOREADRAW)
1540     {
1541         TIFFErrorExt(tif->tif_clientdata, module,
1542                 "Compression scheme does not support access to raw uncompressed data");
1543         return 0;
1544     }
1545 
1546     tif->tif_flags &= ~TIFF_MYBUFFER;
1547     tif->tif_flags |= TIFF_BUFFERMMAP;
1548     tif->tif_rawdatasize = insize;
1549     tif->tif_rawdata = inbuf;
1550     tif->tif_rawdataoff = 0;
1551     tif->tif_rawdataloaded = insize;
1552 
1553     if (!isFillOrder(tif, td->td_fillorder) &&
1554         (tif->tif_flags & TIFF_NOBITREV) == 0)
1555     {
1556         TIFFReverseBits(inbuf, insize);
1557     }
1558 
1559     if( TIFFIsTiled(tif) )
1560     {
1561         if( !TIFFStartTile(tif, strile) ||
1562             !(*tif->tif_decodetile)(tif, (uint8*) outbuf, outsize,
1563                                     (uint16)(strile/td->td_stripsperimage)) )
1564         {
1565             ret = 0;
1566         }
1567     }
1568     else
1569     {
1570         uint32 rowsperstrip=td->td_rowsperstrip;
1571         uint32 stripsperplane;
1572         if (rowsperstrip>td->td_imagelength)
1573             rowsperstrip=td->td_imagelength;
1574         stripsperplane= TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip);
1575         if( !TIFFStartStrip(tif, strile) ||
1576             !(*tif->tif_decodestrip)(tif, (uint8*) outbuf, outsize,
1577                                      (uint16)(strile/stripsperplane)) )
1578         {
1579             ret = 0;
1580         }
1581     }
1582     if( ret )
1583     {
1584         (*tif->tif_postdecode)(tif, (uint8*) outbuf, outsize);
1585     }
1586 
1587     if (!isFillOrder(tif, td->td_fillorder) &&
1588         (tif->tif_flags & TIFF_NOBITREV) == 0)
1589     {
1590         TIFFReverseBits(inbuf, insize);
1591     }
1592 
1593     tif->tif_flags = old_tif_flags;
1594     tif->tif_rawdatasize = old_rawdatasize;
1595     tif->tif_rawdata = old_rawdata;
1596     tif->tif_rawdataoff = 0;
1597     tif->tif_rawdataloaded = 0;
1598 
1599     return ret;
1600 }
1601 
1602 void
_TIFFNoPostDecode(TIFF * tif,uint8 * buf,tmsize_t cc)1603 _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
1604 {
1605     (void) tif; (void) buf; (void) cc;
1606 }
1607 
1608 void
_TIFFSwab16BitData(TIFF * tif,uint8 * buf,tmsize_t cc)1609 _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1610 {
1611     (void) tif;
1612     assert((cc & 1) == 0);
1613     TIFFSwabArrayOfShort((uint16*) buf, cc/2);
1614 }
1615 
1616 void
_TIFFSwab24BitData(TIFF * tif,uint8 * buf,tmsize_t cc)1617 _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1618 {
1619     (void) tif;
1620     assert((cc % 3) == 0);
1621     TIFFSwabArrayOfTriples((uint8*) buf, cc/3);
1622 }
1623 
1624 void
_TIFFSwab32BitData(TIFF * tif,uint8 * buf,tmsize_t cc)1625 _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1626 {
1627     (void) tif;
1628     assert((cc & 3) == 0);
1629     TIFFSwabArrayOfLong((uint32*) buf, cc/4);
1630 }
1631 
1632 void
_TIFFSwab64BitData(TIFF * tif,uint8 * buf,tmsize_t cc)1633 _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1634 {
1635     (void) tif;
1636     assert((cc & 7) == 0);
1637     TIFFSwabArrayOfDouble((double*) buf, cc/8);
1638 }
1639 
1640 /* vim: set ts=8 sts=8 sw=8 noet: */
1641 /*
1642  * Local Variables:
1643  * mode: c
1644  * c-basic-offset: 8
1645  * fill-column: 78
1646  * End:
1647  */
1648