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