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