Merge XFA to PDFium master at 4dc95e7 on 10/28/2014
[pdfium.git] / core / src / fxcodec / fx_tiff / tiff_v403 / tif_read.c
1 /* $Id: tif_read.c,v 1.41 2012-07-06 19:22:58 bfriesen Exp $ */
2
3 /*
4  * Copyright (c) 1988-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and 
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  * 
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
18  * 
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
24  * OF THIS SOFTWARE.
25  */
26
27 /*
28  * TIFF Library.
29  * Scanline-oriented Read Support
30  */
31 #if (!defined(_FPDFAPI_MINI_) || defined(_TIFF_DECODER_)) && !defined(_USE_ADDIN_) && !defined _FX_NO_ANSIC_ && !defined(_FX_EMB_NOUSE_DECODER_)
32 #include "tiffiop.h"
33 #include <stdio.h>
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
43 #define NOSTRIP ((uint32)(-1))       /* undefined state */
44 #define NOTILE ((uint32)(-1))         /* undefined state */
45
46 static int
47 TIFFFillStripPartial( TIFF *tif, int strip, tmsize_t read_ahead, int restart )
48 {
49         static const char module[] = "TIFFFillStripPartial";
50         register TIFFDirectory *td = &tif->tif_dir;
51         uint64 unused_data;
52         uint64 read_offset;
53         tmsize_t cc, to_read;
54         /* tmsize_t bytecountm; */
55         
56         if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
57             return 0;
58         
59         /*
60          * Expand raw data buffer, if needed, to hold data
61          * strip coming from file (perhaps should set upper
62          * bound on the size of a buffer we'll use?).
63          */
64
65         /* bytecountm=(tmsize_t) td->td_stripbytecount[strip]; */
66         if (read_ahead*2 > tif->tif_rawdatasize) {
67                 assert( restart );
68                 
69                 tif->tif_curstrip = NOSTRIP;
70                 if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
71                         TIFFErrorExt(tif->tif_clientdata, module,
72                                      "Data buffer too small to hold part of strip %lu",
73                                      (unsigned long) strip);
74                         return (0);
75                 }
76                 if (!TIFFReadBufferSetup(tif, 0, read_ahead*2))
77                         return (0);
78         }
79
80         if( restart )
81         {
82                 tif->tif_rawdataloaded = 0;
83                 tif->tif_rawdataoff = 0;
84         }
85
86         /*
87         ** If we are reading more data, move any unused data to the
88         ** start of the buffer.
89         */
90         if( tif->tif_rawdataloaded > 0 )
91                 unused_data = tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata);
92         else
93                 unused_data = 0;
94         
95         if( unused_data > 0 )
96         {
97                 assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
98                 memmove( tif->tif_rawdata, tif->tif_rawcp, (size_t)unused_data );
99         }
100
101         /*
102         ** Seek to the point in the file where more data should be read.
103         */
104         read_offset = td->td_stripoffset[strip]
105                 + tif->tif_rawdataoff + tif->tif_rawdataloaded;
106
107         if (!SeekOK(tif, read_offset)) {
108                 TIFFErrorExt(tif->tif_clientdata, module,
109                              "Seek error at scanline %lu, strip %lu",
110                              (unsigned long) tif->tif_row, (unsigned long) strip);
111                 return 0;
112         }
113
114         /*
115         ** How much do we want to read?
116         */
117         to_read = (tmsize_t)(tif->tif_rawdatasize - unused_data);
118         if( (uint64) to_read > td->td_stripbytecount[strip] 
119             - tif->tif_rawdataoff - tif->tif_rawdataloaded )
120         {
121                 to_read = (tmsize_t)(td->td_stripbytecount[strip]
122                         - tif->tif_rawdataoff - tif->tif_rawdataloaded);
123         }
124
125         assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
126         cc = TIFFReadFile(tif, tif->tif_rawdata + unused_data, to_read);
127
128         if (cc != to_read) {
129 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
130                 TIFFErrorExt(tif->tif_clientdata, module,
131                              "Read error at scanline %lu; got %I64u bytes, expected %I64u",
132                              (unsigned long) tif->tif_row,
133                              (unsigned __int64) cc,
134                              (unsigned __int64) to_read);
135 #else
136                 TIFFErrorExt(tif->tif_clientdata, module,
137                              "Read error at scanline %lu; got %llu bytes, expected %llu",
138                              (unsigned long) tif->tif_row,
139                              (unsigned long long) cc,
140                              (unsigned long long) to_read);
141 #endif
142                 return 0;
143         }
144         
145         tif->tif_rawdataoff = (tmsize_t)(tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data) ;
146         tif->tif_rawdataloaded = (tmsize_t)unused_data + to_read;
147
148         tif->tif_rawcp = tif->tif_rawdata;
149                         
150         if (!isFillOrder(tif, td->td_fillorder) &&
151             (tif->tif_flags & TIFF_NOBITREV) == 0) {
152                 assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
153                 TIFFReverseBits(tif->tif_rawdata + unused_data, to_read );
154         }
155
156         /*
157         ** When starting a strip from the beginning we need to
158         ** restart the decoder.
159         */
160         if( restart )
161                 return TIFFStartStrip(tif, strip);
162         else
163                 return 1;
164 }
165
166 /*
167  * Seek to a random row+sample in a file.
168  *
169  * Only used by TIFFReadScanline, and is only used on
170  * strip organized files.  We do some tricky stuff to try
171  * and avoid reading the whole compressed raw data for big
172  * strips.
173  */
174 static int
175 TIFFSeek(TIFF* tif, uint32 row, uint16 sample )
176 {
177         register TIFFDirectory *td = &tif->tif_dir;
178         uint32 strip;
179         int    whole_strip;
180         tmsize_t read_ahead = 0;
181
182         /*
183         ** Establish what strip we are working from.
184         */
185         if (row >= td->td_imagelength) {        /* out of range */
186                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
187                     "%lu: Row out of range, max %lu",
188                     (unsigned long) row,
189                     (unsigned long) td->td_imagelength);
190                 return (0);
191         }
192         if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
193                 if (sample >= td->td_samplesperpixel) {
194                         TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
195                             "%lu: Sample out of range, max %lu",
196                             (unsigned long) sample, (unsigned long) td->td_samplesperpixel);
197                         return (0);
198                 }
199                 strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip;
200         } else
201                 strip = row / td->td_rowsperstrip;
202
203         /*
204          * Do we want to treat this strip as one whole chunk or
205          * read it a few lines at a time?
206          */
207 #if defined(CHUNKY_STRIP_READ_SUPPORT)
208         if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
209             return 0;
210         whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10
211                 || isMapped(tif);
212 #else
213         whole_strip = 1;
214 #endif
215         
216         if( !whole_strip )
217         {
218                 read_ahead = tif->tif_scanlinesize * 16 + 5000;
219         }
220
221         /*
222          * If we haven't loaded this strip, do so now, possibly
223          * only reading the first part.
224          */
225         if (strip != tif->tif_curstrip) {       /* different strip, refill */
226                 
227                 if( whole_strip )
228                 {
229                         if (!TIFFFillStrip(tif, strip))
230                                 return (0);
231                 }
232                 else
233                 {
234                         if( !TIFFFillStripPartial(tif,strip,read_ahead,1) )
235                                 return 0;
236                 }
237         }
238
239         /*
240         ** If we already have some data loaded, do we need to read some more?
241         */
242         else if( !whole_strip )
243         {
244                 if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead 
245                     && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] )
246                 {
247                         if( !TIFFFillStripPartial(tif,strip,read_ahead,0) )
248                                 return 0;
249                 }
250         }
251
252         if (row < tif->tif_row) {
253                 /*
254                  * Moving backwards within the same strip: backup
255                  * to the start and then decode forward (below).
256                  *
257                  * NB: If you're planning on lots of random access within a
258                  * strip, it's better to just read and decode the entire
259                  * strip, and then access the decoded data in a random fashion.
260                  */
261
262                 if( tif->tif_rawdataoff != 0 )
263                 {
264                         if( !TIFFFillStripPartial(tif,strip,read_ahead,1) )
265                                 return 0;
266                 }
267                 else
268                 {
269                         if (!TIFFStartStrip(tif, strip))
270                                 return (0);
271                 }
272         }
273         
274         if (row != tif->tif_row) {
275                 /*
276                  * Seek forward to the desired row.
277                  */
278
279                 /* TODO: Will this really work with partial buffers? */
280                 
281                 if (!(*tif->tif_seek)(tif, row - tif->tif_row))
282                         return (0);
283                 tif->tif_row = row;
284         }
285
286         return (1);
287 }
288
289 int
290 TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
291 {
292         int e;
293
294         if (!TIFFCheckRead(tif, 0))
295                 return (-1);
296         if( (e = TIFFSeek(tif, row, sample)) != 0) {
297                 /*
298                  * Decompress desired row into user buffer.
299                  */
300                 e = (*tif->tif_decoderow)
301                     (tif, (uint8*) buf, tif->tif_scanlinesize, sample);  
302
303                 /* we are now poised at the beginning of the next row */
304                 tif->tif_row = row + 1;
305
306                 if (e)
307                         (*tif->tif_postdecode)(tif, (uint8*) buf,
308                             tif->tif_scanlinesize);  
309         }
310         return (e > 0 ? 1 : -1);
311 }
312
313 /*
314  * Read a strip of data and decompress the specified
315  * amount into the user-supplied buffer.
316  */
317 tmsize_t
318 TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
319 {
320         static const char module[] = "TIFFReadEncodedStrip";
321         TIFFDirectory *td = &tif->tif_dir;
322         uint32 rowsperstrip;
323         uint32 stripsperplane;
324         uint32 stripinplane;
325         uint16 plane, comp;
326         uint32 rows;
327         tmsize_t stripsize;
328         if (!TIFFCheckRead(tif,0))
329                 return((tmsize_t)(-1));
330         if (strip>=td->td_nstrips)
331         {
332                 TIFFErrorExt(tif->tif_clientdata,module,
333                     "%lu: Strip out of range, max %lu",(unsigned long)strip,
334                     (unsigned long)td->td_nstrips);
335                 return((tmsize_t)(-1));
336         }
337         /*
338          * Calculate the strip size according to the number of
339          * rows in the strip (check for truncated last strip on any
340          * of the separations).
341          */
342         rowsperstrip=td->td_rowsperstrip;
343         if (rowsperstrip>td->td_imagelength)
344                 rowsperstrip=td->td_imagelength;
345         stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip);
346         stripinplane=(strip%stripsperplane);
347         plane=(strip/stripsperplane);
348         rows=td->td_imagelength-stripinplane*rowsperstrip;
349         if (rows>rowsperstrip)
350                 rows=rowsperstrip;
351         stripsize=TIFFVStripSize(tif,rows);
352         if (stripsize==0)
353                 return((tmsize_t)(-1));
354         if ((size!=(tmsize_t)(-1))&&(size<stripsize))
355                 stripsize=size;
356
357         /*
358          * discard those.
359          * keep code modified by Changjin Gao.
360          * Xiaochuan Liu 20100828.
361          */
362         /*if (!TIFFFillStrip(tif,strip))
363                 return((tmsize_t)(-1));
364         if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
365                 return((tmsize_t)(-1));
366         (*tif->tif_postdecode)(tif,buf,stripsize);
367         return(stripsize);*/
368         
369         /*
370         * Changjin Gao 20110726 fixed decode error issue.
371         * Test file: mantis #27308 020511-1158450.tiff.
372         */
373         comp = COMPRESSION_NONE;
374 StripDecode:
375         if (TIFFFillStrip(tif, strip) && (*tif->tif_decodestrip)(tif, buf, stripsize, plane) > 0)
376         {
377                 (*tif->tif_postdecode)(tif, buf, stripsize);
378                 return (stripsize);
379         }
380         else
381         {
382                 if (comp < 9)
383                 {
384                         TIFFSetField(tif, TIFFTAG_COMPRESSION, comp);
385                         TIFFSetField(tif, TIFFTAG_FAXMODE,FAXMODE_CLASSIC);
386                         comp++;
387                         goto StripDecode;
388                 }
389
390                 return ((tsize_t) -1);
391         }
392 }
393
394 static tmsize_t
395 TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,
396     const char* module)
397 {
398         TIFFDirectory *td = &tif->tif_dir;
399
400     if (!_TIFFFillStriles( tif ))
401         return ((tmsize_t)(-1));
402         
403         assert((tif->tif_flags&TIFF_NOREADRAW)==0);
404         if (!isMapped(tif)) {
405                 tmsize_t cc;
406
407                 if (!SeekOK(tif, td->td_stripoffset[strip])) {
408                         TIFFErrorExt(tif->tif_clientdata, module,
409                             "Seek error at scanline %lu, strip %lu",
410                             (unsigned long) tif->tif_row, (unsigned long) strip);
411                         return ((tmsize_t)(-1));
412                 }
413                 cc = TIFFReadFile(tif, buf, size);
414                 if (cc != size) {
415 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
416                         TIFFErrorExt(tif->tif_clientdata, module,
417                 "Read error at scanline %lu; got %I64u bytes, expected %I64u",
418                                      (unsigned long) tif->tif_row,
419                                      (unsigned __int64) cc,
420                                      (unsigned __int64) size);
421 #else
422                         TIFFErrorExt(tif->tif_clientdata, module,
423                 "Read error at scanline %lu; got %llu bytes, expected %llu",
424                                      (unsigned long) tif->tif_row,
425                                      (unsigned long long) cc,
426                                      (unsigned long long) size);
427 #endif
428                         return ((tmsize_t)(-1));
429                 }
430         } else {
431                 tmsize_t ma,mb;
432                 tmsize_t n;
433                 ma=(tmsize_t)td->td_stripoffset[strip];
434                 mb=ma+size;
435                 if (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size))
436                         n=0;
437                 else if ((mb<ma)||(mb<size)||(mb>tif->tif_size))
438                         n=tif->tif_size-ma;
439                 else
440                         n=size;
441                 if (n!=size) {
442 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
443                         TIFFErrorExt(tif->tif_clientdata, module,
444         "Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u",
445                                      (unsigned long) tif->tif_row,
446                                      (unsigned long) strip,
447                                      (unsigned __int64) n,
448                                      (unsigned __int64) size);
449 #else
450                         TIFFErrorExt(tif->tif_clientdata, module,
451         "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu",
452                                      (unsigned long) tif->tif_row,
453                                      (unsigned long) strip,
454                                      (unsigned long long) n,
455                                      (unsigned long long) size);
456 #endif
457                         return ((tmsize_t)(-1));
458                 }
459                 _TIFFmemcpy(buf, tif->tif_base + ma,
460                             size);
461         }
462         return (size);
463 }
464
465 /*
466  * Read a strip of data from the file.
467  */
468 tmsize_t
469 TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
470 {
471         static const char module[] = "TIFFReadRawStrip";
472         TIFFDirectory *td = &tif->tif_dir;
473         uint64 bytecount;
474         tmsize_t bytecountm;
475
476         if (!TIFFCheckRead(tif, 0))
477                 return ((tmsize_t)(-1));
478         if (strip >= td->td_nstrips) {
479                 TIFFErrorExt(tif->tif_clientdata, module,
480                      "%lu: Strip out of range, max %lu",
481                      (unsigned long) strip,
482                      (unsigned long) td->td_nstrips);
483                 return ((tmsize_t)(-1));
484         }
485         if (tif->tif_flags&TIFF_NOREADRAW)
486         {
487                 TIFFErrorExt(tif->tif_clientdata, module,
488                     "Compression scheme does not support access to raw uncompressed data");
489                 return ((tmsize_t)(-1));
490         }
491         bytecount = td->td_stripbytecount[strip];
492         if (bytecount <= 0) {
493 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
494                 TIFFErrorExt(tif->tif_clientdata, module,
495                              "%I64u: Invalid strip byte count, strip %lu",
496                              (unsigned __int64) bytecount,
497                              (unsigned long) strip);
498 #else
499                 TIFFErrorExt(tif->tif_clientdata, module,
500                              "%llu: Invalid strip byte count, strip %lu",
501                              (unsigned long long) bytecount,
502                              (unsigned long) strip);
503 #endif
504                 return ((tmsize_t)(-1));
505         }
506         bytecountm = (tmsize_t)bytecount;
507         if ((uint64)bytecountm!=bytecount) {
508                 TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow");
509                 return ((tmsize_t)(-1));
510         }
511         if (size != (tmsize_t)(-1) && size < bytecountm)
512                 bytecountm = size;
513         return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module));
514 }
515
516 /*
517  * Read the specified strip and setup for decoding. The data buffer is
518  * expanded, as necessary, to hold the strip's data.
519  */
520 int
521 TIFFFillStrip(TIFF* tif, uint32 strip)
522 {
523         static const char module[] = "TIFFFillStrip";
524         TIFFDirectory *td = &tif->tif_dir;
525
526     if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
527         return 0;
528         
529         if ((tif->tif_flags&TIFF_NOREADRAW)==0)
530         {
531                 uint64 bytecount = td->td_stripbytecount[strip];
532                 if (bytecount <= 0) {
533 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
534                         TIFFErrorExt(tif->tif_clientdata, module,
535                                 "Invalid strip byte count %I64u, strip %lu",
536                                      (unsigned __int64) bytecount,
537                                      (unsigned long) strip);
538 #else
539                         TIFFErrorExt(tif->tif_clientdata, module,
540                                 "Invalid strip byte count %llu, strip %lu",
541                                      (unsigned long long) bytecount,
542                                      (unsigned long) strip);
543 #endif
544                         return (0);
545                 }
546                 if (isMapped(tif) &&
547                     (isFillOrder(tif, td->td_fillorder)
548                     || (tif->tif_flags & TIFF_NOBITREV))) {
549                         /*
550                          * The image is mapped into memory and we either don't
551                          * need to flip bits or the compression routine is
552                          * going to handle this operation itself.  In this
553                          * case, avoid copying the raw data and instead just
554                          * reference the data from the memory mapped file
555                          * image.  This assumes that the decompression
556                          * routines do not modify the contents of the raw data
557                          * buffer (if they try to, the application will get a
558                          * fault since the file is mapped read-only).
559                          */
560                         if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
561                                 _TIFFfree(tif->tif_rawdata);
562                                 tif->tif_rawdata = NULL;
563                                 tif->tif_rawdatasize = 0;
564                         }
565                         tif->tif_flags &= ~TIFF_MYBUFFER;
566                         /*
567                          * We must check for overflow, potentially causing
568                          * an OOB read. Instead of simple
569                          *
570                          *  td->td_stripoffset[strip]+bytecount > tif->tif_size
571                          *
572                          * comparison (which can overflow) we do the following
573                          * two comparisons:
574                          */
575                         if (bytecount > (uint64)tif->tif_size ||
576                             td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) {
577                                 /*
578                                  * This error message might seem strange, but
579                                  * it's what would happen if a read were done
580                                  * instead.
581                                  */
582 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
583                                 TIFFErrorExt(tif->tif_clientdata, module,
584
585                                         "Read error on strip %lu; "
586                                         "got %I64u bytes, expected %I64u",
587                                         (unsigned long) strip,
588                                         (unsigned __int64) tif->tif_size - td->td_stripoffset[strip],
589                                         (unsigned __int64) bytecount);
590 #else
591                                 TIFFErrorExt(tif->tif_clientdata, module,
592
593                                         "Read error on strip %lu; "
594                                         "got %llu bytes, expected %llu",
595                                         (unsigned long) strip,
596                                         (unsigned long long) tif->tif_size - td->td_stripoffset[strip],
597                                         (unsigned long long) bytecount);
598 #endif
599                                 tif->tif_curstrip = NOSTRIP;
600                                 return (0);
601                         }
602                         tif->tif_rawdatasize = (tmsize_t)bytecount;
603                         tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip];
604                         tif->tif_rawdataoff = 0;
605                         tif->tif_rawdataloaded = (tmsize_t) bytecount;
606
607                         /* 
608                          * When we have tif_rawdata reference directly into the memory mapped file
609                          * we need to be pretty careful about how we use the rawdata.  It is not
610                          * a general purpose working buffer as it normally otherwise is.  So we
611                          * keep track of this fact to avoid using it improperly.
612                          */
613                         tif->tif_flags |= TIFF_BUFFERMMAP;
614                 } else {
615                         /*
616                          * Expand raw data buffer, if needed, to hold data
617                          * strip coming from file (perhaps should set upper
618                          * bound on the size of a buffer we'll use?).
619                          */
620                         tmsize_t bytecountm;
621                         bytecountm=(tmsize_t)bytecount;
622                         if ((uint64)bytecountm!=bytecount)
623                         {
624                                 TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
625                                 return(0);
626                         }
627                         if (bytecountm > tif->tif_rawdatasize) {
628                                 tif->tif_curstrip = NOSTRIP;
629                                 if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
630                                         TIFFErrorExt(tif->tif_clientdata, module,
631                                             "Data buffer too small to hold strip %lu",
632                                             (unsigned long) strip);
633                                         return (0);
634                                 }
635                                 if (!TIFFReadBufferSetup(tif, 0, bytecountm))
636                                         return (0);
637                         }
638                         if (tif->tif_flags&TIFF_BUFFERMMAP) {
639                                 tif->tif_curstrip = NOSTRIP;
640                                 if (!TIFFReadBufferSetup(tif, 0, bytecountm))
641                                         return (0);
642                         }
643                         if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata,
644                                 bytecountm, module) != bytecountm)
645                                 return (0);
646
647                         tif->tif_rawdataoff = 0;
648                         tif->tif_rawdataloaded = bytecountm;
649                         
650                         if (!isFillOrder(tif, td->td_fillorder) &&
651                             (tif->tif_flags & TIFF_NOBITREV) == 0)
652                                 TIFFReverseBits(tif->tif_rawdata, bytecountm);
653                 }
654         }
655         return (TIFFStartStrip(tif, strip));
656 }
657
658 /*
659  * Tile-oriented Read Support
660  * Contributed by Nancy Cam (Silicon Graphics).
661  */
662
663 /*
664  * Read and decompress a tile of data.  The
665  * tile is selected by the (x,y,z,s) coordinates.
666  */
667 tmsize_t
668 TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
669 {
670         if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
671                 return ((tmsize_t)(-1));
672         return (TIFFReadEncodedTile(tif,
673             TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
674 }
675
676 /*
677  * Read a tile of data and decompress the specified
678  * amount into the user-supplied buffer.
679  */
680 tmsize_t
681 TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
682 {
683         static const char module[] = "TIFFReadEncodedTile";
684         TIFFDirectory *td = &tif->tif_dir;
685         tmsize_t tilesize = tif->tif_tilesize;
686
687         if (!TIFFCheckRead(tif, 1))
688                 return ((tmsize_t)(-1));
689         if (tile >= td->td_nstrips) {
690                 TIFFErrorExt(tif->tif_clientdata, module,
691                     "%lu: Tile out of range, max %lu",
692                     (unsigned long) tile, (unsigned long) td->td_nstrips);
693                 return ((tmsize_t)(-1));
694         }
695         if (size == (tmsize_t)(-1))
696                 size = tilesize;
697         else if (size > tilesize)
698                 size = tilesize;
699         if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif,
700             (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) {
701                 (*tif->tif_postdecode)(tif, (uint8*) buf, size);
702                 return (size);
703         } else
704                 return ((tmsize_t)(-1));
705 }
706
707 static tmsize_t
708 TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module)
709 {
710         TIFFDirectory *td = &tif->tif_dir;
711
712     if (!_TIFFFillStriles( tif ))
713         return ((tmsize_t)(-1));
714
715         assert((tif->tif_flags&TIFF_NOREADRAW)==0);
716         if (!isMapped(tif)) {
717                 tmsize_t cc;
718
719                 if (!SeekOK(tif, td->td_stripoffset[tile])) {
720                         TIFFErrorExt(tif->tif_clientdata, module,
721                             "Seek error at row %lu, col %lu, tile %lu",
722                             (unsigned long) tif->tif_row,
723                             (unsigned long) tif->tif_col,
724                             (unsigned long) tile);
725                         return ((tmsize_t)(-1));
726                 }
727                 cc = TIFFReadFile(tif, buf, size);
728                 if (cc != size) {
729 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
730                         TIFFErrorExt(tif->tif_clientdata, module,
731         "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u",
732                                      (unsigned long) tif->tif_row,
733                                      (unsigned long) tif->tif_col,
734                                      (unsigned __int64) cc,
735                                      (unsigned __int64) size);
736 #else
737                         TIFFErrorExt(tif->tif_clientdata, module,
738         "Read error at row %lu, col %lu; got %llu bytes, expected %llu",
739                                      (unsigned long) tif->tif_row,
740                                      (unsigned long) tif->tif_col,
741                                      (unsigned long long) cc,
742                                      (unsigned long long) size);
743 #endif
744                         return ((tmsize_t)(-1));
745                 }
746         } else {
747                 tmsize_t ma,mb;
748                 tmsize_t n;
749                 ma=(tmsize_t)td->td_stripoffset[tile];
750                 mb=ma+size;
751                 if (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size))
752                         n=0;
753                 else if ((mb<ma)||(mb<size)||(mb>tif->tif_size))
754                         n=tif->tif_size-ma;
755                 else
756                         n=size;
757                 if (n!=size) {
758 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
759                         TIFFErrorExt(tif->tif_clientdata, module,
760 "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u",
761                                      (unsigned long) tif->tif_row,
762                                      (unsigned long) tif->tif_col,
763                                      (unsigned long) tile,
764                                      (unsigned __int64) n,
765                                      (unsigned __int64) size);
766 #else
767                         TIFFErrorExt(tif->tif_clientdata, module,
768 "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu",
769                                      (unsigned long) tif->tif_row,
770                                      (unsigned long) tif->tif_col,
771                                      (unsigned long) tile,
772                                      (unsigned long long) n,
773                                      (unsigned long long) size);
774 #endif
775                         return ((tmsize_t)(-1));
776                 }
777                 _TIFFmemcpy(buf, tif->tif_base + ma, size);
778         }
779         return (size);
780 }
781
782 /*
783  * Read a tile of data from the file.
784  */
785 tmsize_t
786 TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
787 {
788         static const char module[] = "TIFFReadRawTile";
789         TIFFDirectory *td = &tif->tif_dir;
790         uint64 bytecount64;
791         tmsize_t bytecountm;
792
793         if (!TIFFCheckRead(tif, 1))
794                 return ((tmsize_t)(-1));
795         if (tile >= td->td_nstrips) {
796                 TIFFErrorExt(tif->tif_clientdata, module,
797                     "%lu: Tile out of range, max %lu",
798                     (unsigned long) tile, (unsigned long) td->td_nstrips);
799                 return ((tmsize_t)(-1));
800         }
801         if (tif->tif_flags&TIFF_NOREADRAW)
802         {
803                 TIFFErrorExt(tif->tif_clientdata, module,
804                 "Compression scheme does not support access to raw uncompressed data");
805                 return ((tmsize_t)(-1));
806         }
807         bytecount64 = td->td_stripbytecount[tile];
808         if (size != (tmsize_t)(-1) && (uint64)size < bytecount64)
809                 bytecount64 = (uint64)size;
810         bytecountm = (tmsize_t)bytecount64;
811         if ((uint64)bytecountm!=bytecount64)
812         {
813                 TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
814                 return ((tmsize_t)(-1));
815         }
816         return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module));
817 }
818
819 /*
820  * Read the specified tile and setup for decoding. The data buffer is
821  * expanded, as necessary, to hold the tile's data.
822  */
823 int
824 TIFFFillTile(TIFF* tif, uint32 tile)
825 {
826         static const char module[] = "TIFFFillTile";
827         TIFFDirectory *td = &tif->tif_dir;
828
829     if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
830         return 0;
831         
832         if ((tif->tif_flags&TIFF_NOREADRAW)==0)
833         {
834                 uint64 bytecount = td->td_stripbytecount[tile];
835                 if (bytecount <= 0) {
836 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
837                         TIFFErrorExt(tif->tif_clientdata, module,
838                                 "%I64u: Invalid tile byte count, tile %lu",
839                                      (unsigned __int64) bytecount,
840                                      (unsigned long) tile);
841 #else
842                         TIFFErrorExt(tif->tif_clientdata, module,
843                                 "%llu: Invalid tile byte count, tile %lu",
844                                      (unsigned long long) bytecount,
845                                      (unsigned long) tile);
846 #endif
847                         return (0);
848                 }
849                 if (isMapped(tif) &&
850                     (isFillOrder(tif, td->td_fillorder)
851                      || (tif->tif_flags & TIFF_NOBITREV))) {
852                         /*
853                          * The image is mapped into memory and we either don't
854                          * need to flip bits or the compression routine is
855                          * going to handle this operation itself.  In this
856                          * case, avoid copying the raw data and instead just
857                          * reference the data from the memory mapped file
858                          * image.  This assumes that the decompression
859                          * routines do not modify the contents of the raw data
860                          * buffer (if they try to, the application will get a
861                          * fault since the file is mapped read-only).
862                          */
863                         if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
864                                 _TIFFfree(tif->tif_rawdata);
865                                 tif->tif_rawdata = NULL;
866                                 tif->tif_rawdatasize = 0;
867                         }
868                         tif->tif_flags &= ~TIFF_MYBUFFER;
869                         /*
870                          * We must check for overflow, potentially causing
871                          * an OOB read. Instead of simple
872                          *
873                          *  td->td_stripoffset[tile]+bytecount > tif->tif_size
874                          *
875                          * comparison (which can overflow) we do the following
876                          * two comparisons:
877                          */
878                         if (bytecount > (uint64)tif->tif_size ||
879                             td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) {
880                                 tif->tif_curtile = NOTILE;
881                                 return (0);
882                         }
883                         tif->tif_rawdatasize = (tmsize_t)bytecount;
884                         tif->tif_rawdata =
885                                 tif->tif_base + (tmsize_t)td->td_stripoffset[tile];
886                         tif->tif_rawdataoff = 0;
887                         tif->tif_rawdataloaded = (tmsize_t) bytecount;
888                         tif->tif_flags |= TIFF_BUFFERMMAP;
889                 } else {
890                         /*
891                          * Expand raw data buffer, if needed, to hold data
892                          * tile coming from file (perhaps should set upper
893                          * bound on the size of a buffer we'll use?).
894                          */
895                         tmsize_t bytecountm;
896                         bytecountm=(tmsize_t)bytecount;
897                         if ((uint64)bytecountm!=bytecount)
898                         {
899                                 TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
900                                 return(0);
901                         }
902                         if (bytecountm > tif->tif_rawdatasize) {
903                                 tif->tif_curtile = NOTILE;
904                                 if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
905                                         TIFFErrorExt(tif->tif_clientdata, module,
906                                             "Data buffer too small to hold tile %lu",
907                                             (unsigned long) tile);
908                                         return (0);
909                                 }
910                                 if (!TIFFReadBufferSetup(tif, 0, bytecountm))
911                                         return (0);
912                         }
913                         if (tif->tif_flags&TIFF_BUFFERMMAP) {
914                                 tif->tif_curtile = NOTILE;
915                                 if (!TIFFReadBufferSetup(tif, 0, bytecountm))
916                                         return (0);
917                         }
918
919                         if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata,
920                             bytecountm, module) != bytecountm)
921                                 return (0);
922
923                         tif->tif_rawdataoff = 0;
924                         tif->tif_rawdataloaded = bytecountm;
925                         
926                         if (!isFillOrder(tif, td->td_fillorder) &&
927                             (tif->tif_flags & TIFF_NOBITREV) == 0)
928                                 TIFFReverseBits(tif->tif_rawdata,
929                                                 tif->tif_rawdataloaded);
930                 }
931         }
932         return (TIFFStartTile(tif, tile));
933 }
934
935 /*
936  * Setup the raw data buffer in preparation for
937  * reading a strip of raw data.  If the buffer
938  * is specified as zero, then a buffer of appropriate
939  * size is allocated by the library.  Otherwise,
940  * the client must guarantee that the buffer is
941  * large enough to hold any individual strip of
942  * raw data.
943  */
944 int
945 TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size)
946 {
947         static const char module[] = "TIFFReadBufferSetup";
948
949         assert((tif->tif_flags&TIFF_NOREADRAW)==0);
950         tif->tif_flags &= ~TIFF_BUFFERMMAP;
951
952         if (tif->tif_rawdata) {
953                 if (tif->tif_flags & TIFF_MYBUFFER)
954                         _TIFFfree(tif->tif_rawdata);
955                 tif->tif_rawdata = NULL;
956                 tif->tif_rawdatasize = 0;
957         }
958         if (bp) {
959                 tif->tif_rawdatasize = size;
960                 tif->tif_rawdata = (uint8*) bp;
961                 tif->tif_flags &= ~TIFF_MYBUFFER;
962         } else {
963                 tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024);
964                 if (tif->tif_rawdatasize==0)
965                         tif->tif_rawdatasize=(tmsize_t)(-1);
966                 tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize);
967                 tif->tif_flags |= TIFF_MYBUFFER;
968         }
969         if (tif->tif_rawdata == NULL) {
970                 TIFFErrorExt(tif->tif_clientdata, module,
971                     "No space for data buffer at scanline %lu",
972                     (unsigned long) tif->tif_row);
973                 tif->tif_rawdatasize = 0;
974                 return (0);
975         }
976         return (1);
977 }
978
979 /*
980  * Set state to appear as if a
981  * strip has just been read in.
982  */
983 static int
984 TIFFStartStrip(TIFF* tif, uint32 strip)
985 {
986         TIFFDirectory *td = &tif->tif_dir;
987
988     if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
989         return 0;
990
991         if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
992                 if (!(*tif->tif_setupdecode)(tif))
993                         return (0);
994                 tif->tif_flags |= TIFF_CODERSETUP;
995         }
996         tif->tif_curstrip = strip;
997         tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
998         tif->tif_flags &= ~TIFF_BUF4WRITE;
999
1000         if (tif->tif_flags&TIFF_NOREADRAW)
1001         {
1002                 tif->tif_rawcp = NULL;
1003                 tif->tif_rawcc = 0;  
1004         }
1005         else
1006         {
1007                 tif->tif_rawcp = tif->tif_rawdata;
1008                 tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip];
1009         }
1010         return ((*tif->tif_predecode)(tif,
1011                         (uint16)(strip / td->td_stripsperimage)));
1012 }
1013
1014 /*
1015  * Set state to appear as if a
1016  * tile has just been read in.
1017  */
1018 static int
1019 TIFFStartTile(TIFF* tif, uint32 tile)
1020 {
1021         TIFFDirectory *td = &tif->tif_dir;
1022
1023     if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
1024         return 0;
1025
1026         if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
1027                 if (!(*tif->tif_setupdecode)(tif))
1028                         return (0);
1029                 tif->tif_flags |= TIFF_CODERSETUP;
1030         }
1031         tif->tif_curtile = tile;
1032         tif->tif_row =
1033             (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth)) *
1034                 td->td_tilelength;
1035         tif->tif_col =
1036             (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength)) *
1037                 td->td_tilewidth;
1038         tif->tif_flags &= ~TIFF_BUF4WRITE;
1039         if (tif->tif_flags&TIFF_NOREADRAW)
1040         {
1041                 tif->tif_rawcp = NULL;
1042                 tif->tif_rawcc = 0;
1043         }
1044         else
1045         {
1046                 tif->tif_rawcp = tif->tif_rawdata;
1047                 tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile];
1048         }
1049         return ((*tif->tif_predecode)(tif,
1050                         (uint16)(tile/td->td_stripsperimage)));
1051 }
1052
1053 static int
1054 TIFFCheckRead(TIFF* tif, int tiles)
1055 {
1056         if (tif->tif_mode == O_WRONLY) {
1057                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading");
1058                 return (0);
1059         }
1060         if (tiles ^ isTiled(tif)) {
1061                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ?
1062                     "Can not read tiles from a stripped image" :
1063                     "Can not read scanlines from a tiled image");
1064                 return (0);
1065         }
1066         return (1);
1067 }
1068
1069 void
1070 _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
1071 {
1072     (void) tif; (void) buf; (void) cc;
1073 }
1074
1075 void
1076 _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1077 {
1078     (void) tif;
1079     assert((cc & 1) == 0);
1080     TIFFSwabArrayOfShort((uint16*) buf, cc/2);
1081 }
1082
1083 void
1084 _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1085 {
1086     (void) tif;
1087     assert((cc % 3) == 0);
1088     TIFFSwabArrayOfTriples((uint8*) buf, cc/3);
1089 }
1090
1091 void
1092 _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1093 {
1094     (void) tif;
1095     assert((cc & 3) == 0);
1096     TIFFSwabArrayOfLong((uint32*) buf, cc/4);
1097 }
1098
1099 void
1100 _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1101 {
1102     (void) tif;
1103     assert((cc & 7) == 0);
1104     TIFFSwabArrayOfDouble((double*) buf, cc/8);
1105 }
1106
1107 /* vim: set ts=8 sts=8 sw=8 noet: */
1108 /*
1109  * Local Variables:
1110  * mode: c
1111  * c-basic-offset: 8
1112  * fill-column: 78
1113  * End:
1114  */
1115 #endif
1116