tif_read.c 36.3 KB
Newer Older
1
/* $Id: tif_read.c,v 1.40 2012-06-01 00:55:09 fwarmerdam Exp $ */
2 3 4 5 6

/*
 * Copyright (c) 1988-1997 Sam Leffler
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
 *
7
 * Permission to use, copy, modify, distribute, and sell this software and
8 9 10 11 12 13
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names of
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
 * publicity relating to the software without the specific, prior written
 * permission of Sam Leffler and Silicon Graphics.
14 15 16 17 18
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
19 20 21
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 23
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 25 26 27 28 29 30 31 32 33
 * OF THIS SOFTWARE.
 */

/*
 * TIFF Library.
 * Scanline-oriented Read Support
 */
#include "tiffiop.h"
#include <stdio.h>

34 35 36 37 38 39 40
int TIFFFillStrip(TIFF* tif, uint32 strip);
int TIFFFillTile(TIFF* tif, uint32 tile);
static int TIFFStartStrip(TIFF* tif, uint32 strip);
static int TIFFStartTile(TIFF* tif, uint32 tile);
static int TIFFCheckRead(TIFF*, int);
static tmsize_t
TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,const char* module);
41

42 43 44 45 46 47
#define NOSTRIP ((uint32)(-1))       /* undefined state */
#define NOTILE ((uint32)(-1))         /* undefined state */

static int
TIFFFillStripPartial( TIFF *tif, int strip, tmsize_t read_ahead, int restart )
{
48 49
    static const char module[] = "TIFFFillStripPartial";
    register TIFFDirectory *td = &tif->tif_dir;
50 51 52 53
        uint64 unused_data;
        uint64 read_offset;
        tmsize_t cc, to_read;
        tmsize_t bytecountm;
54

55 56
        if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
            return 0;
57

58 59 60 61 62 63 64 65 66
        /*
         * Expand raw data buffer, if needed, to hold data
         * strip coming from file (perhaps should set upper
         * bound on the size of a buffer we'll use?).
         */

        bytecountm=(tmsize_t) td->td_stripbytecount[strip];
        if (read_ahead*2 > tif->tif_rawdatasize) {
                assert( restart );
67

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                tif->tif_curstrip = NOSTRIP;
                if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
                        TIFFErrorExt(tif->tif_clientdata, module,
                                     "Data buffer too small to hold part of strip %lu",
                                     (unsigned long) strip);
                        return (0);
                }
                if (!TIFFReadBufferSetup(tif, 0, read_ahead*2))
                        return (0);
        }

        if( restart )
        {
                tif->tif_rawdataloaded = 0;
                tif->tif_rawdataoff = 0;
        }

        /*
        ** If we are reading more data, move any unused data to the
        ** start of the buffer.
        */
        if( tif->tif_rawdataloaded > 0 )
                unused_data = tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata);
        else
                unused_data = 0;
93

94 95
        if( unused_data > 0 )
        {
96
        assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                memmove( tif->tif_rawdata, tif->tif_rawcp, unused_data );
        }

        /*
        ** Seek to the point in the file where more data should be read.
        */
        read_offset = td->td_stripoffset[strip]
                + tif->tif_rawdataoff + tif->tif_rawdataloaded;

        if (!SeekOK(tif, read_offset)) {
                TIFFErrorExt(tif->tif_clientdata, module,
                             "Seek error at scanline %lu, strip %lu",
                             (unsigned long) tif->tif_row, (unsigned long) strip);
                return 0;
        }

        /*
        ** How much do we want to read?
        */
        to_read = tif->tif_rawdatasize - unused_data;
117
        if( (uint64) to_read > td->td_stripbytecount[strip]
118 119 120 121 122 123
            - tif->tif_rawdataoff - tif->tif_rawdataloaded )
        {
                to_read = td->td_stripbytecount[strip]
                        - tif->tif_rawdataoff - tif->tif_rawdataloaded;
        }

124
    assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        cc = TIFFReadFile(tif, tif->tif_rawdata + unused_data, to_read);

        if (cc != to_read) {
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
                TIFFErrorExt(tif->tif_clientdata, module,
                             "Read error at scanline %lu; got %I64u bytes, expected %I64u",
                             (unsigned long) tif->tif_row,
                             (unsigned __int64) cc,
                             (unsigned __int64) to_read);
#else
                TIFFErrorExt(tif->tif_clientdata, module,
                             "Read error at scanline %lu; got %llu bytes, expected %llu",
                             (unsigned long) tif->tif_row,
                             (unsigned long long) cc,
                             (unsigned long long) to_read);
#endif
                return 0;
        }
143

144 145 146 147
        tif->tif_rawdataoff = tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data ;
        tif->tif_rawdataloaded = unused_data + to_read;

        tif->tif_rawcp = tif->tif_rawdata;
148

149
        if (!isFillOrder(tif, td->td_fillorder) &&
150
            (tif->tif_flags & TIFF_NOBITREV) == 0) {
151
        assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
152
                TIFFReverseBits(tif->tif_rawdata + unused_data, to_read );
153
    }
154 155 156 157 158 159 160 161 162 163

        /*
        ** When starting a strip from the beginning we need to
        ** restart the decoder.
        */
        if( restart )
                return TIFFStartStrip(tif, strip);
        else
                return 1;
}
164 165 166

/*
 * Seek to a random row+sample in a file.
167 168 169 170 171
 *
 * Only used by TIFFReadScanline, and is only used on
 * strip organized files.  We do some tricky stuff to try
 * and avoid reading the whole compressed raw data for big
 * strips.
172 173
 */
static int
174
TIFFSeek(TIFF* tif, uint32 row, uint16 sample )
175
{
176 177
    register TIFFDirectory *td = &tif->tif_dir;
    uint32 strip;
178
        int    whole_strip;
179
    tmsize_t read_ahead = 0;
180

181 182 183
        /*
        ** Establish what strip we are working from.
        */
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    if (row >= td->td_imagelength) {	/* out of range */
        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
            "%lu: Row out of range, max %lu",
            (unsigned long) row,
            (unsigned long) td->td_imagelength);
        return (0);
    }
    if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
        if (sample >= td->td_samplesperpixel) {
            TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                "%lu: Sample out of range, max %lu",
                (unsigned long) sample, (unsigned long) td->td_samplesperpixel);
            return (0);
        }
        strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip;
    } else
        strip = row / td->td_rowsperstrip;
201 202 203 204 205 206 207 208 209 210 211 212 213

        /*
         * Do we want to treat this strip as one whole chunk or
         * read it a few lines at a time?
         */
#if defined(CHUNKY_STRIP_READ_SUPPORT)
        if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
            return 0;
        whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10
                || isMapped(tif);
#else
        whole_strip = 1;
#endif
214

215 216 217 218 219 220 221 222 223
        if( !whole_strip )
        {
                read_ahead = tif->tif_scanlinesize * 16 + 5000;
        }

        /*
         * If we haven't loaded this strip, do so now, possibly
         * only reading the first part.
         */
224 225
    if (strip != tif->tif_curstrip) {	/* different strip, refill */

226 227 228 229 230 231 232 233 234 235
                if( whole_strip )
                {
                        if (!TIFFFillStrip(tif, strip))
                                return (0);
                }
                else
                {
                        if( !TIFFFillStripPartial(tif,strip,read_ahead,1) )
                                return 0;
                }
236
    }
237 238 239 240 241 242

        /*
        ** If we already have some data loaded, do we need to read some more?
        */
        else if( !whole_strip )
        {
243
                if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead
244 245 246 247 248 249 250 251
                    && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] )
                {
                        if( !TIFFFillStripPartial(tif,strip,read_ahead,0) )
                                return 0;
                }
        }

        if (row < tif->tif_row) {
252 253 254 255 256 257 258 259
        /*
         * Moving backwards within the same strip: backup
         * to the start and then decode forward (below).
         *
         * NB: If you're planning on lots of random access within a
         * strip, it's better to just read and decode the entire
         * strip, and then access the decoded data in a random fashion.
         */
260 261 262 263 264 265 266 267 268 269 270

                if( tif->tif_rawdataoff != 0 )
                {
                        if( !TIFFFillStripPartial(tif,strip,read_ahead,1) )
                                return 0;
                }
                else
                {
                        if (!TIFFStartStrip(tif, strip))
                                return (0);
                }
271 272 273 274 275 276
    }

    if (row != tif->tif_row) {
        /*
         * Seek forward to the desired row.
         */
277 278 279

                /* TODO: Will this really work with partial buffers? */

280 281 282 283 284 285
        if (!(*tif->tif_seek)(tif, row - tif->tif_row))
            return (0);
        tif->tif_row = row;
    }

    return (1);
286 287 288
}

int
289
TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample)
290
{
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    int e;

    if (!TIFFCheckRead(tif, 0))
        return (-1);
    if( (e = TIFFSeek(tif, row, sample)) != 0) {
        /*
         * Decompress desired row into user buffer.
         */
        e = (*tif->tif_decoderow)
            (tif, (uint8*) buf, tif->tif_scanlinesize, sample);

        /* we are now poised at the beginning of the next row */
        tif->tif_row = row + 1;

        if (e)
            (*tif->tif_postdecode)(tif, (uint8*) buf,
                tif->tif_scanlinesize);
    }
    return (e > 0 ? 1 : -1);
310 311 312 313 314 315
}

/*
 * Read a strip of data and decompress the specified
 * amount into the user-supplied buffer.
 */
316 317
tmsize_t
TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
318
{
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    static const char module[] = "TIFFReadEncodedStrip";
    TIFFDirectory *td = &tif->tif_dir;
    uint32 rowsperstrip;
    uint32 stripsperplane;
    uint32 stripinplane;
    uint16 plane;
    uint32 rows;
    tmsize_t stripsize;
    if (!TIFFCheckRead(tif,0))
        return((tmsize_t)(-1));
    if (strip>=td->td_nstrips)
    {
        TIFFErrorExt(tif->tif_clientdata,module,
            "%lu: Strip out of range, max %lu",(unsigned long)strip,
            (unsigned long)td->td_nstrips);
        return((tmsize_t)(-1));
    }
    /*
     * Calculate the strip size according to the number of
     * rows in the strip (check for truncated last strip on any
     * of the separations).
     */
    rowsperstrip=td->td_rowsperstrip;
    if (rowsperstrip>td->td_imagelength)
        rowsperstrip=td->td_imagelength;
    stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip);
    stripinplane=(strip%stripsperplane);
    plane=(strip/stripsperplane);
    rows=td->td_imagelength-stripinplane*rowsperstrip;
    if (rows>rowsperstrip)
        rows=rowsperstrip;
    stripsize=TIFFVStripSize(tif,rows);
    if (stripsize==0)
        return((tmsize_t)(-1));
    if ((size!=(tmsize_t)(-1))&&(size<stripsize))
        stripsize=size;
    if (!TIFFFillStrip(tif,strip))
        return((tmsize_t)(-1));
    if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
        return((tmsize_t)(-1));
    (*tif->tif_postdecode)(tif,buf,stripsize);
    return(stripsize);
361 362
}

363 364 365
static tmsize_t
TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,
    const char* module)
366
{
367
    TIFFDirectory *td = &tif->tif_dir;
368

369 370
    if (!_TIFFFillStriles( tif ))
        return ((tmsize_t)(-1));
371 372 373 374 375 376 377 378 379 380 381 382 383

    assert((tif->tif_flags&TIFF_NOREADRAW)==0);
    if (!isMapped(tif)) {
        tmsize_t cc;

        if (!SeekOK(tif, td->td_stripoffset[strip])) {
            TIFFErrorExt(tif->tif_clientdata, module,
                "Seek error at scanline %lu, strip %lu",
                (unsigned long) tif->tif_row, (unsigned long) strip);
            return ((tmsize_t)(-1));
        }
        cc = TIFFReadFile(tif, buf, size);
        if (cc != size) {
384
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
385 386 387 388 389
            TIFFErrorExt(tif->tif_clientdata, module,
        "Read error at scanline %lu; got %I64u bytes, expected %I64u",
                     (unsigned long) tif->tif_row,
                     (unsigned __int64) cc,
                     (unsigned __int64) size);
390
#else
391 392 393 394 395
            TIFFErrorExt(tif->tif_clientdata, module,
        "Read error at scanline %lu; got %llu bytes, expected %llu",
                     (unsigned long) tif->tif_row,
                     (unsigned long long) cc,
                     (unsigned long long) size);
396
#endif
397 398 399 400 401 402 403 404 405 406 407 408 409 410
            return ((tmsize_t)(-1));
        }
    } else {
        tmsize_t ma,mb;
        tmsize_t n;
        ma=(tmsize_t)td->td_stripoffset[strip];
        mb=ma+size;
        if (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size))
            n=0;
        else if ((mb<ma)||(mb<size)||(mb>tif->tif_size))
            n=tif->tif_size-ma;
        else
            n=size;
        if (n!=size) {
411
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
412 413 414 415 416 417
            TIFFErrorExt(tif->tif_clientdata, module,
    "Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u",
                     (unsigned long) tif->tif_row,
                     (unsigned long) strip,
                     (unsigned __int64) n,
                     (unsigned __int64) size);
418
#else
419 420 421 422 423 424
            TIFFErrorExt(tif->tif_clientdata, module,
    "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu",
                     (unsigned long) tif->tif_row,
                     (unsigned long) strip,
                     (unsigned long long) n,
                     (unsigned long long) size);
425
#endif
426 427 428 429 430 431
            return ((tmsize_t)(-1));
        }
        _TIFFmemcpy(buf, tif->tif_base + ma,
                size);
    }
    return (size);
432 433 434 435 436
}

/*
 * Read a strip of data from the file.
 */
437 438
tmsize_t
TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size)
439
{
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    static const char module[] = "TIFFReadRawStrip";
    TIFFDirectory *td = &tif->tif_dir;
    uint64 bytecount;
    tmsize_t bytecountm;

    if (!TIFFCheckRead(tif, 0))
        return ((tmsize_t)(-1));
    if (strip >= td->td_nstrips) {
        TIFFErrorExt(tif->tif_clientdata, module,
             "%lu: Strip out of range, max %lu",
             (unsigned long) strip,
             (unsigned long) td->td_nstrips);
        return ((tmsize_t)(-1));
    }
    if (tif->tif_flags&TIFF_NOREADRAW)
    {
        TIFFErrorExt(tif->tif_clientdata, module,
            "Compression scheme does not support access to raw uncompressed data");
        return ((tmsize_t)(-1));
    }
    bytecount = td->td_stripbytecount[strip];
    if (bytecount <= 0) {
462
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
463 464 465 466
        TIFFErrorExt(tif->tif_clientdata, module,
                 "%I64u: Invalid strip byte count, strip %lu",
                 (unsigned __int64) bytecount,
                 (unsigned long) strip);
467
#else
468 469 470 471
        TIFFErrorExt(tif->tif_clientdata, module,
                 "%llu: Invalid strip byte count, strip %lu",
                 (unsigned long long) bytecount,
                 (unsigned long) strip);
472
#endif
473 474 475 476 477 478 479 480 481 482
        return ((tmsize_t)(-1));
    }
    bytecountm = (tmsize_t)bytecount;
    if ((uint64)bytecountm!=bytecount) {
        TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow");
        return ((tmsize_t)(-1));
    }
    if (size != (tmsize_t)(-1) && size < bytecountm)
        bytecountm = size;
    return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module));
483 484 485
}

/*
486 487
 * Read the specified strip and setup for decoding. The data buffer is
 * expanded, as necessary, to hold the strip's data.
488 489
 */
int
490
TIFFFillStrip(TIFF* tif, uint32 strip)
491
{
492 493
    static const char module[] = "TIFFFillStrip";
    TIFFDirectory *td = &tif->tif_dir;
494

495 496
    if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
        return 0;
497 498 499 500 501

    if ((tif->tif_flags&TIFF_NOREADRAW)==0)
    {
        uint64 bytecount = td->td_stripbytecount[strip];
        if (bytecount <= 0) {
502
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
503 504 505 506
            TIFFErrorExt(tif->tif_clientdata, module,
                "Invalid strip byte count %I64u, strip %lu",
                     (unsigned __int64) bytecount,
                     (unsigned long) strip);
507
#else
508 509 510 511
            TIFFErrorExt(tif->tif_clientdata, module,
                "Invalid strip byte count %llu, strip %lu",
                     (unsigned long long) bytecount,
                     (unsigned long) strip);
512
#endif
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            return (0);
        }
        if (isMapped(tif) &&
            (isFillOrder(tif, td->td_fillorder)
            || (tif->tif_flags & TIFF_NOBITREV))) {
            /*
             * The image is mapped into memory and we either don't
             * need to flip bits or the compression routine is
             * going to handle this operation itself.  In this
             * case, avoid copying the raw data and instead just
             * reference the data from the memory mapped file
             * image.  This assumes that the decompression
             * routines do not modify the contents of the raw data
             * buffer (if they try to, the application will get a
             * fault since the file is mapped read-only).
             */
            if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
                _TIFFfree(tif->tif_rawdata);
                tif->tif_rawdata = NULL;
                tif->tif_rawdatasize = 0;
            }
            tif->tif_flags &= ~TIFF_MYBUFFER;
            /*
             * We must check for overflow, potentially causing
             * an OOB read. Instead of simple
             *
             *  td->td_stripoffset[strip]+bytecount > tif->tif_size
             *
             * comparison (which can overflow) we do the following
             * two comparisons:
             */
            if (bytecount > (uint64)tif->tif_size ||
                td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) {
                /*
                 * This error message might seem strange, but
                 * it's what would happen if a read were done
                 * instead.
                 */
551
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
552
                TIFFErrorExt(tif->tif_clientdata, module,
553

554 555 556 557 558
                    "Read error on strip %lu; "
                    "got %I64u bytes, expected %I64u",
                    (unsigned long) strip,
                    (unsigned __int64) tif->tif_size - td->td_stripoffset[strip],
                    (unsigned __int64) bytecount);
559
#else
560
                TIFFErrorExt(tif->tif_clientdata, module,
561

562 563 564 565 566
                    "Read error on strip %lu; "
                    "got %llu bytes, expected %llu",
                    (unsigned long) strip,
                    (unsigned long long) tif->tif_size - td->td_stripoffset[strip],
                    (unsigned long long) bytecount);
567
#endif
568 569 570 571 572
                tif->tif_curstrip = NOSTRIP;
                return (0);
            }
            tif->tif_rawdatasize = (tmsize_t)bytecount;
            tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip];
573 574
                        tif->tif_rawdataoff = 0;
                        tif->tif_rawdataloaded = (tmsize_t) bytecount;
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
            /*
             * When we have tif_rawdata reference directly into the memory mapped file
             * we need to be pretty careful about how we use the rawdata.  It is not
             * a general purpose working buffer as it normally otherwise is.  So we
             * keep track of this fact to avoid using it improperly.
             */
            tif->tif_flags |= TIFF_BUFFERMMAP;
        } else {
            /*
             * Expand raw data buffer, if needed, to hold data
             * strip coming from file (perhaps should set upper
             * bound on the size of a buffer we'll use?).
             */
            tmsize_t bytecountm;
            bytecountm=(tmsize_t)bytecount;
            if ((uint64)bytecountm!=bytecount)
            {
                TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
                return(0);
            }
            if (bytecountm > tif->tif_rawdatasize) {
                tif->tif_curstrip = NOSTRIP;
                if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
                    TIFFErrorExt(tif->tif_clientdata, module,
                        "Data buffer too small to hold strip %lu",
                        (unsigned long) strip);
                    return (0);
                }
                if (!TIFFReadBufferSetup(tif, 0, bytecountm))
                    return (0);
            }
            if (tif->tif_flags&TIFF_BUFFERMMAP) {
                tif->tif_curstrip = NOSTRIP;
                if (!TIFFReadBufferSetup(tif, 0, bytecountm))
                    return (0);
            }
            if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata,
                bytecountm, module) != bytecountm)
                return (0);
615 616 617

                        tif->tif_rawdataoff = 0;
                        tif->tif_rawdataloaded = bytecountm;
618 619 620 621

            if (!isFillOrder(tif, td->td_fillorder) &&
                (tif->tif_flags & TIFF_NOBITREV) == 0)
                TIFFReverseBits(tif->tif_rawdata, bytecountm);
622
                }
623 624
    }
    return (TIFFStartStrip(tif, strip));
625 626 627 628 629 630 631 632 633 634 635
}

/*
 * Tile-oriented Read Support
 * Contributed by Nancy Cam (Silicon Graphics).
 */

/*
 * Read and decompress a tile of data.  The
 * tile is selected by the (x,y,z,s) coordinates.
 */
636 637
tmsize_t
TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s)
638
{
639 640 641 642
    if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
        return ((tmsize_t)(-1));
    return (TIFFReadEncodedTile(tif,
        TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1)));
643 644 645 646 647 648
}

/*
 * Read a tile of data and decompress the specified
 * amount into the user-supplied buffer.
 */
649 650
tmsize_t
TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
651
{
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    static const char module[] = "TIFFReadEncodedTile";
    TIFFDirectory *td = &tif->tif_dir;
    tmsize_t tilesize = tif->tif_tilesize;

    if (!TIFFCheckRead(tif, 1))
        return ((tmsize_t)(-1));
    if (tile >= td->td_nstrips) {
        TIFFErrorExt(tif->tif_clientdata, module,
            "%lu: Tile out of range, max %lu",
            (unsigned long) tile, (unsigned long) td->td_nstrips);
        return ((tmsize_t)(-1));
    }
    if (size == (tmsize_t)(-1))
        size = tilesize;
    else if (size > tilesize)
        size = tilesize;
    if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif,
        (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) {
        (*tif->tif_postdecode)(tif, (uint8*) buf, size);
        return (size);
    } else
        return ((tmsize_t)(-1));
674 675
}

676 677
static tmsize_t
TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module)
678
{
679
    TIFFDirectory *td = &tif->tif_dir;
680

681 682 683
    if (!_TIFFFillStriles( tif ))
        return ((tmsize_t)(-1));

684 685 686 687 688 689 690 691 692 693 694 695 696 697
    assert((tif->tif_flags&TIFF_NOREADRAW)==0);
    if (!isMapped(tif)) {
        tmsize_t cc;

        if (!SeekOK(tif, td->td_stripoffset[tile])) {
            TIFFErrorExt(tif->tif_clientdata, module,
                "Seek error at row %lu, col %lu, tile %lu",
                (unsigned long) tif->tif_row,
                (unsigned long) tif->tif_col,
                (unsigned long) tile);
            return ((tmsize_t)(-1));
        }
        cc = TIFFReadFile(tif, buf, size);
        if (cc != size) {
698
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
699 700 701 702 703 704
            TIFFErrorExt(tif->tif_clientdata, module,
    "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u",
                     (unsigned long) tif->tif_row,
                     (unsigned long) tif->tif_col,
                     (unsigned __int64) cc,
                     (unsigned __int64) size);
705
#else
706 707 708 709 710 711
            TIFFErrorExt(tif->tif_clientdata, module,
    "Read error at row %lu, col %lu; got %llu bytes, expected %llu",
                     (unsigned long) tif->tif_row,
                     (unsigned long) tif->tif_col,
                     (unsigned long long) cc,
                     (unsigned long long) size);
712
#endif
713 714 715 716 717 718 719 720 721 722 723 724 725 726
            return ((tmsize_t)(-1));
        }
    } else {
        tmsize_t ma,mb;
        tmsize_t n;
        ma=(tmsize_t)td->td_stripoffset[tile];
        mb=ma+size;
        if (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size))
            n=0;
        else if ((mb<ma)||(mb<size)||(mb>tif->tif_size))
            n=tif->tif_size-ma;
        else
            n=size;
        if (n!=size) {
727
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
728
            TIFFErrorExt(tif->tif_clientdata, module,
729
"Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u",
730 731 732 733 734
                     (unsigned long) tif->tif_row,
                     (unsigned long) tif->tif_col,
                     (unsigned long) tile,
                     (unsigned __int64) n,
                     (unsigned __int64) size);
735
#else
736
            TIFFErrorExt(tif->tif_clientdata, module,
737
"Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu",
738 739 740 741 742
                     (unsigned long) tif->tif_row,
                     (unsigned long) tif->tif_col,
                     (unsigned long) tile,
                     (unsigned long long) n,
                     (unsigned long long) size);
743
#endif
744 745 746 747 748
            return ((tmsize_t)(-1));
        }
        _TIFFmemcpy(buf, tif->tif_base + ma, size);
    }
    return (size);
749 750 751 752 753
}

/*
 * Read a tile of data from the file.
 */
754 755
tmsize_t
TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size)
756
{
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    static const char module[] = "TIFFReadRawTile";
    TIFFDirectory *td = &tif->tif_dir;
    uint64 bytecount64;
    tmsize_t bytecountm;

    if (!TIFFCheckRead(tif, 1))
        return ((tmsize_t)(-1));
    if (tile >= td->td_nstrips) {
        TIFFErrorExt(tif->tif_clientdata, module,
            "%lu: Tile out of range, max %lu",
            (unsigned long) tile, (unsigned long) td->td_nstrips);
        return ((tmsize_t)(-1));
    }
    if (tif->tif_flags&TIFF_NOREADRAW)
    {
        TIFFErrorExt(tif->tif_clientdata, module,
        "Compression scheme does not support access to raw uncompressed data");
        return ((tmsize_t)(-1));
    }
    bytecount64 = td->td_stripbytecount[tile];
    if (size != (tmsize_t)(-1) && (uint64)size < bytecount64)
        bytecount64 = (uint64)size;
    bytecountm = (tmsize_t)bytecount64;
    if ((uint64)bytecountm!=bytecount64)
    {
        TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
        return ((tmsize_t)(-1));
    }
    return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module));
786 787 788
}

/*
789 790
 * Read the specified tile and setup for decoding. The data buffer is
 * expanded, as necessary, to hold the tile's data.
791 792
 */
int
793
TIFFFillTile(TIFF* tif, uint32 tile)
794
{
795 796
    static const char module[] = "TIFFFillTile";
    TIFFDirectory *td = &tif->tif_dir;
797

798 799
    if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
        return 0;
800 801 802 803 804

    if ((tif->tif_flags&TIFF_NOREADRAW)==0)
    {
        uint64 bytecount = td->td_stripbytecount[tile];
        if (bytecount <= 0) {
805
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
806 807 808 809
            TIFFErrorExt(tif->tif_clientdata, module,
                "%I64u: Invalid tile byte count, tile %lu",
                     (unsigned __int64) bytecount,
                     (unsigned long) tile);
810
#else
811 812 813 814
            TIFFErrorExt(tif->tif_clientdata, module,
                "%llu: Invalid tile byte count, tile %lu",
                     (unsigned long long) bytecount,
                     (unsigned long) tile);
815
#endif
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
            return (0);
        }
        if (isMapped(tif) &&
            (isFillOrder(tif, td->td_fillorder)
             || (tif->tif_flags & TIFF_NOBITREV))) {
            /*
             * The image is mapped into memory and we either don't
             * need to flip bits or the compression routine is
             * going to handle this operation itself.  In this
             * case, avoid copying the raw data and instead just
             * reference the data from the memory mapped file
             * image.  This assumes that the decompression
             * routines do not modify the contents of the raw data
             * buffer (if they try to, the application will get a
             * fault since the file is mapped read-only).
             */
            if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
                _TIFFfree(tif->tif_rawdata);
                tif->tif_rawdata = NULL;
                tif->tif_rawdatasize = 0;
            }
            tif->tif_flags &= ~TIFF_MYBUFFER;
            /*
             * We must check for overflow, potentially causing
             * an OOB read. Instead of simple
             *
             *  td->td_stripoffset[tile]+bytecount > tif->tif_size
             *
             * comparison (which can overflow) we do the following
             * two comparisons:
             */
            if (bytecount > (uint64)tif->tif_size ||
                td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) {
                tif->tif_curtile = NOTILE;
                return (0);
            }
            tif->tif_rawdatasize = (tmsize_t)bytecount;
            tif->tif_rawdata =
                tif->tif_base + (tmsize_t)td->td_stripoffset[tile];
855 856
                        tif->tif_rawdataoff = 0;
                        tif->tif_rawdataloaded = (tmsize_t) bytecount;
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
            tif->tif_flags |= TIFF_BUFFERMMAP;
        } else {
            /*
             * Expand raw data buffer, if needed, to hold data
             * tile coming from file (perhaps should set upper
             * bound on the size of a buffer we'll use?).
             */
            tmsize_t bytecountm;
            bytecountm=(tmsize_t)bytecount;
            if ((uint64)bytecountm!=bytecount)
            {
                TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
                return(0);
            }
            if (bytecountm > tif->tif_rawdatasize) {
                tif->tif_curtile = NOTILE;
                if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
                    TIFFErrorExt(tif->tif_clientdata, module,
                        "Data buffer too small to hold tile %lu",
                        (unsigned long) tile);
                    return (0);
                }
                if (!TIFFReadBufferSetup(tif, 0, bytecountm))
                    return (0);
            }
            if (tif->tif_flags&TIFF_BUFFERMMAP) {
                tif->tif_curtile = NOTILE;
                if (!TIFFReadBufferSetup(tif, 0, bytecountm))
                    return (0);
            }

            if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata,
                bytecountm, module) != bytecountm)
                return (0);
891 892 893

                        tif->tif_rawdataoff = 0;
                        tif->tif_rawdataloaded = bytecountm;
894 895 896 897

            if (!isFillOrder(tif, td->td_fillorder) &&
                (tif->tif_flags & TIFF_NOBITREV) == 0)
                TIFFReverseBits(tif->tif_rawdata,
898
                                                tif->tif_rawdataloaded);
899 900 901
        }
    }
    return (TIFFStartTile(tif, tile));
902 903 904 905 906 907 908 909 910 911 912 913
}

/*
 * Setup the raw data buffer in preparation for
 * reading a strip of raw data.  If the buffer
 * is specified as zero, then a buffer of appropriate
 * size is allocated by the library.  Otherwise,
 * the client must guarantee that the buffer is
 * large enough to hold any individual strip of
 * raw data.
 */
int
914
TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size)
915
{
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    static const char module[] = "TIFFReadBufferSetup";

    assert((tif->tif_flags&TIFF_NOREADRAW)==0);
    tif->tif_flags &= ~TIFF_BUFFERMMAP;

    if (tif->tif_rawdata) {
        if (tif->tif_flags & TIFF_MYBUFFER)
            _TIFFfree(tif->tif_rawdata);
        tif->tif_rawdata = NULL;
        tif->tif_rawdatasize = 0;
    }
    if (bp) {
        tif->tif_rawdatasize = size;
        tif->tif_rawdata = (uint8*) bp;
        tif->tif_flags &= ~TIFF_MYBUFFER;
    } else {
        tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024);
        if (tif->tif_rawdatasize==0)
            tif->tif_rawdatasize=(tmsize_t)(-1);
        tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize);
        tif->tif_flags |= TIFF_MYBUFFER;
    }
    if (tif->tif_rawdata == NULL) {
        TIFFErrorExt(tif->tif_clientdata, module,
            "No space for data buffer at scanline %lu",
            (unsigned long) tif->tif_row);
        tif->tif_rawdatasize = 0;
        return (0);
    }
    return (1);
946 947 948 949 950 951 952
}

/*
 * Set state to appear as if a
 * strip has just been read in.
 */
static int
953
TIFFStartStrip(TIFF* tif, uint32 strip)
954
{
955
    TIFFDirectory *td = &tif->tif_dir;
956

957 958 959
    if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
        return 0;

960 961 962 963 964 965 966
    if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
        if (!(*tif->tif_setupdecode)(tif))
            return (0);
        tif->tif_flags |= TIFF_CODERSETUP;
    }
    tif->tif_curstrip = strip;
    tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
967 968
        tif->tif_flags &= ~TIFF_BUF4WRITE;

969 970 971 972 973 974 975 976 977 978 979 980
    if (tif->tif_flags&TIFF_NOREADRAW)
    {
        tif->tif_rawcp = NULL;
        tif->tif_rawcc = 0;
    }
    else
    {
        tif->tif_rawcp = tif->tif_rawdata;
        tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip];
    }
    return ((*tif->tif_predecode)(tif,
            (uint16)(strip / td->td_stripsperimage)));
981 982 983 984 985 986 987
}

/*
 * Set state to appear as if a
 * tile has just been read in.
 */
static int
988
TIFFStartTile(TIFF* tif, uint32 tile)
989
{
990
    TIFFDirectory *td = &tif->tif_dir;
991

992 993 994
    if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
        return 0;

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
        if (!(*tif->tif_setupdecode)(tif))
            return (0);
        tif->tif_flags |= TIFF_CODERSETUP;
    }
    tif->tif_curtile = tile;
    tif->tif_row =
        (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth)) *
        td->td_tilelength;
    tif->tif_col =
        (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength)) *
        td->td_tilewidth;
1007
        tif->tif_flags &= ~TIFF_BUF4WRITE;
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    if (tif->tif_flags&TIFF_NOREADRAW)
    {
        tif->tif_rawcp = NULL;
        tif->tif_rawcc = 0;
    }
    else
    {
        tif->tif_rawcp = tif->tif_rawdata;
        tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile];
    }
    return ((*tif->tif_predecode)(tif,
            (uint16)(tile/td->td_stripsperimage)));
1020 1021 1022 1023 1024
}

static int
TIFFCheckRead(TIFF* tif, int tiles)
{
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    if (tif->tif_mode == O_WRONLY) {
        TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading");
        return (0);
    }
    if (tiles ^ isTiled(tif)) {
        TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ?
            "Can not read tiles from a stripped image" :
            "Can not read scanlines from a tiled image");
        return (0);
    }
    return (1);
1036 1037 1038
}

void
1039
_TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
1040 1041 1042 1043 1044
{
    (void) tif; (void) buf; (void) cc;
}

void
1045
_TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1046 1047 1048 1049 1050 1051
{
    (void) tif;
    assert((cc & 1) == 0);
    TIFFSwabArrayOfShort((uint16*) buf, cc/2);
}

1052
void
1053
_TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1054 1055 1056 1057 1058 1059
{
    (void) tif;
    assert((cc % 3) == 0);
    TIFFSwabArrayOfTriples((uint8*) buf, cc/3);
}

1060
void
1061
_TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1062 1063 1064 1065 1066 1067 1068
{
    (void) tif;
    assert((cc & 3) == 0);
    TIFFSwabArrayOfLong((uint32*) buf, cc/4);
}

void
1069
_TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc)
1070 1071 1072 1073 1074 1075 1076
{
    (void) tif;
    assert((cc & 7) == 0);
    TIFFSwabArrayOfDouble((double*) buf, cc/8);
}

/* vim: set ts=8 sts=8 sw=8 noet: */
1077 1078 1079 1080 1081 1082 1083
/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 8
 * fill-column: 78
 * End:
 */