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