Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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