Home | History | Annotate | Download | only in libpng
      1 
      2 /* pngrutil.c - utilities to read a PNG file
      3  *
      4  * Last changed in libpng 1.6.10 [March 6, 2014]
      5  * Copyright (c) 1998-2014 Glenn Randers-Pehrson
      6  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
      7  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
      8  *
      9  * This code is released under the libpng license.
     10  * For conditions of distribution and use, see the disclaimer
     11  * and license in png.h
     12  *
     13  * This file contains routines that are only called from within
     14  * libpng itself during the course of reading an image.
     15  */
     16 
     17 #include "pngpriv.h"
     18 
     19 #ifdef PNG_READ_SUPPORTED
     20 
     21 png_uint_32 PNGAPI
     22 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
     23 {
     24    png_uint_32 uval = png_get_uint_32(buf);
     25 
     26    if (uval > PNG_UINT_31_MAX)
     27       png_error(png_ptr, "PNG unsigned integer out of range");
     28 
     29    return (uval);
     30 }
     31 
     32 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
     33 /* The following is a variation on the above for use with the fixed
     34  * point values used for gAMA and cHRM.  Instead of png_error it
     35  * issues a warning and returns (-1) - an invalid value because both
     36  * gAMA and cHRM use *unsigned* integers for fixed point values.
     37  */
     38 #define PNG_FIXED_ERROR (-1)
     39 
     40 static png_fixed_point /* PRIVATE */
     41 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
     42 {
     43    png_uint_32 uval = png_get_uint_32(buf);
     44 
     45    if (uval <= PNG_UINT_31_MAX)
     46       return (png_fixed_point)uval; /* known to be in range */
     47 
     48    /* The caller can turn off the warning by passing NULL. */
     49    if (png_ptr != NULL)
     50       png_warning(png_ptr, "PNG fixed point integer out of range");
     51 
     52    return PNG_FIXED_ERROR;
     53 }
     54 #endif
     55 
     56 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
     57 /* NOTE: the read macros will obscure these definitions, so that if
     58  * PNG_USE_READ_MACROS is set the library will not use them internally,
     59  * but the APIs will still be available externally.
     60  *
     61  * The parentheses around "PNGAPI function_name" in the following three
     62  * functions are necessary because they allow the macros to co-exist with
     63  * these (unused but exported) functions.
     64  */
     65 
     66 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
     67 png_uint_32 (PNGAPI
     68 png_get_uint_32)(png_const_bytep buf)
     69 {
     70    png_uint_32 uval =
     71        ((png_uint_32)(*(buf    )) << 24) +
     72        ((png_uint_32)(*(buf + 1)) << 16) +
     73        ((png_uint_32)(*(buf + 2)) <<  8) +
     74        ((png_uint_32)(*(buf + 3))      ) ;
     75 
     76    return uval;
     77 }
     78 
     79 /* Grab a signed 32-bit integer from a buffer in big-endian format.  The
     80  * data is stored in the PNG file in two's complement format and there
     81  * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
     82  * the following code does a two's complement to native conversion.
     83  */
     84 png_int_32 (PNGAPI
     85 png_get_int_32)(png_const_bytep buf)
     86 {
     87    png_uint_32 uval = png_get_uint_32(buf);
     88    if ((uval & 0x80000000) == 0) /* non-negative */
     89       return uval;
     90 
     91    uval = (uval ^ 0xffffffff) + 1;  /* 2's complement: -x = ~x+1 */
     92    return -(png_int_32)uval;
     93 }
     94 
     95 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
     96 png_uint_16 (PNGAPI
     97 png_get_uint_16)(png_const_bytep buf)
     98 {
     99    /* ANSI-C requires an int value to accomodate at least 16 bits so this
    100     * works and allows the compiler not to worry about possible narrowing
    101     * on 32 bit systems.  (Pre-ANSI systems did not make integers smaller
    102     * than 16 bits either.)
    103     */
    104    unsigned int val =
    105        ((unsigned int)(*buf) << 8) +
    106        ((unsigned int)(*(buf + 1)));
    107 
    108    return (png_uint_16)val;
    109 }
    110 
    111 #endif /* PNG_READ_INT_FUNCTIONS_SUPPORTED */
    112 
    113 /* Read and check the PNG file signature */
    114 void /* PRIVATE */
    115 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
    116 {
    117    png_size_t num_checked, num_to_check;
    118 
    119    /* Exit if the user application does not expect a signature. */
    120    if (png_ptr->sig_bytes >= 8)
    121       return;
    122 
    123    num_checked = png_ptr->sig_bytes;
    124    num_to_check = 8 - num_checked;
    125 
    126 #ifdef PNG_IO_STATE_SUPPORTED
    127    png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
    128 #endif
    129 
    130    /* The signature must be serialized in a single I/O call. */
    131    png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
    132    png_ptr->sig_bytes = 8;
    133 
    134    if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
    135    {
    136       if (num_checked < 4 &&
    137           png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
    138          png_error(png_ptr, "Not a PNG file");
    139       else
    140          png_error(png_ptr, "PNG file corrupted by ASCII conversion");
    141    }
    142    if (num_checked < 3)
    143       png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
    144 }
    145 
    146 /* Read the chunk header (length + type name).
    147  * Put the type name into png_ptr->chunk_name, and return the length.
    148  */
    149 png_uint_32 /* PRIVATE */
    150 png_read_chunk_header(png_structrp png_ptr)
    151 {
    152    png_byte buf[8];
    153    png_uint_32 length;
    154 
    155 #ifdef PNG_IO_STATE_SUPPORTED
    156    png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
    157 #endif
    158 
    159    /* Read the length and the chunk name.
    160     * This must be performed in a single I/O call.
    161     */
    162    png_read_data(png_ptr, buf, 8);
    163    length = png_get_uint_31(png_ptr, buf);
    164 
    165    /* Put the chunk name into png_ptr->chunk_name. */
    166    png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
    167 
    168    png_debug2(0, "Reading %lx chunk, length = %lu",
    169        (unsigned long)png_ptr->chunk_name, (unsigned long)length);
    170 
    171    /* Reset the crc and run it over the chunk name. */
    172    png_reset_crc(png_ptr);
    173    png_calculate_crc(png_ptr, buf + 4, 4);
    174 
    175    /* Check to see if chunk name is valid. */
    176    png_check_chunk_name(png_ptr, png_ptr->chunk_name);
    177 
    178 #ifdef PNG_IO_STATE_SUPPORTED
    179    png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
    180 #endif
    181 
    182    return length;
    183 }
    184 
    185 /* Read data, and (optionally) run it through the CRC. */
    186 void /* PRIVATE */
    187 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
    188 {
    189    if (png_ptr == NULL)
    190       return;
    191 
    192    png_read_data(png_ptr, buf, length);
    193    png_calculate_crc(png_ptr, buf, length);
    194 }
    195 
    196 /* Optionally skip data and then check the CRC.  Depending on whether we
    197  * are reading an ancillary or critical chunk, and how the program has set
    198  * things up, we may calculate the CRC on the data and print a message.
    199  * Returns '1' if there was a CRC error, '0' otherwise.
    200  */
    201 int /* PRIVATE */
    202 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
    203 {
    204    /* The size of the local buffer for inflate is a good guess as to a
    205     * reasonable size to use for buffering reads from the application.
    206     */
    207    while (skip > 0)
    208    {
    209       png_uint_32 len;
    210       png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
    211 
    212       len = (sizeof tmpbuf);
    213       if (len > skip)
    214          len = skip;
    215       skip -= len;
    216 
    217       png_crc_read(png_ptr, tmpbuf, len);
    218    }
    219 
    220    if (png_crc_error(png_ptr))
    221    {
    222       if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) ?
    223           !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) :
    224           (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE))
    225       {
    226          png_chunk_warning(png_ptr, "CRC error");
    227       }
    228 
    229       else
    230          png_chunk_error(png_ptr, "CRC error");
    231 
    232       return (1);
    233    }
    234 
    235    return (0);
    236 }
    237 
    238 #ifdef PNG_INDEX_SUPPORTED
    239 int /* PRIVATE */
    240 png_opt_crc_finish(png_structrp png_ptr, png_uint_32 skip)
    241 {
    242    while (skip > 0)
    243    {
    244       png_uint_32 len;
    245       png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
    246 
    247       len = (sizeof tmpbuf);
    248       if (len > skip)
    249          len = skip;
    250       skip -= len;
    251 
    252       png_crc_read(png_ptr, tmpbuf, len);
    253    }
    254 
    255    if (png_crc_error(png_ptr))
    256    {
    257       png_chunk_warning(png_ptr, "CRC error");
    258       return (1);
    259    }
    260 
    261    return (0);
    262 }
    263 #endif
    264 
    265 /* Compare the CRC stored in the PNG file with that calculated by libpng from
    266  * the data it has read thus far.
    267  */
    268 int /* PRIVATE */
    269 png_crc_error(png_structrp png_ptr)
    270 {
    271    png_byte crc_bytes[4];
    272    png_uint_32 crc;
    273    int need_crc = 1;
    274 
    275    if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))
    276    {
    277       if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
    278           (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
    279          need_crc = 0;
    280    }
    281 
    282    else /* critical */
    283    {
    284       if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
    285          need_crc = 0;
    286    }
    287 
    288 #ifdef PNG_IO_STATE_SUPPORTED
    289    png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
    290 #endif
    291 
    292    /* The chunk CRC must be serialized in a single I/O call. */
    293    png_read_data(png_ptr, crc_bytes, 4);
    294 
    295    if (need_crc)
    296    {
    297       crc = png_get_uint_32(crc_bytes);
    298       return ((int)(crc != png_ptr->crc));
    299    }
    300 
    301    else
    302       return (0);
    303 }
    304 
    305 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
    306     defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
    307     defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
    308     defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
    309 /* Manage the read buffer; this simply reallocates the buffer if it is not small
    310  * enough (or if it is not allocated).  The routine returns a pointer to the
    311  * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
    312  * it will call png_error (via png_malloc) on failure.  (warn == 2 means
    313  * 'silent').
    314  */
    315 static png_bytep
    316 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
    317 {
    318    png_bytep buffer = png_ptr->read_buffer;
    319 
    320    if (buffer != NULL && new_size > png_ptr->read_buffer_size)
    321    {
    322       png_ptr->read_buffer = NULL;
    323       png_ptr->read_buffer = NULL;
    324       png_ptr->read_buffer_size = 0;
    325       png_free(png_ptr, buffer);
    326       buffer = NULL;
    327    }
    328 
    329    if (buffer == NULL)
    330    {
    331       buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
    332 
    333       if (buffer != NULL)
    334       {
    335          png_ptr->read_buffer = buffer;
    336          png_ptr->read_buffer_size = new_size;
    337       }
    338 
    339       else if (warn < 2) /* else silent */
    340       {
    341          if (warn)
    342              png_chunk_warning(png_ptr, "insufficient memory to read chunk");
    343 
    344          else
    345              png_chunk_error(png_ptr, "insufficient memory to read chunk");
    346       }
    347    }
    348 
    349    return buffer;
    350 }
    351 #endif /* PNG_READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
    352 
    353 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
    354  * decompression.  Returns Z_OK on success, else a zlib error code.  It checks
    355  * the owner but, in final release builds, just issues a warning if some other
    356  * chunk apparently owns the stream.  Prior to release it does a png_error.
    357  */
    358 static int
    359 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
    360 {
    361    if (png_ptr->zowner != 0)
    362    {
    363       char msg[64];
    364 
    365       PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
    366       /* So the message that results is "<chunk> using zstream"; this is an
    367        * internal error, but is very useful for debugging.  i18n requirements
    368        * are minimal.
    369        */
    370       (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
    371 #     if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
    372          png_chunk_warning(png_ptr, msg);
    373          png_ptr->zowner = 0;
    374 #     else
    375          png_chunk_error(png_ptr, msg);
    376 #     endif
    377    }
    378 
    379    /* Implementation note: unlike 'png_deflate_claim' this internal function
    380     * does not take the size of the data as an argument.  Some efficiency could
    381     * be gained by using this when it is known *if* the zlib stream itself does
    382     * not record the number; however, this is an illusion: the original writer
    383     * of the PNG may have selected a lower window size, and we really must
    384     * follow that because, for systems with with limited capabilities, we
    385     * would otherwise reject the application's attempts to use a smaller window
    386     * size (zlib doesn't have an interface to say "this or lower"!).
    387     *
    388     * inflateReset2 was added to zlib 1.2.4; before this the window could not be
    389     * reset, therefore it is necessary to always allocate the maximum window
    390     * size with earlier zlibs just in case later compressed chunks need it.
    391     */
    392    {
    393       int ret; /* zlib return code */
    394 #     if PNG_ZLIB_VERNUM >= 0x1240
    395 
    396 #        if defined(PNG_SET_OPTION_SUPPORTED) && \
    397             defined(PNG_MAXIMUM_INFLATE_WINDOW)
    398             int window_bits;
    399 
    400             if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
    401                PNG_OPTION_ON)
    402                window_bits = 15;
    403 
    404             else
    405                window_bits = 0;
    406 #        else
    407 #           define window_bits 0
    408 #        endif
    409 #     endif
    410 
    411       /* Set this for safety, just in case the previous owner left pointers to
    412        * memory allocations.
    413        */
    414       png_ptr->zstream.next_in = NULL;
    415       png_ptr->zstream.avail_in = 0;
    416       png_ptr->zstream.next_out = NULL;
    417       png_ptr->zstream.avail_out = 0;
    418 
    419       if (png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED)
    420       {
    421 #        if PNG_ZLIB_VERNUM < 0x1240
    422             ret = inflateReset(&png_ptr->zstream);
    423 #        else
    424             ret = inflateReset2(&png_ptr->zstream, window_bits);
    425 #        endif
    426       }
    427 
    428       else
    429       {
    430 #        if PNG_ZLIB_VERNUM < 0x1240
    431             ret = inflateInit(&png_ptr->zstream);
    432 #        else
    433             ret = inflateInit2(&png_ptr->zstream, window_bits);
    434 #        endif
    435 
    436          if (ret == Z_OK)
    437             png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
    438       }
    439 
    440       if (ret == Z_OK)
    441          png_ptr->zowner = owner;
    442 
    443       else
    444          png_zstream_error(png_ptr, ret);
    445 
    446       return ret;
    447    }
    448 
    449 #  ifdef window_bits
    450 #     undef window_bits
    451 #  endif
    452 }
    453 
    454 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
    455 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
    456  * allow the caller to do multiple calls if required.  If the 'finish' flag is
    457  * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
    458  * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
    459  * Z_OK or Z_STREAM_END will be returned on success.
    460  *
    461  * The input and output sizes are updated to the actual amounts of data consumed
    462  * or written, not the amount available (as in a z_stream).  The data pointers
    463  * are not changed, so the next input is (data+input_size) and the next
    464  * available output is (output+output_size).
    465  */
    466 static int
    467 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
    468     /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
    469     /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
    470 {
    471    if (png_ptr->zowner == owner) /* Else not claimed */
    472    {
    473       int ret;
    474       png_alloc_size_t avail_out = *output_size_ptr;
    475       png_uint_32 avail_in = *input_size_ptr;
    476 
    477       /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
    478        * can't even necessarily handle 65536 bytes) because the type uInt is
    479        * "16 bits or more".  Consequently it is necessary to chunk the input to
    480        * zlib.  This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
    481        * maximum value that can be stored in a uInt.)  It is possible to set
    482        * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
    483        * a performance advantage, because it reduces the amount of data accessed
    484        * at each step and that may give the OS more time to page it in.
    485        */
    486       png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
    487       /* avail_in and avail_out are set below from 'size' */
    488       png_ptr->zstream.avail_in = 0;
    489       png_ptr->zstream.avail_out = 0;
    490 
    491       /* Read directly into the output if it is available (this is set to
    492        * a local buffer below if output is NULL).
    493        */
    494       if (output != NULL)
    495          png_ptr->zstream.next_out = output;
    496 
    497       do
    498       {
    499          uInt avail;
    500          Byte local_buffer[PNG_INFLATE_BUF_SIZE];
    501 
    502          /* zlib INPUT BUFFER */
    503          /* The setting of 'avail_in' used to be outside the loop; by setting it
    504           * inside it is possible to chunk the input to zlib and simply rely on
    505           * zlib to advance the 'next_in' pointer.  This allows arbitrary
    506           * amounts of data to be passed through zlib at the unavoidable cost of
    507           * requiring a window save (memcpy of up to 32768 output bytes)
    508           * every ZLIB_IO_MAX input bytes.
    509           */
    510          avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
    511 
    512          avail = ZLIB_IO_MAX;
    513 
    514          if (avail_in < avail)
    515             avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
    516 
    517          avail_in -= avail;
    518          png_ptr->zstream.avail_in = avail;
    519 
    520          /* zlib OUTPUT BUFFER */
    521          avail_out += png_ptr->zstream.avail_out; /* not written last time */
    522 
    523          avail = ZLIB_IO_MAX; /* maximum zlib can process */
    524 
    525          if (output == NULL)
    526          {
    527             /* Reset the output buffer each time round if output is NULL and
    528              * make available the full buffer, up to 'remaining_space'
    529              */
    530             png_ptr->zstream.next_out = local_buffer;
    531             if ((sizeof local_buffer) < avail)
    532                avail = (sizeof local_buffer);
    533          }
    534 
    535          if (avail_out < avail)
    536             avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
    537 
    538          png_ptr->zstream.avail_out = avail;
    539          avail_out -= avail;
    540 
    541          /* zlib inflate call */
    542          /* In fact 'avail_out' may be 0 at this point, that happens at the end
    543           * of the read when the final LZ end code was not passed at the end of
    544           * the previous chunk of input data.  Tell zlib if we have reached the
    545           * end of the output buffer.
    546           */
    547          ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH :
    548             (finish ? Z_FINISH : Z_SYNC_FLUSH));
    549       } while (ret == Z_OK);
    550 
    551       /* For safety kill the local buffer pointer now */
    552       if (output == NULL)
    553          png_ptr->zstream.next_out = NULL;
    554 
    555       /* Claw back the 'size' and 'remaining_space' byte counts. */
    556       avail_in += png_ptr->zstream.avail_in;
    557       avail_out += png_ptr->zstream.avail_out;
    558 
    559       /* Update the input and output sizes; the updated values are the amount
    560        * consumed or written, effectively the inverse of what zlib uses.
    561        */
    562       if (avail_out > 0)
    563          *output_size_ptr -= avail_out;
    564 
    565       if (avail_in > 0)
    566          *input_size_ptr -= avail_in;
    567 
    568       /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
    569       png_zstream_error(png_ptr, ret);
    570       return ret;
    571    }
    572 
    573    else
    574    {
    575       /* This is a bad internal error.  The recovery assigns to the zstream msg
    576        * pointer, which is not owned by the caller, but this is safe; it's only
    577        * used on errors!
    578        */
    579       png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
    580       return Z_STREAM_ERROR;
    581    }
    582 }
    583 
    584 /*
    585  * Decompress trailing data in a chunk.  The assumption is that read_buffer
    586  * points at an allocated area holding the contents of a chunk with a
    587  * trailing compressed part.  What we get back is an allocated area
    588  * holding the original prefix part and an uncompressed version of the
    589  * trailing part (the malloc area passed in is freed).
    590  */
    591 static int
    592 png_decompress_chunk(png_structrp png_ptr,
    593    png_uint_32 chunklength, png_uint_32 prefix_size,
    594    png_alloc_size_t *newlength /* must be initialized to the maximum! */,
    595    int terminate /*add a '\0' to the end of the uncompressed data*/)
    596 {
    597    /* TODO: implement different limits for different types of chunk.
    598     *
    599     * The caller supplies *newlength set to the maximum length of the
    600     * uncompressed data, but this routine allocates space for the prefix and
    601     * maybe a '\0' terminator too.  We have to assume that 'prefix_size' is
    602     * limited only by the maximum chunk size.
    603     */
    604    png_alloc_size_t limit = PNG_SIZE_MAX;
    605 
    606 #  ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
    607       if (png_ptr->user_chunk_malloc_max > 0 &&
    608          png_ptr->user_chunk_malloc_max < limit)
    609          limit = png_ptr->user_chunk_malloc_max;
    610 #  elif PNG_USER_CHUNK_MALLOC_MAX > 0
    611       if (PNG_USER_CHUNK_MALLOC_MAX < limit)
    612          limit = PNG_USER_CHUNK_MALLOC_MAX;
    613 #  endif
    614 
    615    if (limit >= prefix_size + (terminate != 0))
    616    {
    617       int ret;
    618 
    619       limit -= prefix_size + (terminate != 0);
    620 
    621       if (limit < *newlength)
    622          *newlength = limit;
    623 
    624       /* Now try to claim the stream. */
    625       ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
    626 
    627       if (ret == Z_OK)
    628       {
    629          png_uint_32 lzsize = chunklength - prefix_size;
    630 
    631          ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
    632             /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
    633             /* output: */ NULL, newlength);
    634 
    635          if (ret == Z_STREAM_END)
    636          {
    637             /* Use 'inflateReset' here, not 'inflateReset2' because this
    638              * preserves the previously decided window size (otherwise it would
    639              * be necessary to store the previous window size.)  In practice
    640              * this doesn't matter anyway, because png_inflate will call inflate
    641              * with Z_FINISH in almost all cases, so the window will not be
    642              * maintained.
    643              */
    644             if (inflateReset(&png_ptr->zstream) == Z_OK)
    645             {
    646                /* Because of the limit checks above we know that the new,
    647                 * expanded, size will fit in a size_t (let alone an
    648                 * png_alloc_size_t).  Use png_malloc_base here to avoid an
    649                 * extra OOM message.
    650                 */
    651                png_alloc_size_t new_size = *newlength;
    652                png_alloc_size_t buffer_size = prefix_size + new_size +
    653                   (terminate != 0);
    654                png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
    655                   buffer_size));
    656 
    657                if (text != NULL)
    658                {
    659                   ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
    660                      png_ptr->read_buffer + prefix_size, &lzsize,
    661                      text + prefix_size, newlength);
    662 
    663                   if (ret == Z_STREAM_END)
    664                   {
    665                      if (new_size == *newlength)
    666                      {
    667                         if (terminate)
    668                            text[prefix_size + *newlength] = 0;
    669 
    670                         if (prefix_size > 0)
    671                            memcpy(text, png_ptr->read_buffer, prefix_size);
    672 
    673                         {
    674                            png_bytep old_ptr = png_ptr->read_buffer;
    675 
    676                            png_ptr->read_buffer = text;
    677                            png_ptr->read_buffer_size = buffer_size;
    678                            text = old_ptr; /* freed below */
    679                         }
    680                      }
    681 
    682                      else
    683                      {
    684                         /* The size changed on the second read, there can be no
    685                          * guarantee that anything is correct at this point.
    686                          * The 'msg' pointer has been set to "unexpected end of
    687                          * LZ stream", which is fine, but return an error code
    688                          * that the caller won't accept.
    689                          */
    690                         ret = PNG_UNEXPECTED_ZLIB_RETURN;
    691                      }
    692                   }
    693 
    694                   else if (ret == Z_OK)
    695                      ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
    696 
    697                   /* Free the text pointer (this is the old read_buffer on
    698                    * success)
    699                    */
    700                   png_free(png_ptr, text);
    701 
    702                   /* This really is very benign, but it's still an error because
    703                    * the extra space may otherwise be used as a Trojan Horse.
    704                    */
    705                   if (ret == Z_STREAM_END &&
    706                      chunklength - prefix_size != lzsize)
    707                      png_chunk_benign_error(png_ptr, "extra compressed data");
    708                }
    709 
    710                else
    711                {
    712                   /* Out of memory allocating the buffer */
    713                   ret = Z_MEM_ERROR;
    714                   png_zstream_error(png_ptr, Z_MEM_ERROR);
    715                }
    716             }
    717 
    718             else
    719             {
    720                /* inflateReset failed, store the error message */
    721                png_zstream_error(png_ptr, ret);
    722 
    723                if (ret == Z_STREAM_END)
    724                   ret = PNG_UNEXPECTED_ZLIB_RETURN;
    725             }
    726          }
    727 
    728          else if (ret == Z_OK)
    729             ret = PNG_UNEXPECTED_ZLIB_RETURN;
    730 
    731          /* Release the claimed stream */
    732          png_ptr->zowner = 0;
    733       }
    734 
    735       else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
    736          ret = PNG_UNEXPECTED_ZLIB_RETURN;
    737 
    738       return ret;
    739    }
    740 
    741    else
    742    {
    743       /* Application/configuration limits exceeded */
    744       png_zstream_error(png_ptr, Z_MEM_ERROR);
    745       return Z_MEM_ERROR;
    746    }
    747 }
    748 #endif /* PNG_READ_COMPRESSED_TEXT_SUPPORTED */
    749 
    750 #ifdef PNG_READ_iCCP_SUPPORTED
    751 /* Perform a partial read and decompress, producing 'avail_out' bytes and
    752  * reading from the current chunk as required.
    753  */
    754 static int
    755 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
    756    png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
    757    int finish)
    758 {
    759    if (png_ptr->zowner == png_ptr->chunk_name)
    760    {
    761       int ret;
    762 
    763       /* next_in and avail_in must have been initialized by the caller. */
    764       png_ptr->zstream.next_out = next_out;
    765       png_ptr->zstream.avail_out = 0; /* set in the loop */
    766 
    767       do
    768       {
    769          if (png_ptr->zstream.avail_in == 0)
    770          {
    771             if (read_size > *chunk_bytes)
    772                read_size = (uInt)*chunk_bytes;
    773             *chunk_bytes -= read_size;
    774 
    775             if (read_size > 0)
    776                png_crc_read(png_ptr, read_buffer, read_size);
    777 
    778             png_ptr->zstream.next_in = read_buffer;
    779             png_ptr->zstream.avail_in = read_size;
    780          }
    781 
    782          if (png_ptr->zstream.avail_out == 0)
    783          {
    784             uInt avail = ZLIB_IO_MAX;
    785             if (avail > *out_size)
    786                avail = (uInt)*out_size;
    787             *out_size -= avail;
    788 
    789             png_ptr->zstream.avail_out = avail;
    790          }
    791 
    792          /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
    793           * the available output is produced; this allows reading of truncated
    794           * streams.
    795           */
    796          ret = inflate(&png_ptr->zstream,
    797             *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
    798       }
    799       while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
    800 
    801       *out_size += png_ptr->zstream.avail_out;
    802       png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
    803 
    804       /* Ensure the error message pointer is always set: */
    805       png_zstream_error(png_ptr, ret);
    806       return ret;
    807    }
    808 
    809    else
    810    {
    811       png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
    812       return Z_STREAM_ERROR;
    813    }
    814 }
    815 #endif
    816 
    817 /* Read and check the IDHR chunk */
    818 void /* PRIVATE */
    819 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
    820 {
    821    png_byte buf[13];
    822    png_uint_32 width, height;
    823    int bit_depth, color_type, compression_type, filter_type;
    824    int interlace_type;
    825 
    826    png_debug(1, "in png_handle_IHDR");
    827 
    828    if (png_ptr->mode & PNG_HAVE_IHDR)
    829       png_chunk_error(png_ptr, "out of place");
    830 
    831    /* Check the length */
    832    if (length != 13)
    833       png_chunk_error(png_ptr, "invalid");
    834 
    835    png_ptr->mode |= PNG_HAVE_IHDR;
    836 
    837    png_crc_read(png_ptr, buf, 13);
    838    png_crc_finish(png_ptr, 0);
    839 
    840    width = png_get_uint_31(png_ptr, buf);
    841    height = png_get_uint_31(png_ptr, buf + 4);
    842    bit_depth = buf[8];
    843    color_type = buf[9];
    844    compression_type = buf[10];
    845    filter_type = buf[11];
    846    interlace_type = buf[12];
    847 
    848    /* Set internal variables */
    849    png_ptr->width = width;
    850    png_ptr->height = height;
    851    png_ptr->bit_depth = (png_byte)bit_depth;
    852    png_ptr->interlaced = (png_byte)interlace_type;
    853    png_ptr->color_type = (png_byte)color_type;
    854 #ifdef PNG_MNG_FEATURES_SUPPORTED
    855    png_ptr->filter_type = (png_byte)filter_type;
    856 #endif
    857    png_ptr->compression_type = (png_byte)compression_type;
    858 
    859    /* Find number of channels */
    860    switch (png_ptr->color_type)
    861    {
    862       default: /* invalid, png_set_IHDR calls png_error */
    863       case PNG_COLOR_TYPE_GRAY:
    864       case PNG_COLOR_TYPE_PALETTE:
    865          png_ptr->channels = 1;
    866          break;
    867 
    868       case PNG_COLOR_TYPE_RGB:
    869          png_ptr->channels = 3;
    870          break;
    871 
    872       case PNG_COLOR_TYPE_GRAY_ALPHA:
    873          png_ptr->channels = 2;
    874          break;
    875 
    876       case PNG_COLOR_TYPE_RGB_ALPHA:
    877          png_ptr->channels = 4;
    878          break;
    879    }
    880 
    881    /* Set up other useful info */
    882    png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
    883    png_ptr->channels);
    884    png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
    885    png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
    886    png_debug1(3, "channels = %d", png_ptr->channels);
    887    png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
    888    png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
    889        color_type, interlace_type, compression_type, filter_type);
    890 }
    891 
    892 /* Read and check the palette */
    893 void /* PRIVATE */
    894 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
    895 {
    896    png_color palette[PNG_MAX_PALETTE_LENGTH];
    897    int num, i;
    898 #ifdef PNG_POINTER_INDEXING_SUPPORTED
    899    png_colorp pal_ptr;
    900 #endif
    901 
    902    png_debug(1, "in png_handle_PLTE");
    903 
    904    if (!(png_ptr->mode & PNG_HAVE_IHDR))
    905       png_chunk_error(png_ptr, "missing IHDR");
    906 
    907    /* Moved to before the 'after IDAT' check below because otherwise duplicate
    908     * PLTE chunks are potentially ignored (the spec says there shall not be more
    909     * than one PLTE, the error is not treated as benign, so this check trumps
    910     * the requirement that PLTE appears before IDAT.)
    911     */
    912    else if (png_ptr->mode & PNG_HAVE_PLTE)
    913       png_chunk_error(png_ptr, "duplicate");
    914 
    915    else if (png_ptr->mode & PNG_HAVE_IDAT)
    916    {
    917       /* This is benign because the non-benign error happened before, when an
    918        * IDAT was encountered in a color-mapped image with no PLTE.
    919        */
    920       png_crc_finish(png_ptr, length);
    921       png_chunk_benign_error(png_ptr, "out of place");
    922       return;
    923    }
    924 
    925    png_ptr->mode |= PNG_HAVE_PLTE;
    926 
    927    if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR))
    928    {
    929       png_crc_finish(png_ptr, length);
    930       png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
    931       return;
    932    }
    933 
    934 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
    935    if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
    936    {
    937       png_crc_finish(png_ptr, length);
    938       return;
    939    }
    940 #endif
    941 
    942    if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
    943    {
    944       png_crc_finish(png_ptr, length);
    945 
    946       if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
    947          png_chunk_benign_error(png_ptr, "invalid");
    948 
    949       else
    950          png_chunk_error(png_ptr, "invalid");
    951 
    952       return;
    953    }
    954 
    955    /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
    956    num = (int)length / 3;
    957 
    958 #ifdef PNG_POINTER_INDEXING_SUPPORTED
    959    for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
    960    {
    961       png_byte buf[3];
    962 
    963       png_crc_read(png_ptr, buf, 3);
    964       pal_ptr->red = buf[0];
    965       pal_ptr->green = buf[1];
    966       pal_ptr->blue = buf[2];
    967    }
    968 #else
    969    for (i = 0; i < num; i++)
    970    {
    971       png_byte buf[3];
    972 
    973       png_crc_read(png_ptr, buf, 3);
    974       /* Don't depend upon png_color being any order */
    975       palette[i].red = buf[0];
    976       palette[i].green = buf[1];
    977       palette[i].blue = buf[2];
    978    }
    979 #endif
    980 
    981    /* If we actually need the PLTE chunk (ie for a paletted image), we do
    982     * whatever the normal CRC configuration tells us.  However, if we
    983     * have an RGB image, the PLTE can be considered ancillary, so
    984     * we will act as though it is.
    985     */
    986 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
    987    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
    988 #endif
    989    {
    990       png_crc_finish(png_ptr, 0);
    991    }
    992 
    993 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
    994    else if (png_crc_error(png_ptr))  /* Only if we have a CRC error */
    995    {
    996       /* If we don't want to use the data from an ancillary chunk,
    997        * we have two options: an error abort, or a warning and we
    998        * ignore the data in this chunk (which should be OK, since
    999        * it's considered ancillary for a RGB or RGBA image).
   1000        *
   1001        * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
   1002        * chunk type to determine whether to check the ancillary or the critical
   1003        * flags.
   1004        */
   1005       if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
   1006       {
   1007          if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
   1008             return;
   1009 
   1010          else
   1011             png_chunk_error(png_ptr, "CRC error");
   1012       }
   1013 
   1014       /* Otherwise, we (optionally) emit a warning and use the chunk. */
   1015       else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
   1016          png_chunk_warning(png_ptr, "CRC error");
   1017    }
   1018 #endif
   1019 
   1020    /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
   1021     * own copy of the palette.  This has the side effect that when png_start_row
   1022     * is called (this happens after any call to png_read_update_info) the
   1023     * info_ptr palette gets changed.  This is extremely unexpected and
   1024     * confusing.
   1025     *
   1026     * Fix this by not sharing the palette in this way.
   1027     */
   1028    png_set_PLTE(png_ptr, info_ptr, palette, num);
   1029 
   1030    /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
   1031     * IDAT.  Prior to 1.6.0 this was not checked; instead the code merely
   1032     * checked the apparent validity of a tRNS chunk inserted before PLTE on a
   1033     * palette PNG.  1.6.0 attempts to rigorously follow the standard and
   1034     * therefore does a benign error if the erroneous condition is detected *and*
   1035     * cancels the tRNS if the benign error returns.  The alternative is to
   1036     * amend the standard since it would be rather hypocritical of the standards
   1037     * maintainers to ignore it.
   1038     */
   1039 #ifdef PNG_READ_tRNS_SUPPORTED
   1040    if (png_ptr->num_trans > 0 ||
   1041       (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
   1042    {
   1043       /* Cancel this because otherwise it would be used if the transforms
   1044        * require it.  Don't cancel the 'valid' flag because this would prevent
   1045        * detection of duplicate chunks.
   1046        */
   1047       png_ptr->num_trans = 0;
   1048 
   1049       if (info_ptr != NULL)
   1050          info_ptr->num_trans = 0;
   1051 
   1052       png_chunk_benign_error(png_ptr, "tRNS must be after");
   1053    }
   1054 #endif
   1055 
   1056 #ifdef PNG_READ_hIST_SUPPORTED
   1057    if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
   1058       png_chunk_benign_error(png_ptr, "hIST must be after");
   1059 #endif
   1060 
   1061 #ifdef PNG_READ_bKGD_SUPPORTED
   1062    if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
   1063       png_chunk_benign_error(png_ptr, "bKGD must be after");
   1064 #endif
   1065 }
   1066 
   1067 void /* PRIVATE */
   1068 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1069 {
   1070    png_debug(1, "in png_handle_IEND");
   1071 
   1072    if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
   1073       png_chunk_error(png_ptr, "out of place");
   1074 
   1075    png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
   1076 
   1077    png_crc_finish(png_ptr, length);
   1078 
   1079    if (length != 0)
   1080       png_chunk_benign_error(png_ptr, "invalid");
   1081 
   1082    PNG_UNUSED(info_ptr)
   1083 }
   1084 
   1085 #ifdef PNG_READ_gAMA_SUPPORTED
   1086 void /* PRIVATE */
   1087 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1088 {
   1089    png_fixed_point igamma;
   1090    png_byte buf[4];
   1091 
   1092    png_debug(1, "in png_handle_gAMA");
   1093 
   1094    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1095       png_chunk_error(png_ptr, "missing IHDR");
   1096 
   1097    else if (png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE))
   1098    {
   1099       png_crc_finish(png_ptr, length);
   1100       png_chunk_benign_error(png_ptr, "out of place");
   1101       return;
   1102    }
   1103 
   1104    if (length != 4)
   1105    {
   1106       png_crc_finish(png_ptr, length);
   1107       png_chunk_benign_error(png_ptr, "invalid");
   1108       return;
   1109    }
   1110 
   1111    png_crc_read(png_ptr, buf, 4);
   1112 
   1113    if (png_crc_finish(png_ptr, 0))
   1114       return;
   1115 
   1116    igamma = png_get_fixed_point(NULL, buf);
   1117 
   1118    png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
   1119    png_colorspace_sync(png_ptr, info_ptr);
   1120 }
   1121 #endif
   1122 
   1123 #ifdef PNG_READ_sBIT_SUPPORTED
   1124 void /* PRIVATE */
   1125 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1126 {
   1127    unsigned int truelen, i;
   1128    png_byte sample_depth;
   1129    png_byte buf[4];
   1130 
   1131    png_debug(1, "in png_handle_sBIT");
   1132 
   1133    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1134       png_chunk_error(png_ptr, "missing IHDR");
   1135 
   1136    else if (png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE))
   1137    {
   1138       png_crc_finish(png_ptr, length);
   1139       png_chunk_benign_error(png_ptr, "out of place");
   1140       return;
   1141    }
   1142 
   1143    if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
   1144    {
   1145       png_crc_finish(png_ptr, length);
   1146       png_chunk_benign_error(png_ptr, "duplicate");
   1147       return;
   1148    }
   1149 
   1150    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   1151    {
   1152       truelen = 3;
   1153       sample_depth = 8;
   1154    }
   1155 
   1156    else
   1157    {
   1158       truelen = png_ptr->channels;
   1159       sample_depth = png_ptr->bit_depth;
   1160    }
   1161 
   1162    if (length != truelen || length > 4)
   1163    {
   1164       png_chunk_benign_error(png_ptr, "invalid");
   1165       png_crc_finish(png_ptr, length);
   1166       return;
   1167    }
   1168 
   1169    buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
   1170    png_crc_read(png_ptr, buf, truelen);
   1171 
   1172    if (png_crc_finish(png_ptr, 0))
   1173       return;
   1174 
   1175    for (i=0; i<truelen; ++i)
   1176       if (buf[i] == 0 || buf[i] > sample_depth)
   1177       {
   1178          png_chunk_benign_error(png_ptr, "invalid");
   1179          return;
   1180       }
   1181 
   1182    if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
   1183    {
   1184       png_ptr->sig_bit.red = buf[0];
   1185       png_ptr->sig_bit.green = buf[1];
   1186       png_ptr->sig_bit.blue = buf[2];
   1187       png_ptr->sig_bit.alpha = buf[3];
   1188    }
   1189 
   1190    else
   1191    {
   1192       png_ptr->sig_bit.gray = buf[0];
   1193       png_ptr->sig_bit.red = buf[0];
   1194       png_ptr->sig_bit.green = buf[0];
   1195       png_ptr->sig_bit.blue = buf[0];
   1196       png_ptr->sig_bit.alpha = buf[1];
   1197    }
   1198 
   1199    png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
   1200 }
   1201 #endif
   1202 
   1203 #ifdef PNG_READ_cHRM_SUPPORTED
   1204 void /* PRIVATE */
   1205 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1206 {
   1207    png_byte buf[32];
   1208    png_xy xy;
   1209 
   1210    png_debug(1, "in png_handle_cHRM");
   1211 
   1212    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1213       png_chunk_error(png_ptr, "missing IHDR");
   1214 
   1215    else if (png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE))
   1216    {
   1217       png_crc_finish(png_ptr, length);
   1218       png_chunk_benign_error(png_ptr, "out of place");
   1219       return;
   1220    }
   1221 
   1222    if (length != 32)
   1223    {
   1224       png_crc_finish(png_ptr, length);
   1225       png_chunk_benign_error(png_ptr, "invalid");
   1226       return;
   1227    }
   1228 
   1229    png_crc_read(png_ptr, buf, 32);
   1230 
   1231    if (png_crc_finish(png_ptr, 0))
   1232       return;
   1233 
   1234    xy.whitex = png_get_fixed_point(NULL, buf);
   1235    xy.whitey = png_get_fixed_point(NULL, buf + 4);
   1236    xy.redx   = png_get_fixed_point(NULL, buf + 8);
   1237    xy.redy   = png_get_fixed_point(NULL, buf + 12);
   1238    xy.greenx = png_get_fixed_point(NULL, buf + 16);
   1239    xy.greeny = png_get_fixed_point(NULL, buf + 20);
   1240    xy.bluex  = png_get_fixed_point(NULL, buf + 24);
   1241    xy.bluey  = png_get_fixed_point(NULL, buf + 28);
   1242 
   1243    if (xy.whitex == PNG_FIXED_ERROR ||
   1244        xy.whitey == PNG_FIXED_ERROR ||
   1245        xy.redx   == PNG_FIXED_ERROR ||
   1246        xy.redy   == PNG_FIXED_ERROR ||
   1247        xy.greenx == PNG_FIXED_ERROR ||
   1248        xy.greeny == PNG_FIXED_ERROR ||
   1249        xy.bluex  == PNG_FIXED_ERROR ||
   1250        xy.bluey  == PNG_FIXED_ERROR)
   1251    {
   1252       png_chunk_benign_error(png_ptr, "invalid values");
   1253       return;
   1254    }
   1255 
   1256    /* If a colorspace error has already been output skip this chunk */
   1257    if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
   1258       return;
   1259 
   1260    if (png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM)
   1261    {
   1262       png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
   1263       png_colorspace_sync(png_ptr, info_ptr);
   1264       png_chunk_benign_error(png_ptr, "duplicate");
   1265       return;
   1266    }
   1267 
   1268    png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
   1269    (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
   1270       1/*prefer cHRM values*/);
   1271    png_colorspace_sync(png_ptr, info_ptr);
   1272 }
   1273 #endif
   1274 
   1275 #ifdef PNG_READ_sRGB_SUPPORTED
   1276 void /* PRIVATE */
   1277 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1278 {
   1279    png_byte intent;
   1280 
   1281    png_debug(1, "in png_handle_sRGB");
   1282 
   1283    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1284       png_chunk_error(png_ptr, "missing IHDR");
   1285 
   1286    else if (png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE))
   1287    {
   1288       png_crc_finish(png_ptr, length);
   1289       png_chunk_benign_error(png_ptr, "out of place");
   1290       return;
   1291    }
   1292 
   1293    if (length != 1)
   1294    {
   1295       png_crc_finish(png_ptr, length);
   1296       png_chunk_benign_error(png_ptr, "invalid");
   1297       return;
   1298    }
   1299 
   1300    png_crc_read(png_ptr, &intent, 1);
   1301 
   1302    if (png_crc_finish(png_ptr, 0))
   1303       return;
   1304 
   1305    /* If a colorspace error has already been output skip this chunk */
   1306    if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
   1307       return;
   1308 
   1309    /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
   1310     * this.
   1311     */
   1312    if (png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT)
   1313    {
   1314       png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
   1315       png_colorspace_sync(png_ptr, info_ptr);
   1316       png_chunk_benign_error(png_ptr, "too many profiles");
   1317       return;
   1318    }
   1319 
   1320    (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
   1321    png_colorspace_sync(png_ptr, info_ptr);
   1322 }
   1323 #endif /* PNG_READ_sRGB_SUPPORTED */
   1324 
   1325 #ifdef PNG_READ_iCCP_SUPPORTED
   1326 void /* PRIVATE */
   1327 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1328 /* Note: this does not properly handle profiles that are > 64K under DOS */
   1329 {
   1330    png_const_charp errmsg = NULL; /* error message output, or no error */
   1331    int finished = 0; /* crc checked */
   1332 
   1333    png_debug(1, "in png_handle_iCCP");
   1334 
   1335    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1336       png_chunk_error(png_ptr, "missing IHDR");
   1337 
   1338    else if (png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE))
   1339    {
   1340       png_crc_finish(png_ptr, length);
   1341       png_chunk_benign_error(png_ptr, "out of place");
   1342       return;
   1343    }
   1344 
   1345    /* Consistent with all the above colorspace handling an obviously *invalid*
   1346     * chunk is just ignored, so does not invalidate the color space.  An
   1347     * alternative is to set the 'invalid' flags at the start of this routine
   1348     * and only clear them in they were not set before and all the tests pass.
   1349     * The minimum 'deflate' stream is assumed to be just the 2 byte header and 4
   1350     * byte checksum.  The keyword must be one character and there is a
   1351     * terminator (0) byte and the compression method.
   1352     */
   1353    if (length < 9)
   1354    {
   1355       png_crc_finish(png_ptr, length);
   1356       png_chunk_benign_error(png_ptr, "too short");
   1357       return;
   1358    }
   1359 
   1360    /* If a colorspace error has already been output skip this chunk */
   1361    if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
   1362    {
   1363       png_crc_finish(png_ptr, length);
   1364       return;
   1365    }
   1366 
   1367    /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
   1368     * this.
   1369     */
   1370    if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
   1371    {
   1372       uInt read_length, keyword_length;
   1373       char keyword[81];
   1374 
   1375       /* Find the keyword; the keyword plus separator and compression method
   1376        * bytes can be at most 81 characters long.
   1377        */
   1378       read_length = 81; /* maximum */
   1379       if (read_length > length)
   1380          read_length = (uInt)length;
   1381 
   1382       png_crc_read(png_ptr, (png_bytep)keyword, read_length);
   1383       length -= read_length;
   1384 
   1385       keyword_length = 0;
   1386       while (keyword_length < 80 && keyword_length < read_length &&
   1387          keyword[keyword_length] != 0)
   1388          ++keyword_length;
   1389 
   1390       /* TODO: make the keyword checking common */
   1391       if (keyword_length >= 1 && keyword_length <= 79)
   1392       {
   1393          /* We only understand '0' compression - deflate - so if we get a
   1394           * different value we can't safely decode the chunk.
   1395           */
   1396          if (keyword_length+1 < read_length &&
   1397             keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
   1398          {
   1399             read_length -= keyword_length+2;
   1400 
   1401             if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
   1402             {
   1403                Byte profile_header[132];
   1404                Byte local_buffer[PNG_INFLATE_BUF_SIZE];
   1405                png_alloc_size_t size = (sizeof profile_header);
   1406 
   1407                png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
   1408                png_ptr->zstream.avail_in = read_length;
   1409                (void)png_inflate_read(png_ptr, local_buffer,
   1410                   (sizeof local_buffer), &length, profile_header, &size,
   1411                   0/*finish: don't, because the output is too small*/);
   1412 
   1413                if (size == 0)
   1414                {
   1415                   /* We have the ICC profile header; do the basic header checks.
   1416                    */
   1417                   const png_uint_32 profile_length =
   1418                      png_get_uint_32(profile_header);
   1419 
   1420                   if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
   1421                      keyword, profile_length))
   1422                   {
   1423                      /* The length is apparently ok, so we can check the 132
   1424                       * byte header.
   1425                       */
   1426                      if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
   1427                         keyword, profile_length, profile_header,
   1428                         png_ptr->color_type))
   1429                      {
   1430                         /* Now read the tag table; a variable size buffer is
   1431                          * needed at this point, allocate one for the whole
   1432                          * profile.  The header check has already validated
   1433                          * that none of these stuff will overflow.
   1434                          */
   1435                         const png_uint_32 tag_count = png_get_uint_32(
   1436                            profile_header+128);
   1437                         png_bytep profile = png_read_buffer(png_ptr,
   1438                            profile_length, 2/*silent*/);
   1439 
   1440                         if (profile != NULL)
   1441                         {
   1442                            memcpy(profile, profile_header,
   1443                               (sizeof profile_header));
   1444 
   1445                            size = 12 * tag_count;
   1446 
   1447                            (void)png_inflate_read(png_ptr, local_buffer,
   1448                               (sizeof local_buffer), &length,
   1449                               profile + (sizeof profile_header), &size, 0);
   1450 
   1451                            /* Still expect a buffer error because we expect
   1452                             * there to be some tag data!
   1453                             */
   1454                            if (size == 0)
   1455                            {
   1456                               if (png_icc_check_tag_table(png_ptr,
   1457                                  &png_ptr->colorspace, keyword, profile_length,
   1458                                  profile))
   1459                               {
   1460                                  /* The profile has been validated for basic
   1461                                   * security issues, so read the whole thing in.
   1462                                   */
   1463                                  size = profile_length - (sizeof profile_header)
   1464                                     - 12 * tag_count;
   1465 
   1466                                  (void)png_inflate_read(png_ptr, local_buffer,
   1467                                     (sizeof local_buffer), &length,
   1468                                     profile + (sizeof profile_header) +
   1469                                     12 * tag_count, &size, 1/*finish*/);
   1470 
   1471                                  if (length > 0 && !(png_ptr->flags &
   1472                                        PNG_FLAG_BENIGN_ERRORS_WARN))
   1473                                     errmsg = "extra compressed data";
   1474 
   1475                                  /* But otherwise allow extra data: */
   1476                                  else if (size == 0)
   1477                                  {
   1478                                     if (length > 0)
   1479                                     {
   1480                                        /* This can be handled completely, so
   1481                                         * keep going.
   1482                                         */
   1483                                        png_chunk_warning(png_ptr,
   1484                                           "extra compressed data");
   1485                                     }
   1486 
   1487                                     png_crc_finish(png_ptr, length);
   1488                                     finished = 1;
   1489 
   1490 #                                   ifdef PNG_sRGB_SUPPORTED
   1491                                        /* Check for a match against sRGB */
   1492                                        png_icc_set_sRGB(png_ptr,
   1493                                           &png_ptr->colorspace, profile,
   1494                                           png_ptr->zstream.adler);
   1495 #                                   endif
   1496 
   1497                                     /* Steal the profile for info_ptr. */
   1498                                     if (info_ptr != NULL)
   1499                                     {
   1500                                        png_free_data(png_ptr, info_ptr,
   1501                                           PNG_FREE_ICCP, 0);
   1502 
   1503                                        info_ptr->iccp_name = png_voidcast(char*,
   1504                                           png_malloc_base(png_ptr,
   1505                                           keyword_length+1));
   1506                                        if (info_ptr->iccp_name != NULL)
   1507                                        {
   1508                                           memcpy(info_ptr->iccp_name, keyword,
   1509                                              keyword_length+1);
   1510                                           info_ptr->iccp_proflen =
   1511                                              profile_length;
   1512                                           info_ptr->iccp_profile = profile;
   1513                                           png_ptr->read_buffer = NULL; /*steal*/
   1514                                           info_ptr->free_me |= PNG_FREE_ICCP;
   1515                                           info_ptr->valid |= PNG_INFO_iCCP;
   1516                                        }
   1517 
   1518                                        else
   1519                                        {
   1520                                           png_ptr->colorspace.flags |=
   1521                                              PNG_COLORSPACE_INVALID;
   1522                                           errmsg = "out of memory";
   1523                                        }
   1524                                     }
   1525 
   1526                                     /* else the profile remains in the read
   1527                                      * buffer which gets reused for subsequent
   1528                                      * chunks.
   1529                                      */
   1530 
   1531                                     if (info_ptr != NULL)
   1532                                        png_colorspace_sync(png_ptr, info_ptr);
   1533 
   1534                                     if (errmsg == NULL)
   1535                                     {
   1536                                        png_ptr->zowner = 0;
   1537                                        return;
   1538                                     }
   1539                                  }
   1540 
   1541                                  else if (size > 0)
   1542                                     errmsg = "truncated";
   1543 
   1544                                  else
   1545                                     errmsg = png_ptr->zstream.msg;
   1546                               }
   1547 
   1548                               /* else png_icc_check_tag_table output an error */
   1549                            }
   1550 
   1551                            else /* profile truncated */
   1552                               errmsg = png_ptr->zstream.msg;
   1553                         }
   1554 
   1555                         else
   1556                            errmsg = "out of memory";
   1557                      }
   1558 
   1559                      /* else png_icc_check_header output an error */
   1560                   }
   1561 
   1562                   /* else png_icc_check_length output an error */
   1563                }
   1564 
   1565                else /* profile truncated */
   1566                   errmsg = png_ptr->zstream.msg;
   1567 
   1568                /* Release the stream */
   1569                png_ptr->zowner = 0;
   1570             }
   1571 
   1572             else /* png_inflate_claim failed */
   1573                errmsg = png_ptr->zstream.msg;
   1574          }
   1575 
   1576          else
   1577             errmsg = "bad compression method"; /* or missing */
   1578       }
   1579 
   1580       else
   1581          errmsg = "bad keyword";
   1582    }
   1583 
   1584    else
   1585       errmsg = "too many profiles";
   1586 
   1587    /* Failure: the reason is in 'errmsg' */
   1588    if (!finished)
   1589       png_crc_finish(png_ptr, length);
   1590 
   1591    png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
   1592    png_colorspace_sync(png_ptr, info_ptr);
   1593    if (errmsg != NULL) /* else already output */
   1594       png_chunk_benign_error(png_ptr, errmsg);
   1595 }
   1596 #endif /* PNG_READ_iCCP_SUPPORTED */
   1597 
   1598 #ifdef PNG_READ_sPLT_SUPPORTED
   1599 void /* PRIVATE */
   1600 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1601 /* Note: this does not properly handle chunks that are > 64K under DOS */
   1602 {
   1603    png_bytep entry_start, buffer;
   1604    png_sPLT_t new_palette;
   1605    png_sPLT_entryp pp;
   1606    png_uint_32 data_length;
   1607    int entry_size, i;
   1608    png_uint_32 skip = 0;
   1609    png_uint_32 dl;
   1610    png_size_t max_dl;
   1611 
   1612    png_debug(1, "in png_handle_sPLT");
   1613 
   1614 #ifdef PNG_USER_LIMITS_SUPPORTED
   1615    if (png_ptr->user_chunk_cache_max != 0)
   1616    {
   1617       if (png_ptr->user_chunk_cache_max == 1)
   1618       {
   1619          png_crc_finish(png_ptr, length);
   1620          return;
   1621       }
   1622 
   1623       if (--png_ptr->user_chunk_cache_max == 1)
   1624       {
   1625          png_warning(png_ptr, "No space in chunk cache for sPLT");
   1626          png_crc_finish(png_ptr, length);
   1627          return;
   1628       }
   1629    }
   1630 #endif
   1631 
   1632    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1633       png_chunk_error(png_ptr, "missing IHDR");
   1634 
   1635    else if (png_ptr->mode & PNG_HAVE_IDAT)
   1636    {
   1637       png_crc_finish(png_ptr, length);
   1638       png_chunk_benign_error(png_ptr, "out of place");
   1639       return;
   1640    }
   1641 
   1642 #ifdef PNG_MAX_MALLOC_64K
   1643    if (length > 65535U)
   1644    {
   1645       png_crc_finish(png_ptr, length);
   1646       png_chunk_benign_error(png_ptr, "too large to fit in memory");
   1647       return;
   1648    }
   1649 #endif
   1650 
   1651    buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
   1652    if (buffer == NULL)
   1653    {
   1654       png_crc_finish(png_ptr, length);
   1655       png_chunk_benign_error(png_ptr, "out of memory");
   1656       return;
   1657    }
   1658 
   1659 
   1660    /* WARNING: this may break if size_t is less than 32 bits; it is assumed
   1661     * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
   1662     * potential breakage point if the types in pngconf.h aren't exactly right.
   1663     */
   1664    png_crc_read(png_ptr, buffer, length);
   1665 
   1666    if (png_crc_finish(png_ptr, skip))
   1667       return;
   1668 
   1669    buffer[length] = 0;
   1670 
   1671    for (entry_start = buffer; *entry_start; entry_start++)
   1672       /* Empty loop to find end of name */ ;
   1673 
   1674    ++entry_start;
   1675 
   1676    /* A sample depth should follow the separator, and we should be on it  */
   1677    if (entry_start > buffer + length - 2)
   1678    {
   1679       png_warning(png_ptr, "malformed sPLT chunk");
   1680       return;
   1681    }
   1682 
   1683    new_palette.depth = *entry_start++;
   1684    entry_size = (new_palette.depth == 8 ? 6 : 10);
   1685    /* This must fit in a png_uint_32 because it is derived from the original
   1686     * chunk data length.
   1687     */
   1688    data_length = length - (png_uint_32)(entry_start - buffer);
   1689 
   1690    /* Integrity-check the data length */
   1691    if (data_length % entry_size)
   1692    {
   1693       png_warning(png_ptr, "sPLT chunk has bad length");
   1694       return;
   1695    }
   1696 
   1697    dl = (png_int_32)(data_length / entry_size);
   1698    max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
   1699 
   1700    if (dl > max_dl)
   1701    {
   1702        png_warning(png_ptr, "sPLT chunk too long");
   1703        return;
   1704    }
   1705 
   1706    new_palette.nentries = (png_int_32)(data_length / entry_size);
   1707 
   1708    new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
   1709        png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
   1710 
   1711    if (new_palette.entries == NULL)
   1712    {
   1713        png_warning(png_ptr, "sPLT chunk requires too much memory");
   1714        return;
   1715    }
   1716 
   1717 #ifdef PNG_POINTER_INDEXING_SUPPORTED
   1718    for (i = 0; i < new_palette.nentries; i++)
   1719    {
   1720       pp = new_palette.entries + i;
   1721 
   1722       if (new_palette.depth == 8)
   1723       {
   1724          pp->red = *entry_start++;
   1725          pp->green = *entry_start++;
   1726          pp->blue = *entry_start++;
   1727          pp->alpha = *entry_start++;
   1728       }
   1729 
   1730       else
   1731       {
   1732          pp->red   = png_get_uint_16(entry_start); entry_start += 2;
   1733          pp->green = png_get_uint_16(entry_start); entry_start += 2;
   1734          pp->blue  = png_get_uint_16(entry_start); entry_start += 2;
   1735          pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
   1736       }
   1737 
   1738       pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
   1739    }
   1740 #else
   1741    pp = new_palette.entries;
   1742 
   1743    for (i = 0; i < new_palette.nentries; i++)
   1744    {
   1745 
   1746       if (new_palette.depth == 8)
   1747       {
   1748          pp[i].red   = *entry_start++;
   1749          pp[i].green = *entry_start++;
   1750          pp[i].blue  = *entry_start++;
   1751          pp[i].alpha = *entry_start++;
   1752       }
   1753 
   1754       else
   1755       {
   1756          pp[i].red   = png_get_uint_16(entry_start); entry_start += 2;
   1757          pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
   1758          pp[i].blue  = png_get_uint_16(entry_start); entry_start += 2;
   1759          pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
   1760       }
   1761 
   1762       pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
   1763    }
   1764 #endif
   1765 
   1766    /* Discard all chunk data except the name and stash that */
   1767    new_palette.name = (png_charp)buffer;
   1768 
   1769    png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
   1770 
   1771    png_free(png_ptr, new_palette.entries);
   1772 }
   1773 #endif /* PNG_READ_sPLT_SUPPORTED */
   1774 
   1775 #ifdef PNG_READ_tRNS_SUPPORTED
   1776 void /* PRIVATE */
   1777 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1778 {
   1779    png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
   1780 
   1781    png_debug(1, "in png_handle_tRNS");
   1782 
   1783    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1784       png_chunk_error(png_ptr, "missing IHDR");
   1785 
   1786    else if (png_ptr->mode & PNG_HAVE_IDAT)
   1787    {
   1788       png_crc_finish(png_ptr, length);
   1789       png_chunk_benign_error(png_ptr, "out of place");
   1790       return;
   1791    }
   1792 
   1793    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
   1794    {
   1795       png_crc_finish(png_ptr, length);
   1796       png_chunk_benign_error(png_ptr, "duplicate");
   1797       return;
   1798    }
   1799 
   1800    if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
   1801    {
   1802       png_byte buf[2];
   1803 
   1804       if (length != 2)
   1805       {
   1806          png_crc_finish(png_ptr, length);
   1807          png_chunk_benign_error(png_ptr, "invalid");
   1808          return;
   1809       }
   1810 
   1811       png_crc_read(png_ptr, buf, 2);
   1812       png_ptr->num_trans = 1;
   1813       png_ptr->trans_color.gray = png_get_uint_16(buf);
   1814    }
   1815 
   1816    else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
   1817    {
   1818       png_byte buf[6];
   1819 
   1820       if (length != 6)
   1821       {
   1822          png_crc_finish(png_ptr, length);
   1823          png_chunk_benign_error(png_ptr, "invalid");
   1824          return;
   1825       }
   1826 
   1827       png_crc_read(png_ptr, buf, length);
   1828       png_ptr->num_trans = 1;
   1829       png_ptr->trans_color.red = png_get_uint_16(buf);
   1830       png_ptr->trans_color.green = png_get_uint_16(buf + 2);
   1831       png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
   1832    }
   1833 
   1834    else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   1835    {
   1836       if (!(png_ptr->mode & PNG_HAVE_PLTE))
   1837       {
   1838          /* TODO: is this actually an error in the ISO spec? */
   1839          png_crc_finish(png_ptr, length);
   1840          png_chunk_benign_error(png_ptr, "out of place");
   1841          return;
   1842       }
   1843 
   1844       if (length > png_ptr->num_palette || length > PNG_MAX_PALETTE_LENGTH ||
   1845          length == 0)
   1846       {
   1847          png_crc_finish(png_ptr, length);
   1848          png_chunk_benign_error(png_ptr, "invalid");
   1849          return;
   1850       }
   1851 
   1852       png_crc_read(png_ptr, readbuf, length);
   1853       png_ptr->num_trans = (png_uint_16)length;
   1854    }
   1855 
   1856    else
   1857    {
   1858       png_crc_finish(png_ptr, length);
   1859       png_chunk_benign_error(png_ptr, "invalid with alpha channel");
   1860       return;
   1861    }
   1862 
   1863    if (png_crc_finish(png_ptr, 0))
   1864    {
   1865       png_ptr->num_trans = 0;
   1866       return;
   1867    }
   1868 
   1869    /* TODO: this is a horrible side effect in the palette case because the
   1870     * png_struct ends up with a pointer to the tRNS buffer owned by the
   1871     * png_info.  Fix this.
   1872     */
   1873    png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
   1874        &(png_ptr->trans_color));
   1875 }
   1876 #endif
   1877 
   1878 #ifdef PNG_READ_bKGD_SUPPORTED
   1879 void /* PRIVATE */
   1880 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1881 {
   1882    unsigned int truelen;
   1883    png_byte buf[6];
   1884    png_color_16 background;
   1885 
   1886    png_debug(1, "in png_handle_bKGD");
   1887 
   1888    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1889       png_chunk_error(png_ptr, "missing IHDR");
   1890 
   1891    else if ((png_ptr->mode & PNG_HAVE_IDAT) ||
   1892       (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
   1893        !(png_ptr->mode & PNG_HAVE_PLTE)))
   1894    {
   1895       png_crc_finish(png_ptr, length);
   1896       png_chunk_benign_error(png_ptr, "out of place");
   1897       return;
   1898    }
   1899 
   1900    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
   1901    {
   1902       png_crc_finish(png_ptr, length);
   1903       png_chunk_benign_error(png_ptr, "duplicate");
   1904       return;
   1905    }
   1906 
   1907    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   1908       truelen = 1;
   1909 
   1910    else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
   1911       truelen = 6;
   1912 
   1913    else
   1914       truelen = 2;
   1915 
   1916    if (length != truelen)
   1917    {
   1918       png_crc_finish(png_ptr, length);
   1919       png_chunk_benign_error(png_ptr, "invalid");
   1920       return;
   1921    }
   1922 
   1923    png_crc_read(png_ptr, buf, truelen);
   1924 
   1925    if (png_crc_finish(png_ptr, 0))
   1926       return;
   1927 
   1928    /* We convert the index value into RGB components so that we can allow
   1929     * arbitrary RGB values for background when we have transparency, and
   1930     * so it is easy to determine the RGB values of the background color
   1931     * from the info_ptr struct.
   1932     */
   1933    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   1934    {
   1935       background.index = buf[0];
   1936 
   1937       if (info_ptr && info_ptr->num_palette)
   1938       {
   1939          if (buf[0] >= info_ptr->num_palette)
   1940          {
   1941             png_chunk_benign_error(png_ptr, "invalid index");
   1942             return;
   1943          }
   1944 
   1945          background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
   1946          background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
   1947          background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
   1948       }
   1949 
   1950       else
   1951          background.red = background.green = background.blue = 0;
   1952 
   1953       background.gray = 0;
   1954    }
   1955 
   1956    else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
   1957    {
   1958       background.index = 0;
   1959       background.red =
   1960       background.green =
   1961       background.blue =
   1962       background.gray = png_get_uint_16(buf);
   1963    }
   1964 
   1965    else
   1966    {
   1967       background.index = 0;
   1968       background.red = png_get_uint_16(buf);
   1969       background.green = png_get_uint_16(buf + 2);
   1970       background.blue = png_get_uint_16(buf + 4);
   1971       background.gray = 0;
   1972    }
   1973 
   1974    png_set_bKGD(png_ptr, info_ptr, &background);
   1975 }
   1976 #endif
   1977 
   1978 #ifdef PNG_READ_hIST_SUPPORTED
   1979 void /* PRIVATE */
   1980 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   1981 {
   1982    unsigned int num, i;
   1983    png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
   1984 
   1985    png_debug(1, "in png_handle_hIST");
   1986 
   1987    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   1988       png_chunk_error(png_ptr, "missing IHDR");
   1989 
   1990    else if ((png_ptr->mode & PNG_HAVE_IDAT) || !(png_ptr->mode & PNG_HAVE_PLTE))
   1991    {
   1992       png_crc_finish(png_ptr, length);
   1993       png_chunk_benign_error(png_ptr, "out of place");
   1994       return;
   1995    }
   1996 
   1997    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
   1998    {
   1999       png_crc_finish(png_ptr, length);
   2000       png_chunk_benign_error(png_ptr, "duplicate");
   2001       return;
   2002    }
   2003 
   2004    num = length / 2 ;
   2005 
   2006    if (num != png_ptr->num_palette || num > PNG_MAX_PALETTE_LENGTH)
   2007    {
   2008       png_crc_finish(png_ptr, length);
   2009       png_chunk_benign_error(png_ptr, "invalid");
   2010       return;
   2011    }
   2012 
   2013    for (i = 0; i < num; i++)
   2014    {
   2015       png_byte buf[2];
   2016 
   2017       png_crc_read(png_ptr, buf, 2);
   2018       readbuf[i] = png_get_uint_16(buf);
   2019    }
   2020 
   2021    if (png_crc_finish(png_ptr, 0))
   2022       return;
   2023 
   2024    png_set_hIST(png_ptr, info_ptr, readbuf);
   2025 }
   2026 #endif
   2027 
   2028 #ifdef PNG_READ_pHYs_SUPPORTED
   2029 void /* PRIVATE */
   2030 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2031 {
   2032    png_byte buf[9];
   2033    png_uint_32 res_x, res_y;
   2034    int unit_type;
   2035 
   2036    png_debug(1, "in png_handle_pHYs");
   2037 
   2038    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2039       png_chunk_error(png_ptr, "missing IHDR");
   2040 
   2041    else if (png_ptr->mode & PNG_HAVE_IDAT)
   2042    {
   2043       png_crc_finish(png_ptr, length);
   2044       png_chunk_benign_error(png_ptr, "out of place");
   2045       return;
   2046    }
   2047 
   2048    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
   2049    {
   2050       png_crc_finish(png_ptr, length);
   2051       png_chunk_benign_error(png_ptr, "duplicate");
   2052       return;
   2053    }
   2054 
   2055    if (length != 9)
   2056    {
   2057       png_crc_finish(png_ptr, length);
   2058       png_chunk_benign_error(png_ptr, "invalid");
   2059       return;
   2060    }
   2061 
   2062    png_crc_read(png_ptr, buf, 9);
   2063 
   2064    if (png_crc_finish(png_ptr, 0))
   2065       return;
   2066 
   2067    res_x = png_get_uint_32(buf);
   2068    res_y = png_get_uint_32(buf + 4);
   2069    unit_type = buf[8];
   2070    png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
   2071 }
   2072 #endif
   2073 
   2074 #ifdef PNG_READ_oFFs_SUPPORTED
   2075 void /* PRIVATE */
   2076 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2077 {
   2078    png_byte buf[9];
   2079    png_int_32 offset_x, offset_y;
   2080    int unit_type;
   2081 
   2082    png_debug(1, "in png_handle_oFFs");
   2083 
   2084    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2085       png_chunk_error(png_ptr, "missing IHDR");
   2086 
   2087    else if (png_ptr->mode & PNG_HAVE_IDAT)
   2088    {
   2089       png_crc_finish(png_ptr, length);
   2090       png_chunk_benign_error(png_ptr, "out of place");
   2091       return;
   2092    }
   2093 
   2094    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
   2095    {
   2096       png_crc_finish(png_ptr, length);
   2097       png_chunk_benign_error(png_ptr, "duplicate");
   2098       return;
   2099    }
   2100 
   2101    if (length != 9)
   2102    {
   2103       png_crc_finish(png_ptr, length);
   2104       png_chunk_benign_error(png_ptr, "invalid");
   2105       return;
   2106    }
   2107 
   2108    png_crc_read(png_ptr, buf, 9);
   2109 
   2110    if (png_crc_finish(png_ptr, 0))
   2111       return;
   2112 
   2113    offset_x = png_get_int_32(buf);
   2114    offset_y = png_get_int_32(buf + 4);
   2115    unit_type = buf[8];
   2116    png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
   2117 }
   2118 #endif
   2119 
   2120 #ifdef PNG_READ_pCAL_SUPPORTED
   2121 /* Read the pCAL chunk (described in the PNG Extensions document) */
   2122 void /* PRIVATE */
   2123 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2124 {
   2125    png_int_32 X0, X1;
   2126    png_byte type, nparams;
   2127    png_bytep buffer, buf, units, endptr;
   2128    png_charpp params;
   2129    int i;
   2130 
   2131    png_debug(1, "in png_handle_pCAL");
   2132 
   2133    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2134       png_chunk_error(png_ptr, "missing IHDR");
   2135 
   2136    else if (png_ptr->mode & PNG_HAVE_IDAT)
   2137    {
   2138       png_crc_finish(png_ptr, length);
   2139       png_chunk_benign_error(png_ptr, "out of place");
   2140       return;
   2141    }
   2142 
   2143    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
   2144    {
   2145       png_crc_finish(png_ptr, length);
   2146       png_chunk_benign_error(png_ptr, "duplicate");
   2147       return;
   2148    }
   2149 
   2150    png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
   2151        length + 1);
   2152 
   2153    buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
   2154 
   2155    if (buffer == NULL)
   2156    {
   2157       png_crc_finish(png_ptr, length);
   2158       png_chunk_benign_error(png_ptr, "out of memory");
   2159       return;
   2160    }
   2161 
   2162    png_crc_read(png_ptr, buffer, length);
   2163 
   2164    if (png_crc_finish(png_ptr, 0))
   2165       return;
   2166 
   2167    buffer[length] = 0; /* Null terminate the last string */
   2168 
   2169    png_debug(3, "Finding end of pCAL purpose string");
   2170    for (buf = buffer; *buf; buf++)
   2171       /* Empty loop */ ;
   2172 
   2173    endptr = buffer + length;
   2174 
   2175    /* We need to have at least 12 bytes after the purpose string
   2176     * in order to get the parameter information.
   2177     */
   2178    if (endptr <= buf + 12)
   2179    {
   2180       png_chunk_benign_error(png_ptr, "invalid");
   2181       return;
   2182    }
   2183 
   2184    png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
   2185    X0 = png_get_int_32((png_bytep)buf+1);
   2186    X1 = png_get_int_32((png_bytep)buf+5);
   2187    type = buf[9];
   2188    nparams = buf[10];
   2189    units = buf + 11;
   2190 
   2191    png_debug(3, "Checking pCAL equation type and number of parameters");
   2192    /* Check that we have the right number of parameters for known
   2193     * equation types.
   2194     */
   2195    if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
   2196        (type == PNG_EQUATION_BASE_E && nparams != 3) ||
   2197        (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
   2198        (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
   2199    {
   2200       png_chunk_benign_error(png_ptr, "invalid parameter count");
   2201       return;
   2202    }
   2203 
   2204    else if (type >= PNG_EQUATION_LAST)
   2205    {
   2206       png_chunk_benign_error(png_ptr, "unrecognized equation type");
   2207    }
   2208 
   2209    for (buf = units; *buf; buf++)
   2210       /* Empty loop to move past the units string. */ ;
   2211 
   2212    png_debug(3, "Allocating pCAL parameters array");
   2213 
   2214    params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
   2215        nparams * (sizeof (png_charp))));
   2216 
   2217    if (params == NULL)
   2218    {
   2219       png_chunk_benign_error(png_ptr, "out of memory");
   2220       return;
   2221    }
   2222 
   2223    /* Get pointers to the start of each parameter string. */
   2224    for (i = 0; i < nparams; i++)
   2225    {
   2226       buf++; /* Skip the null string terminator from previous parameter. */
   2227 
   2228       png_debug1(3, "Reading pCAL parameter %d", i);
   2229 
   2230       for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
   2231          /* Empty loop to move past each parameter string */ ;
   2232 
   2233       /* Make sure we haven't run out of data yet */
   2234       if (buf > endptr)
   2235       {
   2236          png_free(png_ptr, params);
   2237          png_chunk_benign_error(png_ptr, "invalid data");
   2238          return;
   2239       }
   2240    }
   2241 
   2242    png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
   2243       (png_charp)units, params);
   2244 
   2245    png_free(png_ptr, params);
   2246 }
   2247 #endif
   2248 
   2249 #ifdef PNG_READ_sCAL_SUPPORTED
   2250 /* Read the sCAL chunk */
   2251 void /* PRIVATE */
   2252 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2253 {
   2254    png_bytep buffer;
   2255    png_size_t i;
   2256    int state;
   2257 
   2258    png_debug(1, "in png_handle_sCAL");
   2259 
   2260    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2261       png_chunk_error(png_ptr, "missing IHDR");
   2262 
   2263    else if (png_ptr->mode & PNG_HAVE_IDAT)
   2264    {
   2265       png_crc_finish(png_ptr, length);
   2266       png_chunk_benign_error(png_ptr, "out of place");
   2267       return;
   2268    }
   2269 
   2270    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
   2271    {
   2272       png_crc_finish(png_ptr, length);
   2273       png_chunk_benign_error(png_ptr, "duplicate");
   2274       return;
   2275    }
   2276 
   2277    /* Need unit type, width, \0, height: minimum 4 bytes */
   2278    else if (length < 4)
   2279    {
   2280       png_crc_finish(png_ptr, length);
   2281       png_chunk_benign_error(png_ptr, "invalid");
   2282       return;
   2283    }
   2284 
   2285    png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
   2286       length + 1);
   2287 
   2288    buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
   2289 
   2290    if (buffer == NULL)
   2291    {
   2292       png_chunk_benign_error(png_ptr, "out of memory");
   2293       png_crc_finish(png_ptr, length);
   2294       return;
   2295    }
   2296 
   2297    png_crc_read(png_ptr, buffer, length);
   2298    buffer[length] = 0; /* Null terminate the last string */
   2299 
   2300    if (png_crc_finish(png_ptr, 0))
   2301       return;
   2302 
   2303    /* Validate the unit. */
   2304    if (buffer[0] != 1 && buffer[0] != 2)
   2305    {
   2306       png_chunk_benign_error(png_ptr, "invalid unit");
   2307       return;
   2308    }
   2309 
   2310    /* Validate the ASCII numbers, need two ASCII numbers separated by
   2311     * a '\0' and they need to fit exactly in the chunk data.
   2312     */
   2313    i = 1;
   2314    state = 0;
   2315 
   2316    if (!png_check_fp_number((png_const_charp)buffer, length, &state, &i) ||
   2317        i >= length || buffer[i++] != 0)
   2318       png_chunk_benign_error(png_ptr, "bad width format");
   2319 
   2320    else if (!PNG_FP_IS_POSITIVE(state))
   2321       png_chunk_benign_error(png_ptr, "non-positive width");
   2322 
   2323    else
   2324    {
   2325       png_size_t heighti = i;
   2326 
   2327       state = 0;
   2328       if (!png_check_fp_number((png_const_charp)buffer, length, &state, &i) ||
   2329          i != length)
   2330          png_chunk_benign_error(png_ptr, "bad height format");
   2331 
   2332       else if (!PNG_FP_IS_POSITIVE(state))
   2333          png_chunk_benign_error(png_ptr, "non-positive height");
   2334 
   2335       else
   2336          /* This is the (only) success case. */
   2337          png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
   2338             (png_charp)buffer+1, (png_charp)buffer+heighti);
   2339    }
   2340 }
   2341 #endif
   2342 
   2343 #ifdef PNG_READ_tIME_SUPPORTED
   2344 void /* PRIVATE */
   2345 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2346 {
   2347    png_byte buf[7];
   2348    png_time mod_time;
   2349 
   2350    png_debug(1, "in png_handle_tIME");
   2351 
   2352    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2353       png_chunk_error(png_ptr, "missing IHDR");
   2354 
   2355    else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
   2356    {
   2357       png_crc_finish(png_ptr, length);
   2358       png_chunk_benign_error(png_ptr, "duplicate");
   2359       return;
   2360    }
   2361 
   2362    if (png_ptr->mode & PNG_HAVE_IDAT)
   2363       png_ptr->mode |= PNG_AFTER_IDAT;
   2364 
   2365    if (length != 7)
   2366    {
   2367       png_crc_finish(png_ptr, length);
   2368       png_chunk_benign_error(png_ptr, "invalid");
   2369       return;
   2370    }
   2371 
   2372    png_crc_read(png_ptr, buf, 7);
   2373 
   2374    if (png_crc_finish(png_ptr, 0))
   2375       return;
   2376 
   2377    mod_time.second = buf[6];
   2378    mod_time.minute = buf[5];
   2379    mod_time.hour = buf[4];
   2380    mod_time.day = buf[3];
   2381    mod_time.month = buf[2];
   2382    mod_time.year = png_get_uint_16(buf);
   2383 
   2384    png_set_tIME(png_ptr, info_ptr, &mod_time);
   2385 }
   2386 #endif
   2387 
   2388 #ifdef PNG_READ_tEXt_SUPPORTED
   2389 /* Note: this does not properly handle chunks that are > 64K under DOS */
   2390 void /* PRIVATE */
   2391 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2392 {
   2393    png_text  text_info;
   2394    png_bytep buffer;
   2395    png_charp key;
   2396    png_charp text;
   2397    png_uint_32 skip = 0;
   2398 
   2399    png_debug(1, "in png_handle_tEXt");
   2400 
   2401 #ifdef PNG_USER_LIMITS_SUPPORTED
   2402    if (png_ptr->user_chunk_cache_max != 0)
   2403    {
   2404       if (png_ptr->user_chunk_cache_max == 1)
   2405       {
   2406          png_crc_finish(png_ptr, length);
   2407          return;
   2408       }
   2409 
   2410       if (--png_ptr->user_chunk_cache_max == 1)
   2411       {
   2412          png_crc_finish(png_ptr, length);
   2413          png_chunk_benign_error(png_ptr, "no space in chunk cache");
   2414          return;
   2415       }
   2416    }
   2417 #endif
   2418 
   2419    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2420       png_chunk_error(png_ptr, "missing IHDR");
   2421 
   2422    if (png_ptr->mode & PNG_HAVE_IDAT)
   2423       png_ptr->mode |= PNG_AFTER_IDAT;
   2424 
   2425 #ifdef PNG_MAX_MALLOC_64K
   2426    if (length > 65535U)
   2427    {
   2428       png_crc_finish(png_ptr, length);
   2429       png_chunk_benign_error(png_ptr, "too large to fit in memory");
   2430       return;
   2431    }
   2432 #endif
   2433 
   2434    buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
   2435 
   2436    if (buffer == NULL)
   2437    {
   2438      png_chunk_benign_error(png_ptr, "out of memory");
   2439      return;
   2440    }
   2441 
   2442    png_crc_read(png_ptr, buffer, length);
   2443 
   2444    if (png_crc_finish(png_ptr, skip))
   2445       return;
   2446 
   2447    key = (png_charp)buffer;
   2448    key[length] = 0;
   2449 
   2450    for (text = key; *text; text++)
   2451       /* Empty loop to find end of key */ ;
   2452 
   2453    if (text != key + length)
   2454       text++;
   2455 
   2456    text_info.compression = PNG_TEXT_COMPRESSION_NONE;
   2457    text_info.key = key;
   2458    text_info.lang = NULL;
   2459    text_info.lang_key = NULL;
   2460    text_info.itxt_length = 0;
   2461    text_info.text = text;
   2462    text_info.text_length = strlen(text);
   2463 
   2464    if (png_set_text_2(png_ptr, info_ptr, &text_info, 1))
   2465       png_warning(png_ptr, "Insufficient memory to process text chunk");
   2466 }
   2467 #endif
   2468 
   2469 #ifdef PNG_READ_zTXt_SUPPORTED
   2470 /* Note: this does not correctly handle chunks that are > 64K under DOS */
   2471 void /* PRIVATE */
   2472 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2473 {
   2474    png_const_charp errmsg = NULL;
   2475    png_bytep       buffer;
   2476    png_uint_32     keyword_length;
   2477 
   2478    png_debug(1, "in png_handle_zTXt");
   2479 
   2480 #ifdef PNG_USER_LIMITS_SUPPORTED
   2481    if (png_ptr->user_chunk_cache_max != 0)
   2482    {
   2483       if (png_ptr->user_chunk_cache_max == 1)
   2484       {
   2485          png_crc_finish(png_ptr, length);
   2486          return;
   2487       }
   2488 
   2489       if (--png_ptr->user_chunk_cache_max == 1)
   2490       {
   2491          png_crc_finish(png_ptr, length);
   2492          png_chunk_benign_error(png_ptr, "no space in chunk cache");
   2493          return;
   2494       }
   2495    }
   2496 #endif
   2497 
   2498    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2499       png_chunk_error(png_ptr, "missing IHDR");
   2500 
   2501    if (png_ptr->mode & PNG_HAVE_IDAT)
   2502       png_ptr->mode |= PNG_AFTER_IDAT;
   2503 
   2504    buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
   2505 
   2506    if (buffer == NULL)
   2507    {
   2508       png_crc_finish(png_ptr, length);
   2509       png_chunk_benign_error(png_ptr, "out of memory");
   2510       return;
   2511    }
   2512 
   2513    png_crc_read(png_ptr, buffer, length);
   2514 
   2515    if (png_crc_finish(png_ptr, 0))
   2516       return;
   2517 
   2518    /* TODO: also check that the keyword contents match the spec! */
   2519    for (keyword_length = 0;
   2520       keyword_length < length && buffer[keyword_length] != 0;
   2521       ++keyword_length)
   2522       /* Empty loop to find end of name */ ;
   2523 
   2524    if (keyword_length > 79 || keyword_length < 1)
   2525       errmsg = "bad keyword";
   2526 
   2527    /* zTXt must have some LZ data after the keyword, although it may expand to
   2528     * zero bytes; we need a '\0' at the end of the keyword, the compression type
   2529     * then the LZ data:
   2530     */
   2531    else if (keyword_length + 3 > length)
   2532       errmsg = "truncated";
   2533 
   2534    else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
   2535       errmsg = "unknown compression type";
   2536 
   2537    else
   2538    {
   2539       png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
   2540 
   2541       /* TODO: at present png_decompress_chunk imposes a single application
   2542        * level memory limit, this should be split to different values for iCCP
   2543        * and text chunks.
   2544        */
   2545       if (png_decompress_chunk(png_ptr, length, keyword_length+2,
   2546          &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
   2547       {
   2548          png_text text;
   2549 
   2550          /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
   2551           * for the extra compression type byte and the fact that it isn't
   2552           * necessarily '\0' terminated.
   2553           */
   2554          buffer = png_ptr->read_buffer;
   2555          buffer[uncompressed_length+(keyword_length+2)] = 0;
   2556 
   2557          text.compression = PNG_TEXT_COMPRESSION_zTXt;
   2558          text.key = (png_charp)buffer;
   2559          text.text = (png_charp)(buffer + keyword_length+2);
   2560          text.text_length = uncompressed_length;
   2561          text.itxt_length = 0;
   2562          text.lang = NULL;
   2563          text.lang_key = NULL;
   2564 
   2565          if (png_set_text_2(png_ptr, info_ptr, &text, 1))
   2566             errmsg = "insufficient memory";
   2567       }
   2568 
   2569       else
   2570          errmsg = png_ptr->zstream.msg;
   2571    }
   2572 
   2573    if (errmsg != NULL)
   2574       png_chunk_benign_error(png_ptr, errmsg);
   2575 }
   2576 #endif
   2577 
   2578 #ifdef PNG_READ_iTXt_SUPPORTED
   2579 /* Note: this does not correctly handle chunks that are > 64K under DOS */
   2580 void /* PRIVATE */
   2581 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
   2582 {
   2583    png_const_charp errmsg = NULL;
   2584    png_bytep buffer;
   2585    png_uint_32 prefix_length;
   2586 
   2587    png_debug(1, "in png_handle_iTXt");
   2588 
   2589 #ifdef PNG_USER_LIMITS_SUPPORTED
   2590    if (png_ptr->user_chunk_cache_max != 0)
   2591    {
   2592       if (png_ptr->user_chunk_cache_max == 1)
   2593       {
   2594          png_crc_finish(png_ptr, length);
   2595          return;
   2596       }
   2597 
   2598       if (--png_ptr->user_chunk_cache_max == 1)
   2599       {
   2600          png_crc_finish(png_ptr, length);
   2601          png_chunk_benign_error(png_ptr, "no space in chunk cache");
   2602          return;
   2603       }
   2604    }
   2605 #endif
   2606 
   2607    if (!(png_ptr->mode & PNG_HAVE_IHDR))
   2608       png_chunk_error(png_ptr, "missing IHDR");
   2609 
   2610    if (png_ptr->mode & PNG_HAVE_IDAT)
   2611       png_ptr->mode |= PNG_AFTER_IDAT;
   2612 
   2613    buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
   2614 
   2615    if (buffer == NULL)
   2616    {
   2617       png_crc_finish(png_ptr, length);
   2618       png_chunk_benign_error(png_ptr, "out of memory");
   2619       return;
   2620    }
   2621 
   2622    png_crc_read(png_ptr, buffer, length);
   2623 
   2624    if (png_crc_finish(png_ptr, 0))
   2625       return;
   2626 
   2627    /* First the keyword. */
   2628    for (prefix_length=0;
   2629       prefix_length < length && buffer[prefix_length] != 0;
   2630       ++prefix_length)
   2631       /* Empty loop */ ;
   2632 
   2633    /* Perform a basic check on the keyword length here. */
   2634    if (prefix_length > 79 || prefix_length < 1)
   2635       errmsg = "bad keyword";
   2636 
   2637    /* Expect keyword, compression flag, compression type, language, translated
   2638     * keyword (both may be empty but are 0 terminated) then the text, which may
   2639     * be empty.
   2640     */
   2641    else if (prefix_length + 5 > length)
   2642       errmsg = "truncated";
   2643 
   2644    else if (buffer[prefix_length+1] == 0 ||
   2645       (buffer[prefix_length+1] == 1 &&
   2646       buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
   2647    {
   2648       int compressed = buffer[prefix_length+1] != 0;
   2649       png_uint_32 language_offset, translated_keyword_offset;
   2650       png_alloc_size_t uncompressed_length = 0;
   2651 
   2652       /* Now the language tag */
   2653       prefix_length += 3;
   2654       language_offset = prefix_length;
   2655 
   2656       for (; prefix_length < length && buffer[prefix_length] != 0;
   2657          ++prefix_length)
   2658          /* Empty loop */ ;
   2659 
   2660       /* WARNING: the length may be invalid here, this is checked below. */
   2661       translated_keyword_offset = ++prefix_length;
   2662 
   2663       for (; prefix_length < length && buffer[prefix_length] != 0;
   2664          ++prefix_length)
   2665          /* Empty loop */ ;
   2666 
   2667       /* prefix_length should now be at the trailing '\0' of the translated
   2668        * keyword, but it may already be over the end.  None of this arithmetic
   2669        * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
   2670        * systems the available allocaton may overflow.
   2671        */
   2672       ++prefix_length;
   2673 
   2674       if (!compressed && prefix_length <= length)
   2675          uncompressed_length = length - prefix_length;
   2676 
   2677       else if (compressed && prefix_length < length)
   2678       {
   2679          uncompressed_length = PNG_SIZE_MAX;
   2680 
   2681          /* TODO: at present png_decompress_chunk imposes a single application
   2682           * level memory limit, this should be split to different values for
   2683           * iCCP and text chunks.
   2684           */
   2685          if (png_decompress_chunk(png_ptr, length, prefix_length,
   2686             &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
   2687             buffer = png_ptr->read_buffer;
   2688 
   2689          else
   2690             errmsg = png_ptr->zstream.msg;
   2691       }
   2692 
   2693       else
   2694          errmsg = "truncated";
   2695 
   2696       if (errmsg == NULL)
   2697       {
   2698          png_text text;
   2699 
   2700          buffer[uncompressed_length+prefix_length] = 0;
   2701 
   2702          if (compressed)
   2703             text.compression = PNG_ITXT_COMPRESSION_NONE;
   2704 
   2705          else
   2706             text.compression = PNG_ITXT_COMPRESSION_zTXt;
   2707 
   2708          text.key = (png_charp)buffer;
   2709          text.lang = (png_charp)buffer + language_offset;
   2710          text.lang_key = (png_charp)buffer + translated_keyword_offset;
   2711          text.text = (png_charp)buffer + prefix_length;
   2712          text.text_length = 0;
   2713          text.itxt_length = uncompressed_length;
   2714 
   2715          if (png_set_text_2(png_ptr, info_ptr, &text, 1))
   2716             errmsg = "insufficient memory";
   2717       }
   2718    }
   2719 
   2720    else
   2721       errmsg = "bad compression info";
   2722 
   2723    if (errmsg != NULL)
   2724       png_chunk_benign_error(png_ptr, errmsg);
   2725 }
   2726 #endif
   2727 
   2728 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
   2729 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
   2730 static int
   2731 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
   2732 {
   2733    png_alloc_size_t limit = PNG_SIZE_MAX;
   2734 
   2735    if (png_ptr->unknown_chunk.data != NULL)
   2736    {
   2737       png_free(png_ptr, png_ptr->unknown_chunk.data);
   2738       png_ptr->unknown_chunk.data = NULL;
   2739    }
   2740 
   2741 #  ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
   2742       if (png_ptr->user_chunk_malloc_max > 0 &&
   2743          png_ptr->user_chunk_malloc_max < limit)
   2744          limit = png_ptr->user_chunk_malloc_max;
   2745 
   2746 #  elif PNG_USER_CHUNK_MALLOC_MAX > 0
   2747       if (PNG_USER_CHUNK_MALLOC_MAX < limit)
   2748          limit = PNG_USER_CHUNK_MALLOC_MAX;
   2749 #  endif
   2750 
   2751    if (length <= limit)
   2752    {
   2753       PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
   2754       /* The following is safe because of the PNG_SIZE_MAX init above */
   2755       png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
   2756       /* 'mode' is a flag array, only the bottom four bits matter here */
   2757       png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
   2758 
   2759       if (length == 0)
   2760          png_ptr->unknown_chunk.data = NULL;
   2761 
   2762       else
   2763       {
   2764          /* Do a 'warn' here - it is handled below. */
   2765          png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
   2766             png_malloc_warn(png_ptr, length));
   2767       }
   2768    }
   2769 
   2770    if (png_ptr->unknown_chunk.data == NULL && length > 0)
   2771    {
   2772       /* This is benign because we clean up correctly */
   2773       png_crc_finish(png_ptr, length);
   2774       png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
   2775       return 0;
   2776    }
   2777 
   2778    else
   2779    {
   2780       if (length > 0)
   2781          png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
   2782       png_crc_finish(png_ptr, 0);
   2783       return 1;
   2784    }
   2785 }
   2786 #endif /* PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
   2787 
   2788 /* Handle an unknown, or known but disabled, chunk */
   2789 void /* PRIVATE */
   2790 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
   2791    png_uint_32 length, int keep)
   2792 {
   2793    int handled = 0; /* the chunk was handled */
   2794 
   2795    png_debug(1, "in png_handle_unknown");
   2796 
   2797 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
   2798    /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
   2799     * the bug which meant that setting a non-default behavior for a specific
   2800     * chunk would be ignored (the default was always used unless a user
   2801     * callback was installed).
   2802     *
   2803     * 'keep' is the value from the png_chunk_unknown_handling, the setting for
   2804     * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
   2805     * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
   2806     * This is just an optimization to avoid multiple calls to the lookup
   2807     * function.
   2808     */
   2809 #  ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
   2810 #     ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
   2811          keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
   2812 #     endif
   2813 #  endif
   2814 
   2815    /* One of the following methods will read the chunk or skip it (at least one
   2816     * of these is always defined because this is the only way to switch on
   2817     * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
   2818     */
   2819 #  ifdef PNG_READ_USER_CHUNKS_SUPPORTED
   2820       /* The user callback takes precedence over the chunk keep value, but the
   2821        * keep value is still required to validate a save of a critical chunk.
   2822        */
   2823       if (png_ptr->read_user_chunk_fn != NULL)
   2824       {
   2825          if (png_cache_unknown_chunk(png_ptr, length))
   2826          {
   2827             /* Callback to user unknown chunk handler */
   2828             int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
   2829                &png_ptr->unknown_chunk);
   2830 
   2831             /* ret is:
   2832              * negative: An error occured, png_chunk_error will be called.
   2833              *     zero: The chunk was not handled, the chunk will be discarded
   2834              *           unless png_set_keep_unknown_chunks has been used to set
   2835              *           a 'keep' behavior for this particular chunk, in which
   2836              *           case that will be used.  A critical chunk will cause an
   2837              *           error at this point unless it is to be saved.
   2838              * positive: The chunk was handled, libpng will ignore/discard it.
   2839              */
   2840             if (ret < 0)
   2841                png_chunk_error(png_ptr, "error in user chunk");
   2842 
   2843             else if (ret == 0)
   2844             {
   2845                /* If the keep value is 'default' or 'never' override it, but
   2846                 * still error out on critical chunks unless the keep value is
   2847                 * 'always'  While this is weird it is the behavior in 1.4.12.
   2848                 * A possible improvement would be to obey the value set for the
   2849                 * chunk, but this would be an API change that would probably
   2850                 * damage some applications.
   2851                 *
   2852                 * The png_app_warning below catches the case that matters, where
   2853                 * the application has not set specific save or ignore for this
   2854                 * chunk or global save or ignore.
   2855                 */
   2856                if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
   2857                {
   2858 #                 ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
   2859                      if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
   2860                      {
   2861                         png_chunk_warning(png_ptr, "Saving unknown chunk:");
   2862                         png_app_warning(png_ptr,
   2863                            "forcing save of an unhandled chunk;"
   2864                            " please call png_set_keep_unknown_chunks");
   2865                            /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
   2866                      }
   2867 #                 endif
   2868                   keep = PNG_HANDLE_CHUNK_IF_SAFE;
   2869                }
   2870             }
   2871 
   2872             else /* chunk was handled */
   2873             {
   2874                handled = 1;
   2875                /* Critical chunks can be safely discarded at this point. */
   2876                keep = PNG_HANDLE_CHUNK_NEVER;
   2877             }
   2878          }
   2879 
   2880          else
   2881             keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
   2882       }
   2883 
   2884       else
   2885          /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
   2886 #  endif /* PNG_READ_USER_CHUNKS_SUPPORTED */
   2887 
   2888 #  ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
   2889       {
   2890          /* keep is currently just the per-chunk setting, if there was no
   2891           * setting change it to the global default now (not that this may
   2892           * still be AS_DEFAULT) then obtain the cache of the chunk if required,
   2893           * if not simply skip the chunk.
   2894           */
   2895          if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
   2896             keep = png_ptr->unknown_default;
   2897 
   2898          if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
   2899             (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
   2900              PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
   2901          {
   2902             if (!png_cache_unknown_chunk(png_ptr, length))
   2903                keep = PNG_HANDLE_CHUNK_NEVER;
   2904          }
   2905 
   2906          else
   2907             png_crc_finish(png_ptr, length);
   2908       }
   2909 #  else
   2910 #     ifndef PNG_READ_USER_CHUNKS_SUPPORTED
   2911 #        error no method to support READ_UNKNOWN_CHUNKS
   2912 #     endif
   2913 
   2914       {
   2915          /* If here there is no read callback pointer set and no support is
   2916           * compiled in to just save the unknown chunks, so simply skip this
   2917           * chunk.  If 'keep' is something other than AS_DEFAULT or NEVER then
   2918           * the app has erroneously asked for unknown chunk saving when there
   2919           * is no support.
   2920           */
   2921          if (keep > PNG_HANDLE_CHUNK_NEVER)
   2922             png_app_error(png_ptr, "no unknown chunk support available");
   2923 
   2924          png_crc_finish(png_ptr, length);
   2925       }
   2926 #  endif
   2927 
   2928 #  ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
   2929       /* Now store the chunk in the chunk list if appropriate, and if the limits
   2930        * permit it.
   2931        */
   2932       if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
   2933          (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
   2934           PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
   2935       {
   2936 #     ifdef PNG_USER_LIMITS_SUPPORTED
   2937          switch (png_ptr->user_chunk_cache_max)
   2938          {
   2939             case 2:
   2940                png_ptr->user_chunk_cache_max = 1;
   2941                png_chunk_benign_error(png_ptr, "no space in chunk cache");
   2942                /* FALL THROUGH */
   2943             case 1:
   2944                /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
   2945                 * chunk being skipped, now there will be a hard error below.
   2946                 */
   2947                break;
   2948 
   2949             default: /* not at limit */
   2950                --(png_ptr->user_chunk_cache_max);
   2951                /* FALL THROUGH */
   2952             case 0: /* no limit */
   2953 #     endif /* PNG_USER_LIMITS_SUPPORTED */
   2954                /* Here when the limit isn't reached or when limits are compiled
   2955                 * out; store the chunk.
   2956                 */
   2957                png_set_unknown_chunks(png_ptr, info_ptr,
   2958                   &png_ptr->unknown_chunk, 1);
   2959                handled = 1;
   2960 #     ifdef PNG_USER_LIMITS_SUPPORTED
   2961                break;
   2962          }
   2963 #     endif
   2964       }
   2965 #  else /* no store support: the chunk must be handled by the user callback */
   2966       PNG_UNUSED(info_ptr)
   2967 #  endif
   2968 
   2969    /* Regardless of the error handling below the cached data (if any) can be
   2970     * freed now.  Notice that the data is not freed if there is a png_error, but
   2971     * it will be freed by destroy_read_struct.
   2972     */
   2973    if (png_ptr->unknown_chunk.data != NULL)
   2974       png_free(png_ptr, png_ptr->unknown_chunk.data);
   2975    png_ptr->unknown_chunk.data = NULL;
   2976 
   2977 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
   2978    /* There is no support to read an unknown chunk, so just skip it. */
   2979    png_crc_finish(png_ptr, length);
   2980    PNG_UNUSED(info_ptr)
   2981    PNG_UNUSED(keep)
   2982 #endif /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
   2983 
   2984    /* Check for unhandled critical chunks */
   2985    if (!handled && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
   2986       png_chunk_error(png_ptr, "unhandled critical chunk");
   2987 }
   2988 
   2989 /* This function is called to verify that a chunk name is valid.
   2990  * This function can't have the "critical chunk check" incorporated
   2991  * into it, since in the future we will need to be able to call user
   2992  * functions to handle unknown critical chunks after we check that
   2993  * the chunk name itself is valid.
   2994  */
   2995 
   2996 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
   2997  *
   2998  * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
   2999  */
   3000 
   3001 void /* PRIVATE */
   3002 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
   3003 {
   3004    int i;
   3005 
   3006    png_debug(1, "in png_check_chunk_name");
   3007 
   3008    for (i=1; i<=4; ++i)
   3009    {
   3010       int c = chunk_name & 0xff;
   3011 
   3012       if (c < 65 || c > 122 || (c > 90 && c < 97))
   3013          png_chunk_error(png_ptr, "invalid chunk type");
   3014 
   3015       chunk_name >>= 8;
   3016    }
   3017 }
   3018 
   3019 /* Combines the row recently read in with the existing pixels in the row.  This
   3020  * routine takes care of alpha and transparency if requested.  This routine also
   3021  * handles the two methods of progressive display of interlaced images,
   3022  * depending on the 'display' value; if 'display' is true then the whole row
   3023  * (dp) is filled from the start by replicating the available pixels.  If
   3024  * 'display' is false only those pixels present in the pass are filled in.
   3025  */
   3026 void /* PRIVATE */
   3027 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
   3028 {
   3029    unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
   3030    png_const_bytep sp = png_ptr->row_buf + 1;
   3031    png_alloc_size_t row_width = png_ptr->width;
   3032    unsigned int pass = png_ptr->pass;
   3033    png_bytep end_ptr = 0;
   3034    png_byte end_byte = 0;
   3035    unsigned int end_mask;
   3036 
   3037    png_debug(1, "in png_combine_row");
   3038 
   3039    /* Added in 1.5.6: it should not be possible to enter this routine until at
   3040     * least one row has been read from the PNG data and transformed.
   3041     */
   3042    if (pixel_depth == 0)
   3043       png_error(png_ptr, "internal row logic error");
   3044 
   3045    /* Added in 1.5.4: the pixel depth should match the information returned by
   3046     * any call to png_read_update_info at this point.  Do not continue if we got
   3047     * this wrong.
   3048     */
   3049    if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
   3050           PNG_ROWBYTES(pixel_depth, row_width))
   3051       png_error(png_ptr, "internal row size calculation error");
   3052 
   3053    /* Don't expect this to ever happen: */
   3054    if (row_width == 0)
   3055       png_error(png_ptr, "internal row width error");
   3056 
   3057    /* Preserve the last byte in cases where only part of it will be overwritten,
   3058     * the multiply below may overflow, we don't care because ANSI-C guarantees
   3059     * we get the low bits.
   3060     */
   3061    end_mask = (pixel_depth * row_width) & 7;
   3062    if (end_mask != 0)
   3063    {
   3064       /* end_ptr == NULL is a flag to say do nothing */
   3065       end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
   3066       end_byte = *end_ptr;
   3067 #     ifdef PNG_READ_PACKSWAP_SUPPORTED
   3068          if (png_ptr->transformations & PNG_PACKSWAP) /* little-endian byte */
   3069             end_mask = 0xff << end_mask;
   3070 
   3071          else /* big-endian byte */
   3072 #     endif
   3073          end_mask = 0xff >> end_mask;
   3074       /* end_mask is now the bits to *keep* from the destination row */
   3075    }
   3076 
   3077    /* For non-interlaced images this reduces to a memcpy(). A memcpy()
   3078     * will also happen if interlacing isn't supported or if the application
   3079     * does not call png_set_interlace_handling().  In the latter cases the
   3080     * caller just gets a sequence of the unexpanded rows from each interlace
   3081     * pass.
   3082     */
   3083 #ifdef PNG_READ_INTERLACING_SUPPORTED
   3084    if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE) &&
   3085       pass < 6 && (display == 0 ||
   3086       /* The following copies everything for 'display' on passes 0, 2 and 4. */
   3087       (display == 1 && (pass & 1) != 0)))
   3088    {
   3089       /* Narrow images may have no bits in a pass; the caller should handle
   3090        * this, but this test is cheap:
   3091        */
   3092       if (row_width <= PNG_PASS_START_COL(pass))
   3093          return;
   3094 
   3095       if (pixel_depth < 8)
   3096       {
   3097          /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
   3098           * into 32 bits, then a single loop over the bytes using the four byte
   3099           * values in the 32-bit mask can be used.  For the 'display' option the
   3100           * expanded mask may also not require any masking within a byte.  To
   3101           * make this work the PACKSWAP option must be taken into account - it
   3102           * simply requires the pixels to be reversed in each byte.
   3103           *
   3104           * The 'regular' case requires a mask for each of the first 6 passes,
   3105           * the 'display' case does a copy for the even passes in the range
   3106           * 0..6.  This has already been handled in the test above.
   3107           *
   3108           * The masks are arranged as four bytes with the first byte to use in
   3109           * the lowest bits (little-endian) regardless of the order (PACKSWAP or
   3110           * not) of the pixels in each byte.
   3111           *
   3112           * NOTE: the whole of this logic depends on the caller of this function
   3113           * only calling it on rows appropriate to the pass.  This function only
   3114           * understands the 'x' logic; the 'y' logic is handled by the caller.
   3115           *
   3116           * The following defines allow generation of compile time constant bit
   3117           * masks for each pixel depth and each possibility of swapped or not
   3118           * swapped bytes.  Pass 'p' is in the range 0..6; 'x', a pixel index,
   3119           * is in the range 0..7; and the result is 1 if the pixel is to be
   3120           * copied in the pass, 0 if not.  'S' is for the sparkle method, 'B'
   3121           * for the block method.
   3122           *
   3123           * With some compilers a compile time expression of the general form:
   3124           *
   3125           *    (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
   3126           *
   3127           * Produces warnings with values of 'shift' in the range 33 to 63
   3128           * because the right hand side of the ?: expression is evaluated by
   3129           * the compiler even though it isn't used.  Microsoft Visual C (various
   3130           * versions) and the Intel C compiler are known to do this.  To avoid
   3131           * this the following macros are used in 1.5.6.  This is a temporary
   3132           * solution to avoid destabilizing the code during the release process.
   3133           */
   3134 #        if PNG_USE_COMPILE_TIME_MASKS
   3135 #           define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
   3136 #           define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
   3137 #        else
   3138 #           define PNG_LSR(x,s) ((x)>>(s))
   3139 #           define PNG_LSL(x,s) ((x)<<(s))
   3140 #        endif
   3141 #        define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
   3142            PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
   3143 #        define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
   3144            PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
   3145 
   3146          /* Return a mask for pass 'p' pixel 'x' at depth 'd'.  The mask is
   3147           * little endian - the first pixel is at bit 0 - however the extra
   3148           * parameter 's' can be set to cause the mask position to be swapped
   3149           * within each byte, to match the PNG format.  This is done by XOR of
   3150           * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
   3151           */
   3152 #        define PIXEL_MASK(p,x,d,s) \
   3153             (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
   3154 
   3155          /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
   3156           */
   3157 #        define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
   3158 #        define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
   3159 
   3160          /* Combine 8 of these to get the full mask.  For the 1-bpp and 2-bpp
   3161           * cases the result needs replicating, for the 4-bpp case the above
   3162           * generates a full 32 bits.
   3163           */
   3164 #        define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
   3165 
   3166 #        define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
   3167             S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
   3168             S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
   3169 
   3170 #        define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
   3171             B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
   3172             B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
   3173 
   3174 #if PNG_USE_COMPILE_TIME_MASKS
   3175          /* Utility macros to construct all the masks for a depth/swap
   3176           * combination.  The 's' parameter says whether the format is PNG
   3177           * (big endian bytes) or not.  Only the three odd-numbered passes are
   3178           * required for the display/block algorithm.
   3179           */
   3180 #        define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
   3181             S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
   3182 
   3183 #        define B_MASKS(d,s) { B_MASK(1,d,s), S_MASK(3,d,s), S_MASK(5,d,s) }
   3184 
   3185 #        define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
   3186 
   3187          /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
   3188           * then pass:
   3189           */
   3190          static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
   3191          {
   3192             /* Little-endian byte masks for PACKSWAP */
   3193             { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
   3194             /* Normal (big-endian byte) masks - PNG format */
   3195             { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
   3196          };
   3197 
   3198          /* display_mask has only three entries for the odd passes, so index by
   3199           * pass>>1.
   3200           */
   3201          static PNG_CONST png_uint_32 display_mask[2][3][3] =
   3202          {
   3203             /* Little-endian byte masks for PACKSWAP */
   3204             { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
   3205             /* Normal (big-endian byte) masks - PNG format */
   3206             { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
   3207          };
   3208 
   3209 #        define MASK(pass,depth,display,png)\
   3210             ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
   3211                row_mask[png][DEPTH_INDEX(depth)][pass])
   3212 
   3213 #else /* !PNG_USE_COMPILE_TIME_MASKS */
   3214          /* This is the runtime alternative: it seems unlikely that this will
   3215           * ever be either smaller or faster than the compile time approach.
   3216           */
   3217 #        define MASK(pass,depth,display,png)\
   3218             ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
   3219 #endif /* !PNG_USE_COMPILE_TIME_MASKS */
   3220 
   3221          /* Use the appropriate mask to copy the required bits.  In some cases
   3222           * the byte mask will be 0 or 0xff, optimize these cases.  row_width is
   3223           * the number of pixels, but the code copies bytes, so it is necessary
   3224           * to special case the end.
   3225           */
   3226          png_uint_32 pixels_per_byte = 8 / pixel_depth;
   3227          png_uint_32 mask;
   3228 
   3229 #        ifdef PNG_READ_PACKSWAP_SUPPORTED
   3230             if (png_ptr->transformations & PNG_PACKSWAP)
   3231                mask = MASK(pass, pixel_depth, display, 0);
   3232 
   3233             else
   3234 #        endif
   3235             mask = MASK(pass, pixel_depth, display, 1);
   3236 
   3237          for (;;)
   3238          {
   3239             png_uint_32 m;
   3240 
   3241             /* It doesn't matter in the following if png_uint_32 has more than
   3242              * 32 bits because the high bits always match those in m<<24; it is,
   3243              * however, essential to use OR here, not +, because of this.
   3244              */
   3245             m = mask;
   3246             mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
   3247             m &= 0xff;
   3248 
   3249             if (m != 0) /* something to copy */
   3250             {
   3251                if (m != 0xff)
   3252                   *dp = (png_byte)((*dp & ~m) | (*sp & m));
   3253                else
   3254                   *dp = *sp;
   3255             }
   3256 
   3257             /* NOTE: this may overwrite the last byte with garbage if the image
   3258              * is not an exact number of bytes wide; libpng has always done
   3259              * this.
   3260              */
   3261             if (row_width <= pixels_per_byte)
   3262                break; /* May need to restore part of the last byte */
   3263 
   3264             row_width -= pixels_per_byte;
   3265             ++dp;
   3266             ++sp;
   3267          }
   3268       }
   3269 
   3270       else /* pixel_depth >= 8 */
   3271       {
   3272          unsigned int bytes_to_copy, bytes_to_jump;
   3273 
   3274          /* Validate the depth - it must be a multiple of 8 */
   3275          if (pixel_depth & 7)
   3276             png_error(png_ptr, "invalid user transform pixel depth");
   3277 
   3278          pixel_depth >>= 3; /* now in bytes */
   3279          row_width *= pixel_depth;
   3280 
   3281          /* Regardless of pass number the Adam 7 interlace always results in a
   3282           * fixed number of pixels to copy then to skip.  There may be a
   3283           * different number of pixels to skip at the start though.
   3284           */
   3285          {
   3286             unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
   3287 
   3288             row_width -= offset;
   3289             dp += offset;
   3290             sp += offset;
   3291          }
   3292 
   3293          /* Work out the bytes to copy. */
   3294          if (display)
   3295          {
   3296             /* When doing the 'block' algorithm the pixel in the pass gets
   3297              * replicated to adjacent pixels.  This is why the even (0,2,4,6)
   3298              * passes are skipped above - the entire expanded row is copied.
   3299              */
   3300             bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
   3301 
   3302             /* But don't allow this number to exceed the actual row width. */
   3303             if (bytes_to_copy > row_width)
   3304                bytes_to_copy = (unsigned int)/*SAFE*/row_width;
   3305          }
   3306 
   3307          else /* normal row; Adam7 only ever gives us one pixel to copy. */
   3308             bytes_to_copy = pixel_depth;
   3309 
   3310          /* In Adam7 there is a constant offset between where the pixels go. */
   3311          bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
   3312 
   3313          /* And simply copy these bytes.  Some optimization is possible here,
   3314           * depending on the value of 'bytes_to_copy'.  Special case the low
   3315           * byte counts, which we know to be frequent.
   3316           *
   3317           * Notice that these cases all 'return' rather than 'break' - this
   3318           * avoids an unnecessary test on whether to restore the last byte
   3319           * below.
   3320           */
   3321          switch (bytes_to_copy)
   3322          {
   3323             case 1:
   3324                for (;;)
   3325                {
   3326                   *dp = *sp;
   3327 
   3328                   if (row_width <= bytes_to_jump)
   3329                      return;
   3330 
   3331                   dp += bytes_to_jump;
   3332                   sp += bytes_to_jump;
   3333                   row_width -= bytes_to_jump;
   3334                }
   3335 
   3336             case 2:
   3337                /* There is a possibility of a partial copy at the end here; this
   3338                 * slows the code down somewhat.
   3339                 */
   3340                do
   3341                {
   3342                   dp[0] = sp[0], dp[1] = sp[1];
   3343 
   3344                   if (row_width <= bytes_to_jump)
   3345                      return;
   3346 
   3347                   sp += bytes_to_jump;
   3348                   dp += bytes_to_jump;
   3349                   row_width -= bytes_to_jump;
   3350                }
   3351                while (row_width > 1);
   3352 
   3353                /* And there can only be one byte left at this point: */
   3354                *dp = *sp;
   3355                return;
   3356 
   3357             case 3:
   3358                /* This can only be the RGB case, so each copy is exactly one
   3359                 * pixel and it is not necessary to check for a partial copy.
   3360                 */
   3361                for(;;)
   3362                {
   3363                   dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
   3364 
   3365                   if (row_width <= bytes_to_jump)
   3366                      return;
   3367 
   3368                   sp += bytes_to_jump;
   3369                   dp += bytes_to_jump;
   3370                   row_width -= bytes_to_jump;
   3371                }
   3372 
   3373             default:
   3374 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
   3375                /* Check for double byte alignment and, if possible, use a
   3376                 * 16-bit copy.  Don't attempt this for narrow images - ones that
   3377                 * are less than an interlace panel wide.  Don't attempt it for
   3378                 * wide bytes_to_copy either - use the memcpy there.
   3379                 */
   3380                if (bytes_to_copy < 16 /*else use memcpy*/ &&
   3381                   png_isaligned(dp, png_uint_16) &&
   3382                   png_isaligned(sp, png_uint_16) &&
   3383                   bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
   3384                   bytes_to_jump % (sizeof (png_uint_16)) == 0)
   3385                {
   3386                   /* Everything is aligned for png_uint_16 copies, but try for
   3387                    * png_uint_32 first.
   3388                    */
   3389                   if (png_isaligned(dp, png_uint_32) &&
   3390                      png_isaligned(sp, png_uint_32) &&
   3391                      bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
   3392                      bytes_to_jump % (sizeof (png_uint_32)) == 0)
   3393                   {
   3394                      png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
   3395                      png_const_uint_32p sp32 = png_aligncastconst(
   3396                         png_const_uint_32p, sp);
   3397                      size_t skip = (bytes_to_jump-bytes_to_copy) /
   3398                         (sizeof (png_uint_32));
   3399 
   3400                      do
   3401                      {
   3402                         size_t c = bytes_to_copy;
   3403                         do
   3404                         {
   3405                            *dp32++ = *sp32++;
   3406                            c -= (sizeof (png_uint_32));
   3407                         }
   3408                         while (c > 0);
   3409 
   3410                         if (row_width <= bytes_to_jump)
   3411                            return;
   3412 
   3413                         dp32 += skip;
   3414                         sp32 += skip;
   3415                         row_width -= bytes_to_jump;
   3416                      }
   3417                      while (bytes_to_copy <= row_width);
   3418 
   3419                      /* Get to here when the row_width truncates the final copy.
   3420                       * There will be 1-3 bytes left to copy, so don't try the
   3421                       * 16-bit loop below.
   3422                       */
   3423                      dp = (png_bytep)dp32;
   3424                      sp = (png_const_bytep)sp32;
   3425                      do
   3426                         *dp++ = *sp++;
   3427                      while (--row_width > 0);
   3428                      return;
   3429                   }
   3430 
   3431                   /* Else do it in 16-bit quantities, but only if the size is
   3432                    * not too large.
   3433                    */
   3434                   else
   3435                   {
   3436                      png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
   3437                      png_const_uint_16p sp16 = png_aligncastconst(
   3438                         png_const_uint_16p, sp);
   3439                      size_t skip = (bytes_to_jump-bytes_to_copy) /
   3440                         (sizeof (png_uint_16));
   3441 
   3442                      do
   3443                      {
   3444                         size_t c = bytes_to_copy;
   3445                         do
   3446                         {
   3447                            *dp16++ = *sp16++;
   3448                            c -= (sizeof (png_uint_16));
   3449                         }
   3450                         while (c > 0);
   3451 
   3452                         if (row_width <= bytes_to_jump)
   3453                            return;
   3454 
   3455                         dp16 += skip;
   3456                         sp16 += skip;
   3457                         row_width -= bytes_to_jump;
   3458                      }
   3459                      while (bytes_to_copy <= row_width);
   3460 
   3461                      /* End of row - 1 byte left, bytes_to_copy > row_width: */
   3462                      dp = (png_bytep)dp16;
   3463                      sp = (png_const_bytep)sp16;
   3464                      do
   3465                         *dp++ = *sp++;
   3466                      while (--row_width > 0);
   3467                      return;
   3468                   }
   3469                }
   3470 #endif /* PNG_ALIGN_ code */
   3471 
   3472                /* The true default - use a memcpy: */
   3473                for (;;)
   3474                {
   3475                   memcpy(dp, sp, bytes_to_copy);
   3476 
   3477                   if (row_width <= bytes_to_jump)
   3478                      return;
   3479 
   3480                   sp += bytes_to_jump;
   3481                   dp += bytes_to_jump;
   3482                   row_width -= bytes_to_jump;
   3483                   if (bytes_to_copy > row_width)
   3484                      bytes_to_copy = (unsigned int)/*SAFE*/row_width;
   3485                }
   3486          }
   3487 
   3488          /* NOT REACHED*/
   3489       } /* pixel_depth >= 8 */
   3490 
   3491       /* Here if pixel_depth < 8 to check 'end_ptr' below. */
   3492    }
   3493    else
   3494 #endif
   3495 
   3496    /* If here then the switch above wasn't used so just memcpy the whole row
   3497     * from the temporary row buffer (notice that this overwrites the end of the
   3498     * destination row if it is a partial byte.)
   3499     */
   3500    memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
   3501 
   3502    /* Restore the overwritten bits from the last byte if necessary. */
   3503    if (end_ptr != NULL)
   3504       *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
   3505 }
   3506 
   3507 #ifdef PNG_READ_INTERLACING_SUPPORTED
   3508 void /* PRIVATE */
   3509 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
   3510    png_uint_32 transformations /* Because these may affect the byte layout */)
   3511 {
   3512    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
   3513    /* Offset to next interlace block */
   3514    static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
   3515 
   3516    png_debug(1, "in png_do_read_interlace");
   3517    if (row != NULL && row_info != NULL)
   3518    {
   3519       png_uint_32 final_width;
   3520 
   3521       final_width = row_info->width * png_pass_inc[pass];
   3522 
   3523       switch (row_info->pixel_depth)
   3524       {
   3525          case 1:
   3526          {
   3527             png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
   3528             png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
   3529             int sshift, dshift;
   3530             int s_start, s_end, s_inc;
   3531             int jstop = png_pass_inc[pass];
   3532             png_byte v;
   3533             png_uint_32 i;
   3534             int j;
   3535 
   3536 #ifdef PNG_READ_PACKSWAP_SUPPORTED
   3537             if (transformations & PNG_PACKSWAP)
   3538             {
   3539                 sshift = (int)((row_info->width + 7) & 0x07);
   3540                 dshift = (int)((final_width + 7) & 0x07);
   3541                 s_start = 7;
   3542                 s_end = 0;
   3543                 s_inc = -1;
   3544             }
   3545 
   3546             else
   3547 #endif
   3548             {
   3549                 sshift = 7 - (int)((row_info->width + 7) & 0x07);
   3550                 dshift = 7 - (int)((final_width + 7) & 0x07);
   3551                 s_start = 0;
   3552                 s_end = 7;
   3553                 s_inc = 1;
   3554             }
   3555 
   3556             for (i = 0; i < row_info->width; i++)
   3557             {
   3558                v = (png_byte)((*sp >> sshift) & 0x01);
   3559                for (j = 0; j < jstop; j++)
   3560                {
   3561                   unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
   3562                   tmp |= v << dshift;
   3563                   *dp = (png_byte)(tmp & 0xff);
   3564 
   3565                   if (dshift == s_end)
   3566                   {
   3567                      dshift = s_start;
   3568                      dp--;
   3569                   }
   3570 
   3571                   else
   3572                      dshift += s_inc;
   3573                }
   3574 
   3575                if (sshift == s_end)
   3576                {
   3577                   sshift = s_start;
   3578                   sp--;
   3579                }
   3580 
   3581                else
   3582                   sshift += s_inc;
   3583             }
   3584             break;
   3585          }
   3586 
   3587          case 2:
   3588          {
   3589             png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
   3590             png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
   3591             int sshift, dshift;
   3592             int s_start, s_end, s_inc;
   3593             int jstop = png_pass_inc[pass];
   3594             png_uint_32 i;
   3595 
   3596 #ifdef PNG_READ_PACKSWAP_SUPPORTED
   3597             if (transformations & PNG_PACKSWAP)
   3598             {
   3599                sshift = (int)(((row_info->width + 3) & 0x03) << 1);
   3600                dshift = (int)(((final_width + 3) & 0x03) << 1);
   3601                s_start = 6;
   3602                s_end = 0;
   3603                s_inc = -2;
   3604             }
   3605 
   3606             else
   3607 #endif
   3608             {
   3609                sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
   3610                dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
   3611                s_start = 0;
   3612                s_end = 6;
   3613                s_inc = 2;
   3614             }
   3615 
   3616             for (i = 0; i < row_info->width; i++)
   3617             {
   3618                png_byte v;
   3619                int j;
   3620 
   3621                v = (png_byte)((*sp >> sshift) & 0x03);
   3622                for (j = 0; j < jstop; j++)
   3623                {
   3624                   unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
   3625                   tmp |= v << dshift;
   3626                   *dp = (png_byte)(tmp & 0xff);
   3627 
   3628                   if (dshift == s_end)
   3629                   {
   3630                      dshift = s_start;
   3631                      dp--;
   3632                   }
   3633 
   3634                   else
   3635                      dshift += s_inc;
   3636                }
   3637 
   3638                if (sshift == s_end)
   3639                {
   3640                   sshift = s_start;
   3641                   sp--;
   3642                }
   3643 
   3644                else
   3645                   sshift += s_inc;
   3646             }
   3647             break;
   3648          }
   3649 
   3650          case 4:
   3651          {
   3652             png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
   3653             png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
   3654             int sshift, dshift;
   3655             int s_start, s_end, s_inc;
   3656             png_uint_32 i;
   3657             int jstop = png_pass_inc[pass];
   3658 
   3659 #ifdef PNG_READ_PACKSWAP_SUPPORTED
   3660             if (transformations & PNG_PACKSWAP)
   3661             {
   3662                sshift = (int)(((row_info->width + 1) & 0x01) << 2);
   3663                dshift = (int)(((final_width + 1) & 0x01) << 2);
   3664                s_start = 4;
   3665                s_end = 0;
   3666                s_inc = -4;
   3667             }
   3668 
   3669             else
   3670 #endif
   3671             {
   3672                sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
   3673                dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
   3674                s_start = 0;
   3675                s_end = 4;
   3676                s_inc = 4;
   3677             }
   3678 
   3679             for (i = 0; i < row_info->width; i++)
   3680             {
   3681                png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
   3682                int j;
   3683 
   3684                for (j = 0; j < jstop; j++)
   3685                {
   3686                   unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
   3687                   tmp |= v << dshift;
   3688                   *dp = (png_byte)(tmp & 0xff);
   3689 
   3690                   if (dshift == s_end)
   3691                   {
   3692                      dshift = s_start;
   3693                      dp--;
   3694                   }
   3695 
   3696                   else
   3697                      dshift += s_inc;
   3698                }
   3699 
   3700                if (sshift == s_end)
   3701                {
   3702                   sshift = s_start;
   3703                   sp--;
   3704                }
   3705 
   3706                else
   3707                   sshift += s_inc;
   3708             }
   3709             break;
   3710          }
   3711 
   3712          default:
   3713          {
   3714             png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
   3715 
   3716             png_bytep sp = row + (png_size_t)(row_info->width - 1)
   3717                 * pixel_bytes;
   3718 
   3719             png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
   3720 
   3721             int jstop = png_pass_inc[pass];
   3722             png_uint_32 i;
   3723 
   3724             for (i = 0; i < row_info->width; i++)
   3725             {
   3726                png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
   3727                int j;
   3728 
   3729                memcpy(v, sp, pixel_bytes);
   3730 
   3731                for (j = 0; j < jstop; j++)
   3732                {
   3733                   memcpy(dp, v, pixel_bytes);
   3734                   dp -= pixel_bytes;
   3735                }
   3736 
   3737                sp -= pixel_bytes;
   3738             }
   3739             break;
   3740          }
   3741       }
   3742 
   3743       row_info->width = final_width;
   3744       row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
   3745    }
   3746 #ifndef PNG_READ_PACKSWAP_SUPPORTED
   3747    PNG_UNUSED(transformations)  /* Silence compiler warning */
   3748 #endif
   3749 }
   3750 #endif /* PNG_READ_INTERLACING_SUPPORTED */
   3751 
   3752 static void
   3753 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
   3754    png_const_bytep prev_row)
   3755 {
   3756    png_size_t i;
   3757    png_size_t istop = row_info->rowbytes;
   3758    unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
   3759    png_bytep rp = row + bpp;
   3760 
   3761    PNG_UNUSED(prev_row)
   3762 
   3763    for (i = bpp; i < istop; i++)
   3764    {
   3765       *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
   3766       rp++;
   3767    }
   3768 }
   3769 
   3770 static void
   3771 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
   3772    png_const_bytep prev_row)
   3773 {
   3774    png_size_t i;
   3775    png_size_t istop = row_info->rowbytes;
   3776    png_bytep rp = row;
   3777    png_const_bytep pp = prev_row;
   3778 
   3779    for (i = 0; i < istop; i++)
   3780    {
   3781       *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
   3782       rp++;
   3783    }
   3784 }
   3785 
   3786 static void
   3787 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
   3788    png_const_bytep prev_row)
   3789 {
   3790    png_size_t i;
   3791    png_bytep rp = row;
   3792    png_const_bytep pp = prev_row;
   3793    unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
   3794    png_size_t istop = row_info->rowbytes - bpp;
   3795 
   3796    for (i = 0; i < bpp; i++)
   3797    {
   3798       *rp = (png_byte)(((int)(*rp) +
   3799          ((int)(*pp++) / 2 )) & 0xff);
   3800 
   3801       rp++;
   3802    }
   3803 
   3804    for (i = 0; i < istop; i++)
   3805    {
   3806       *rp = (png_byte)(((int)(*rp) +
   3807          (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
   3808 
   3809       rp++;
   3810    }
   3811 }
   3812 
   3813 static void
   3814 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
   3815    png_const_bytep prev_row)
   3816 {
   3817    png_bytep rp_end = row + row_info->rowbytes;
   3818    int a, c;
   3819 
   3820    /* First pixel/byte */
   3821    c = *prev_row++;
   3822    a = *row + c;
   3823    *row++ = (png_byte)a;
   3824 
   3825    /* Remainder */
   3826    while (row < rp_end)
   3827    {
   3828       int b, pa, pb, pc, p;
   3829 
   3830       a &= 0xff; /* From previous iteration or start */
   3831       b = *prev_row++;
   3832 
   3833       p = b - c;
   3834       pc = a - c;
   3835 
   3836 #     ifdef PNG_USE_ABS
   3837          pa = abs(p);
   3838          pb = abs(pc);
   3839          pc = abs(p + pc);
   3840 #     else
   3841          pa = p < 0 ? -p : p;
   3842          pb = pc < 0 ? -pc : pc;
   3843          pc = (p + pc) < 0 ? -(p + pc) : p + pc;
   3844 #     endif
   3845 
   3846       /* Find the best predictor, the least of pa, pb, pc favoring the earlier
   3847        * ones in the case of a tie.
   3848        */
   3849       if (pb < pa) pa = pb, a = b;
   3850       if (pc < pa) a = c;
   3851 
   3852       /* Calculate the current pixel in a, and move the previous row pixel to c
   3853        * for the next time round the loop
   3854        */
   3855       c = b;
   3856       a += *row;
   3857       *row++ = (png_byte)a;
   3858    }
   3859 }
   3860 
   3861 static void
   3862 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
   3863    png_const_bytep prev_row)
   3864 {
   3865    int bpp = (row_info->pixel_depth + 7) >> 3;
   3866    png_bytep rp_end = row + bpp;
   3867 
   3868    /* Process the first pixel in the row completely (this is the same as 'up'
   3869     * because there is only one candidate predictor for the first row).
   3870     */
   3871    while (row < rp_end)
   3872    {
   3873       int a = *row + *prev_row++;
   3874       *row++ = (png_byte)a;
   3875    }
   3876 
   3877    /* Remainder */
   3878    rp_end += row_info->rowbytes - bpp;
   3879 
   3880    while (row < rp_end)
   3881    {
   3882       int a, b, c, pa, pb, pc, p;
   3883 
   3884       c = *(prev_row - bpp);
   3885       a = *(row - bpp);
   3886       b = *prev_row++;
   3887 
   3888       p = b - c;
   3889       pc = a - c;
   3890 
   3891 #     ifdef PNG_USE_ABS
   3892          pa = abs(p);
   3893          pb = abs(pc);
   3894          pc = abs(p + pc);
   3895 #     else
   3896          pa = p < 0 ? -p : p;
   3897          pb = pc < 0 ? -pc : pc;
   3898          pc = (p + pc) < 0 ? -(p + pc) : p + pc;
   3899 #     endif
   3900 
   3901       if (pb < pa) pa = pb, a = b;
   3902       if (pc < pa) a = c;
   3903 
   3904       a += *row;
   3905       *row++ = (png_byte)a;
   3906    }
   3907 }
   3908 
   3909 static void
   3910 png_init_filter_functions(png_structrp pp)
   3911    /* This function is called once for every PNG image (except for PNG images
   3912     * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
   3913     * implementations required to reverse the filtering of PNG rows.  Reversing
   3914     * the filter is the first transformation performed on the row data.  It is
   3915     * performed in place, therefore an implementation can be selected based on
   3916     * the image pixel format.  If the implementation depends on image width then
   3917     * take care to ensure that it works correctly if the image is interlaced -
   3918     * interlacing causes the actual row width to vary.
   3919     */
   3920 {
   3921    unsigned int bpp = (pp->pixel_depth + 7) >> 3;
   3922 
   3923    pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
   3924    pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
   3925    pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
   3926    if (bpp == 1)
   3927       pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
   3928          png_read_filter_row_paeth_1byte_pixel;
   3929    else
   3930       pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
   3931          png_read_filter_row_paeth_multibyte_pixel;
   3932 
   3933 #ifdef PNG_FILTER_OPTIMIZATIONS
   3934    /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
   3935     * call to install hardware optimizations for the above functions; simply
   3936     * replace whatever elements of the pp->read_filter[] array with a hardware
   3937     * specific (or, for that matter, generic) optimization.
   3938     *
   3939     * To see an example of this examine what configure.ac does when
   3940     * --enable-arm-neon is specified on the command line.
   3941     */
   3942    PNG_FILTER_OPTIMIZATIONS(pp, bpp);
   3943 #endif
   3944 }
   3945 
   3946 void /* PRIVATE */
   3947 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
   3948    png_const_bytep prev_row, int filter)
   3949 {
   3950    /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
   3951     * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
   3952     * implementations.  See png_init_filter_functions above.
   3953     */
   3954    if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
   3955    {
   3956       if (pp->read_filter[0] == NULL)
   3957          png_init_filter_functions(pp);
   3958 
   3959       pp->read_filter[filter-1](row_info, row, prev_row);
   3960    }
   3961 }
   3962 
   3963 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
   3964 void /* PRIVATE */
   3965 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
   3966    png_alloc_size_t avail_out)
   3967 {
   3968    /* Loop reading IDATs and decompressing the result into output[avail_out] */
   3969    png_ptr->zstream.next_out = output;
   3970    png_ptr->zstream.avail_out = 0; /* safety: set below */
   3971 
   3972    if (output == NULL)
   3973       avail_out = 0;
   3974 
   3975    do
   3976    {
   3977       int ret;
   3978       png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
   3979 
   3980       if (png_ptr->zstream.avail_in == 0)
   3981       {
   3982          uInt avail_in;
   3983          png_bytep buffer;
   3984 
   3985          while (png_ptr->idat_size == 0)
   3986          {
   3987 #ifdef PNG_INDEX_SUPPORTED
   3988             if (png_ptr->index) {
   3989                png_opt_crc_finish(png_ptr, 0);
   3990                png_ptr->index->stream_idat_position = png_ptr->total_data_read;
   3991             } else
   3992 #endif
   3993             png_crc_finish(png_ptr, 0);
   3994 
   3995             png_ptr->idat_size = png_read_chunk_header(png_ptr);
   3996             /* This is an error even in the 'check' case because the code just
   3997              * consumed a non-IDAT header.
   3998              */
   3999             if (png_ptr->chunk_name != png_IDAT)
   4000                png_error(png_ptr, "Not enough image data");
   4001          }
   4002 
   4003          avail_in = png_ptr->IDAT_read_size;
   4004 
   4005          if (avail_in > png_ptr->idat_size)
   4006             avail_in = (uInt)png_ptr->idat_size;
   4007 
   4008          /* A PNG with a gradually increasing IDAT size will defeat this attempt
   4009           * to minimize memory usage by causing lots of re-allocs, but
   4010           * realistically doing IDAT_read_size re-allocs is not likely to be a
   4011           * big problem.
   4012           */
   4013          buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
   4014 
   4015          png_crc_read(png_ptr, buffer, avail_in);
   4016          png_ptr->idat_size -= avail_in;
   4017 
   4018          png_ptr->zstream.next_in = buffer;
   4019          png_ptr->zstream.avail_in = avail_in;
   4020       }
   4021 
   4022       /* And set up the output side. */
   4023       if (output != NULL) /* standard read */
   4024       {
   4025          uInt out = ZLIB_IO_MAX;
   4026 
   4027          if (out > avail_out)
   4028             out = (uInt)avail_out;
   4029 
   4030          avail_out -= out;
   4031          png_ptr->zstream.avail_out = out;
   4032       }
   4033 
   4034       else /* after last row, checking for end */
   4035       {
   4036          png_ptr->zstream.next_out = tmpbuf;
   4037          png_ptr->zstream.avail_out = (sizeof tmpbuf);
   4038       }
   4039 
   4040       /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
   4041        * process.  If the LZ stream is truncated the sequential reader will
   4042        * terminally damage the stream, above, by reading the chunk header of the
   4043        * following chunk (it then exits with png_error).
   4044        *
   4045        * TODO: deal more elegantly with truncated IDAT lists.
   4046        */
   4047       ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
   4048 
   4049       /* Take the unconsumed output back. */
   4050       if (output != NULL)
   4051          avail_out += png_ptr->zstream.avail_out;
   4052 
   4053       else /* avail_out counts the extra bytes */
   4054          avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
   4055 
   4056       png_ptr->zstream.avail_out = 0;
   4057 
   4058       if (ret == Z_STREAM_END)
   4059       {
   4060          /* Do this for safety; we won't read any more into this row. */
   4061          png_ptr->zstream.next_out = NULL;
   4062 
   4063          png_ptr->mode |= PNG_AFTER_IDAT;
   4064          png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
   4065 
   4066          if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
   4067             png_chunk_benign_error(png_ptr, "Extra compressed data");
   4068          break;
   4069       }
   4070 
   4071       if (ret != Z_OK)
   4072 #ifdef PNG_INDEX_SUPPORTED
   4073         if (png_ptr->index && png_ptr->row_number != png_ptr->height - 1)
   4074 #endif
   4075       {
   4076          png_zstream_error(png_ptr, ret);
   4077 
   4078          if (output != NULL)
   4079             png_chunk_error(png_ptr, png_ptr->zstream.msg);
   4080 
   4081          else /* checking */
   4082          {
   4083             png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
   4084             return;
   4085          }
   4086       }
   4087    } while (avail_out > 0);
   4088 
   4089    if (avail_out > 0)
   4090    {
   4091       /* The stream ended before the image; this is the same as too few IDATs so
   4092        * should be handled the same way.
   4093        */
   4094       if (output != NULL)
   4095          png_error(png_ptr, "Not enough image data");
   4096 
   4097       else /* the deflate stream contained extra data */
   4098          png_chunk_benign_error(png_ptr, "Too much image data");
   4099    }
   4100 }
   4101 
   4102 void /* PRIVATE */
   4103 png_read_finish_IDAT(png_structrp png_ptr)
   4104 {
   4105    /* We don't need any more data and the stream should have ended, however the
   4106     * LZ end code may actually not have been processed.  In this case we must
   4107     * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
   4108     * may still remain to be consumed.
   4109     */
   4110    if (!(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
   4111    {
   4112       /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
   4113        * the compressed stream, but the stream may be damaged too, so even after
   4114        * this call we may need to terminate the zstream ownership.
   4115        */
   4116       png_read_IDAT_data(png_ptr, NULL, 0);
   4117       png_ptr->zstream.next_out = NULL; /* safety */
   4118 
   4119       /* Now clear everything out for safety; the following may not have been
   4120        * done.
   4121        */
   4122       if (!(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
   4123       {
   4124          png_ptr->mode |= PNG_AFTER_IDAT;
   4125          png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
   4126       }
   4127    }
   4128 
   4129    /* If the zstream has not been released do it now *and* terminate the reading
   4130     * of the final IDAT chunk.
   4131     */
   4132    if (png_ptr->zowner == png_IDAT)
   4133    {
   4134       /* Always do this; the pointers otherwise point into the read buffer. */
   4135       png_ptr->zstream.next_in = NULL;
   4136       png_ptr->zstream.avail_in = 0;
   4137 
   4138       /* Now we no longer own the zstream. */
   4139       png_ptr->zowner = 0;
   4140 
   4141       /* The slightly weird semantics of the sequential IDAT reading is that we
   4142        * are always in or at the end of an IDAT chunk, so we always need to do a
   4143        * crc_finish here.  If idat_size is non-zero we also need to read the
   4144        * spurious bytes at the end of the chunk now.
   4145        */
   4146       (void)png_crc_finish(png_ptr, png_ptr->idat_size);
   4147    }
   4148 }
   4149 
   4150 #ifdef PNG_INDEX_SUPPORTED
   4151 void /* PRIVATE */
   4152 png_set_interlaced_pass(png_structp png_ptr, int pass)
   4153 {
   4154    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
   4155    /* Start of interlace block */
   4156    PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
   4157    /* Offset to next interlace block */
   4158    PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
   4159    /* Start of interlace block in the y direction */
   4160    PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
   4161    /* Offset to next interlace block in the y direction */
   4162    PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
   4163    png_ptr->pass = pass;
   4164    png_ptr->iwidth = (png_ptr->width +
   4165          png_pass_inc[png_ptr->pass] - 1 -
   4166          png_pass_start[png_ptr->pass]) /
   4167       png_pass_inc[png_ptr->pass];
   4168 }
   4169 #endif
   4170 
   4171 void /* PRIVATE */
   4172 png_read_finish_row(png_structrp png_ptr)
   4173 {
   4174 #ifdef PNG_READ_INTERLACING_SUPPORTED
   4175    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
   4176 
   4177    /* Start of interlace block */
   4178    static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
   4179 
   4180    /* Offset to next interlace block */
   4181    static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
   4182 
   4183    /* Start of interlace block in the y direction */
   4184    static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
   4185 
   4186    /* Offset to next interlace block in the y direction */
   4187    static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
   4188 #endif /* PNG_READ_INTERLACING_SUPPORTED */
   4189 
   4190    png_debug(1, "in png_read_finish_row");
   4191    png_ptr->row_number++;
   4192    if (png_ptr->row_number < png_ptr->num_rows)
   4193       return;
   4194 
   4195 #ifdef PNG_READ_INTERLACING_SUPPORTED
   4196    if (png_ptr->interlaced)
   4197    {
   4198       png_ptr->row_number = 0;
   4199 
   4200       /* TO DO: don't do this if prev_row isn't needed (requires
   4201        * read-ahead of the next row's filter byte.
   4202        */
   4203       memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
   4204 
   4205       do
   4206       {
   4207          png_ptr->pass++;
   4208 
   4209          if (png_ptr->pass >= 7)
   4210             break;
   4211 
   4212          png_ptr->iwidth = (png_ptr->width +
   4213             png_pass_inc[png_ptr->pass] - 1 -
   4214             png_pass_start[png_ptr->pass]) /
   4215             png_pass_inc[png_ptr->pass];
   4216 
   4217          if (!(png_ptr->transformations & PNG_INTERLACE))
   4218          {
   4219             png_ptr->num_rows = (png_ptr->height +
   4220                 png_pass_yinc[png_ptr->pass] - 1 -
   4221                 png_pass_ystart[png_ptr->pass]) /
   4222                 png_pass_yinc[png_ptr->pass];
   4223          }
   4224 
   4225          else  /* if (png_ptr->transformations & PNG_INTERLACE) */
   4226             break; /* libpng deinterlacing sees every row */
   4227 
   4228       } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
   4229 
   4230       if (png_ptr->pass < 7)
   4231          return;
   4232    }
   4233 #endif /* PNG_READ_INTERLACING_SUPPORTED */
   4234 
   4235    /* Here after at the end of the last row of the last pass. */
   4236    png_read_finish_IDAT(png_ptr);
   4237 }
   4238 #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
   4239 
   4240 void /* PRIVATE */
   4241 png_read_start_row(png_structrp png_ptr)
   4242 {
   4243 #ifdef PNG_READ_INTERLACING_SUPPORTED
   4244    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
   4245 
   4246    /* Start of interlace block */
   4247    static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
   4248 
   4249    /* Offset to next interlace block */
   4250    static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
   4251 
   4252    /* Start of interlace block in the y direction */
   4253    static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
   4254 
   4255    /* Offset to next interlace block in the y direction */
   4256    static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
   4257 #endif
   4258 
   4259    int max_pixel_depth;
   4260    png_size_t row_bytes;
   4261 
   4262    png_debug(1, "in png_read_start_row");
   4263 
   4264 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
   4265    png_init_read_transformations(png_ptr);
   4266 #endif
   4267 #ifdef PNG_READ_INTERLACING_SUPPORTED
   4268    if (png_ptr->interlaced)
   4269    {
   4270       if (!(png_ptr->transformations & PNG_INTERLACE))
   4271          png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
   4272              png_pass_ystart[0]) / png_pass_yinc[0];
   4273 
   4274       else
   4275          png_ptr->num_rows = png_ptr->height;
   4276 
   4277       png_ptr->iwidth = (png_ptr->width +
   4278           png_pass_inc[png_ptr->pass] - 1 -
   4279           png_pass_start[png_ptr->pass]) /
   4280           png_pass_inc[png_ptr->pass];
   4281    }
   4282 
   4283    else
   4284 #endif /* PNG_READ_INTERLACING_SUPPORTED */
   4285    {
   4286       png_ptr->num_rows = png_ptr->height;
   4287       png_ptr->iwidth = png_ptr->width;
   4288    }
   4289 
   4290    max_pixel_depth = png_ptr->pixel_depth;
   4291 
   4292    /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpliar set of
   4293     * calculations to calculate the final pixel depth, then
   4294     * png_do_read_transforms actually does the transforms.  This means that the
   4295     * code which effectively calculates this value is actually repeated in three
   4296     * separate places.  They must all match.  Innocent changes to the order of
   4297     * transformations can and will break libpng in a way that causes memory
   4298     * overwrites.
   4299     *
   4300     * TODO: fix this.
   4301     */
   4302 #ifdef PNG_READ_PACK_SUPPORTED
   4303    if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
   4304       max_pixel_depth = 8;
   4305 #endif
   4306 
   4307 #ifdef PNG_READ_EXPAND_SUPPORTED
   4308    if (png_ptr->transformations & PNG_EXPAND)
   4309    {
   4310       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   4311       {
   4312          if (png_ptr->num_trans)
   4313             max_pixel_depth = 32;
   4314 
   4315          else
   4316             max_pixel_depth = 24;
   4317       }
   4318 
   4319       else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
   4320       {
   4321          if (max_pixel_depth < 8)
   4322             max_pixel_depth = 8;
   4323 
   4324          if (png_ptr->num_trans)
   4325             max_pixel_depth *= 2;
   4326       }
   4327 
   4328       else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
   4329       {
   4330          if (png_ptr->num_trans)
   4331          {
   4332             max_pixel_depth *= 4;
   4333             max_pixel_depth /= 3;
   4334          }
   4335       }
   4336    }
   4337 #endif
   4338 
   4339 #ifdef PNG_READ_EXPAND_16_SUPPORTED
   4340    if (png_ptr->transformations & PNG_EXPAND_16)
   4341    {
   4342 #     ifdef PNG_READ_EXPAND_SUPPORTED
   4343          /* In fact it is an error if it isn't supported, but checking is
   4344           * the safe way.
   4345           */
   4346          if (png_ptr->transformations & PNG_EXPAND)
   4347          {
   4348             if (png_ptr->bit_depth < 16)
   4349                max_pixel_depth *= 2;
   4350          }
   4351          else
   4352 #     endif
   4353          png_ptr->transformations &= ~PNG_EXPAND_16;
   4354    }
   4355 #endif
   4356 
   4357 #ifdef PNG_READ_FILLER_SUPPORTED
   4358    if (png_ptr->transformations & (PNG_FILLER))
   4359    {
   4360       if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
   4361       {
   4362          if (max_pixel_depth <= 8)
   4363             max_pixel_depth = 16;
   4364 
   4365          else
   4366             max_pixel_depth = 32;
   4367       }
   4368 
   4369       else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
   4370          png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
   4371       {
   4372          if (max_pixel_depth <= 32)
   4373             max_pixel_depth = 32;
   4374 
   4375          else
   4376             max_pixel_depth = 64;
   4377       }
   4378    }
   4379 #endif
   4380 
   4381 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
   4382    if (png_ptr->transformations & PNG_GRAY_TO_RGB)
   4383    {
   4384       if (
   4385 #ifdef PNG_READ_EXPAND_SUPPORTED
   4386           (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
   4387 #endif
   4388 #ifdef PNG_READ_FILLER_SUPPORTED
   4389           (png_ptr->transformations & (PNG_FILLER)) ||
   4390 #endif
   4391           png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
   4392       {
   4393          if (max_pixel_depth <= 16)
   4394             max_pixel_depth = 32;
   4395 
   4396          else
   4397             max_pixel_depth = 64;
   4398       }
   4399 
   4400       else
   4401       {
   4402          if (max_pixel_depth <= 8)
   4403          {
   4404             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
   4405                max_pixel_depth = 32;
   4406 
   4407             else
   4408                max_pixel_depth = 24;
   4409          }
   4410 
   4411          else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
   4412             max_pixel_depth = 64;
   4413 
   4414          else
   4415             max_pixel_depth = 48;
   4416       }
   4417    }
   4418 #endif
   4419 
   4420 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
   4421 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
   4422    if (png_ptr->transformations & PNG_USER_TRANSFORM)
   4423    {
   4424       int user_pixel_depth = png_ptr->user_transform_depth *
   4425          png_ptr->user_transform_channels;
   4426 
   4427       if (user_pixel_depth > max_pixel_depth)
   4428          max_pixel_depth = user_pixel_depth;
   4429    }
   4430 #endif
   4431 
   4432    /* This value is stored in png_struct and double checked in the row read
   4433     * code.
   4434     */
   4435    png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
   4436    png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
   4437 
   4438    /* Align the width on the next larger 8 pixels.  Mainly used
   4439     * for interlacing
   4440     */
   4441    row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
   4442    /* Calculate the maximum bytes needed, adding a byte and a pixel
   4443     * for safety's sake
   4444     */
   4445    row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
   4446        1 + ((max_pixel_depth + 7) >> 3);
   4447 
   4448 #ifdef PNG_MAX_MALLOC_64K
   4449    if (row_bytes > (png_uint_32)65536L)
   4450       png_error(png_ptr, "This image requires a row greater than 64KB");
   4451 #endif
   4452 
   4453    if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
   4454    {
   4455      png_free(png_ptr, png_ptr->big_row_buf);
   4456      png_free(png_ptr, png_ptr->big_prev_row);
   4457 
   4458      if (png_ptr->interlaced)
   4459         png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
   4460             row_bytes + 48);
   4461 
   4462      else
   4463         png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
   4464 
   4465      png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
   4466 
   4467 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
   4468      /* Use 16-byte aligned memory for row_buf with at least 16 bytes
   4469       * of padding before and after row_buf; treat prev_row similarly.
   4470       * NOTE: the alignment is to the start of the pixels, one beyond the start
   4471       * of the buffer, because of the filter byte.  Prior to libpng 1.5.6 this
   4472       * was incorrect; the filter byte was aligned, which had the exact
   4473       * opposite effect of that intended.
   4474       */
   4475      {
   4476         png_bytep temp = png_ptr->big_row_buf + 32;
   4477         int extra = (int)((temp - (png_bytep)0) & 0x0f);
   4478         png_ptr->row_buf = temp - extra - 1/*filter byte*/;
   4479 
   4480         temp = png_ptr->big_prev_row + 32;
   4481         extra = (int)((temp - (png_bytep)0) & 0x0f);
   4482         png_ptr->prev_row = temp - extra - 1/*filter byte*/;
   4483      }
   4484 
   4485 #else
   4486      /* Use 31 bytes of padding before and 17 bytes after row_buf. */
   4487      png_ptr->row_buf = png_ptr->big_row_buf + 31;
   4488      png_ptr->prev_row = png_ptr->big_prev_row + 31;
   4489 #endif
   4490      png_ptr->old_big_row_buf_size = row_bytes + 48;
   4491    }
   4492 
   4493 #ifdef PNG_MAX_MALLOC_64K
   4494    if (png_ptr->rowbytes > 65535)
   4495       png_error(png_ptr, "This image requires a row greater than 64KB");
   4496 
   4497 #endif
   4498    if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
   4499       png_error(png_ptr, "Row has too many bytes to allocate in memory");
   4500 
   4501    memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
   4502 
   4503    png_debug1(3, "width = %u,", png_ptr->width);
   4504    png_debug1(3, "height = %u,", png_ptr->height);
   4505    png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
   4506    png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
   4507    png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
   4508    png_debug1(3, "irowbytes = %lu",
   4509        (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
   4510 
   4511    /* The sequential reader needs a buffer for IDAT, but the progressive reader
   4512     * does not, so free the read buffer now regardless; the sequential reader
   4513     * reallocates it on demand.
   4514     */
   4515    if (png_ptr->read_buffer)
   4516    {
   4517       png_bytep buffer = png_ptr->read_buffer;
   4518 
   4519       png_ptr->read_buffer_size = 0;
   4520       png_ptr->read_buffer = NULL;
   4521       png_free(png_ptr, buffer);
   4522    }
   4523 
   4524    /* Finally claim the zstream for the inflate of the IDAT data, use the bits
   4525     * value from the stream (note that this will result in a fatal error if the
   4526     * IDAT stream has a bogus deflate header window_bits value, but this should
   4527     * not be happening any longer!)
   4528     */
   4529    if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
   4530       png_error(png_ptr, png_ptr->zstream.msg);
   4531 
   4532    png_ptr->flags |= PNG_FLAG_ROW_INIT;
   4533 }
   4534 #endif /* PNG_READ_SUPPORTED */
   4535