2 /* pngrutil.c - utilities to read a PNG file
4 * Last changed in libpng 1.6.24 [August 4, 2016]
5 * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
13 * This file contains routines that are only called from within
14 * libpng itself during the course of reading an image.
19 #ifdef PNG_READ_SUPPORTED
22 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
24 png_uint_32 uval = png_get_uint_32(buf);
26 if (uval > PNG_UINT_31_MAX)
27 png_error(png_ptr, "PNG unsigned integer out of range");
32 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
33 /* The following is a variation on the above for use with the fixed
34 * point values used for gAMA and cHRM. Instead of png_error it
35 * issues a warning and returns (-1) - an invalid value because both
36 * gAMA and cHRM use *unsigned* integers for fixed point values.
38 #define PNG_FIXED_ERROR (-1)
40 static png_fixed_point /* PRIVATE */
41 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
43 png_uint_32 uval = png_get_uint_32(buf);
45 if (uval <= PNG_UINT_31_MAX)
46 return (png_fixed_point)uval; /* known to be in range */
48 /* The caller can turn off the warning by passing NULL. */
50 png_warning(png_ptr, "PNG fixed point integer out of range");
52 return PNG_FIXED_ERROR;
56 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
57 /* NOTE: the read macros will obscure these definitions, so that if
58 * PNG_USE_READ_MACROS is set the library will not use them internally,
59 * but the APIs will still be available externally.
61 * The parentheses around "PNGAPI function_name" in the following three
62 * functions are necessary because they allow the macros to co-exist with
63 * these (unused but exported) functions.
66 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
68 png_get_uint_32)(png_const_bytep buf)
71 ((png_uint_32)(*(buf )) << 24) +
72 ((png_uint_32)(*(buf + 1)) << 16) +
73 ((png_uint_32)(*(buf + 2)) << 8) +
74 ((png_uint_32)(*(buf + 3)) ) ;
79 /* Grab a signed 32-bit integer from a buffer in big-endian format. The
80 * data is stored in the PNG file in two's complement format and there
81 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
82 * the following code does a two's complement to native conversion.
85 png_get_int_32)(png_const_bytep buf)
87 png_uint_32 uval = png_get_uint_32(buf);
88 if ((uval & 0x80000000) == 0) /* non-negative */
91 uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */
92 if ((uval & 0x80000000) == 0) /* no overflow */
93 return -(png_int_32)uval;
94 /* The following has to be safe; this function only gets called on PNG data
95 * and if we get here that data is invalid. 0 is the most safe value and
96 * if not then an attacker would surely just generate a PNG with 0 instead.
101 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
103 png_get_uint_16)(png_const_bytep buf)
105 /* ANSI-C requires an int value to accomodate at least 16 bits so this
106 * works and allows the compiler not to worry about possible narrowing
107 * on 32-bit systems. (Pre-ANSI systems did not make integers smaller
108 * than 16 bits either.)
111 ((unsigned int)(*buf) << 8) +
112 ((unsigned int)(*(buf + 1)));
114 return (png_uint_16)val;
117 #endif /* READ_INT_FUNCTIONS */
119 /* Read and check the PNG file signature */
121 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
123 png_size_t num_checked, num_to_check;
125 /* Exit if the user application does not expect a signature. */
126 if (png_ptr->sig_bytes >= 8)
129 num_checked = png_ptr->sig_bytes;
130 num_to_check = 8 - num_checked;
132 #ifdef PNG_IO_STATE_SUPPORTED
133 png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
136 /* The signature must be serialized in a single I/O call. */
137 png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
138 png_ptr->sig_bytes = 8;
140 if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
142 if (num_checked < 4 &&
143 png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
144 png_error(png_ptr, "Not a PNG file");
146 png_error(png_ptr, "PNG file corrupted by ASCII conversion");
149 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
152 /* Read the chunk header (length + type name).
153 * Put the type name into png_ptr->chunk_name, and return the length.
155 png_uint_32 /* PRIVATE */
156 png_read_chunk_header(png_structrp png_ptr)
161 #ifdef PNG_IO_STATE_SUPPORTED
162 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
165 /* Read the length and the chunk name.
166 * This must be performed in a single I/O call.
168 png_read_data(png_ptr, buf, 8);
169 length = png_get_uint_31(png_ptr, buf);
171 /* Put the chunk name into png_ptr->chunk_name. */
172 png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
174 png_debug2(0, "Reading %lx chunk, length = %lu",
175 (unsigned long)png_ptr->chunk_name, (unsigned long)length);
177 /* Reset the crc and run it over the chunk name. */
178 png_reset_crc(png_ptr);
179 png_calculate_crc(png_ptr, buf + 4, 4);
181 /* Check to see if chunk name is valid. */
182 png_check_chunk_name(png_ptr, png_ptr->chunk_name);
184 #ifdef PNG_IO_STATE_SUPPORTED
185 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
191 /* Read data, and (optionally) run it through the CRC. */
193 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
198 png_read_data(png_ptr, buf, length);
199 png_calculate_crc(png_ptr, buf, length);
202 /* Optionally skip data and then check the CRC. Depending on whether we
203 * are reading an ancillary or critical chunk, and how the program has set
204 * things up, we may calculate the CRC on the data and print a message.
205 * Returns '1' if there was a CRC error, '0' otherwise.
208 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
210 /* The size of the local buffer for inflate is a good guess as to a
211 * reasonable size to use for buffering reads from the application.
216 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
218 len = (sizeof tmpbuf);
223 png_crc_read(png_ptr, tmpbuf, len);
226 if (png_crc_error(png_ptr) != 0)
228 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
229 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
230 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
232 png_chunk_warning(png_ptr, "CRC error");
236 png_chunk_error(png_ptr, "CRC error");
244 /* Compare the CRC stored in the PNG file with that calculated by libpng from
245 * the data it has read thus far.
248 png_crc_error(png_structrp png_ptr)
250 png_byte crc_bytes[4];
254 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
256 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
257 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
263 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
267 #ifdef PNG_IO_STATE_SUPPORTED
268 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
271 /* The chunk CRC must be serialized in a single I/O call. */
272 png_read_data(png_ptr, crc_bytes, 4);
276 crc = png_get_uint_32(crc_bytes);
277 return ((int)(crc != png_ptr->crc));
284 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
285 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
286 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
287 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
288 /* Manage the read buffer; this simply reallocates the buffer if it is not small
289 * enough (or if it is not allocated). The routine returns a pointer to the
290 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
291 * it will call png_error (via png_malloc) on failure. (warn == 2 means
295 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
297 png_bytep buffer = png_ptr->read_buffer;
299 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
301 png_ptr->read_buffer = NULL;
302 png_ptr->read_buffer = NULL;
303 png_ptr->read_buffer_size = 0;
304 png_free(png_ptr, buffer);
310 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
314 png_ptr->read_buffer = buffer;
315 png_ptr->read_buffer_size = new_size;
318 else if (warn < 2) /* else silent */
321 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
324 png_chunk_error(png_ptr, "insufficient memory to read chunk");
330 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
332 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
333 * decompression. Returns Z_OK on success, else a zlib error code. It checks
334 * the owner but, in final release builds, just issues a warning if some other
335 * chunk apparently owns the stream. Prior to release it does a png_error.
338 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
340 if (png_ptr->zowner != 0)
344 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
345 /* So the message that results is "<chunk> using zstream"; this is an
346 * internal error, but is very useful for debugging. i18n requirements
349 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
350 #if PNG_RELEASE_BUILD
351 png_chunk_warning(png_ptr, msg);
354 png_chunk_error(png_ptr, msg);
358 /* Implementation note: unlike 'png_deflate_claim' this internal function
359 * does not take the size of the data as an argument. Some efficiency could
360 * be gained by using this when it is known *if* the zlib stream itself does
361 * not record the number; however, this is an illusion: the original writer
362 * of the PNG may have selected a lower window size, and we really must
363 * follow that because, for systems with with limited capabilities, we
364 * would otherwise reject the application's attempts to use a smaller window
365 * size (zlib doesn't have an interface to say "this or lower"!).
367 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
368 * reset, therefore it is necessary to always allocate the maximum window
369 * size with earlier zlibs just in case later compressed chunks need it.
372 int ret; /* zlib return code */
373 #if PNG_ZLIB_VERNUM >= 0x1240
375 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
378 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
382 png_ptr->zstream_start = 0; /* fixed window size */
388 png_ptr->zstream_start = 1;
391 # define window_bits 0
395 /* Set this for safety, just in case the previous owner left pointers to
396 * memory allocations.
398 png_ptr->zstream.next_in = NULL;
399 png_ptr->zstream.avail_in = 0;
400 png_ptr->zstream.next_out = NULL;
401 png_ptr->zstream.avail_out = 0;
403 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
405 #if PNG_ZLIB_VERNUM < 0x1240
406 ret = inflateReset(&png_ptr->zstream);
408 ret = inflateReset2(&png_ptr->zstream, window_bits);
414 #if PNG_ZLIB_VERNUM < 0x1240
415 ret = inflateInit(&png_ptr->zstream);
417 ret = inflateInit2(&png_ptr->zstream, window_bits);
421 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
425 png_ptr->zowner = owner;
428 png_zstream_error(png_ptr, ret);
438 #if PNG_ZLIB_VERNUM >= 0x1240
439 /* Handle the start of the inflate stream if we called inflateInit2(strm,0);
440 * in this case some zlib versions skip validation of the CINFO field and, in
441 * certain circumstances, libpng may end up displaying an invalid image, in
442 * contrast to implementations that call zlib in the normal way (e.g. libpng
446 png_zlib_inflate(png_structrp png_ptr, int flush)
448 if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0)
450 if ((*png_ptr->zstream.next_in >> 4) > 7)
452 png_ptr->zstream.msg = "invalid window size (libpng)";
456 png_ptr->zstream_start = 0;
459 return inflate(&png_ptr->zstream, flush);
461 #endif /* Zlib >= 1.2.4 */
463 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
464 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
465 * allow the caller to do multiple calls if required. If the 'finish' flag is
466 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
467 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
468 * Z_OK or Z_STREAM_END will be returned on success.
470 * The input and output sizes are updated to the actual amounts of data consumed
471 * or written, not the amount available (as in a z_stream). The data pointers
472 * are not changed, so the next input is (data+input_size) and the next
473 * available output is (output+output_size).
476 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
477 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
478 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
480 if (png_ptr->zowner == owner) /* Else not claimed */
483 png_alloc_size_t avail_out = *output_size_ptr;
484 png_uint_32 avail_in = *input_size_ptr;
486 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
487 * can't even necessarily handle 65536 bytes) because the type uInt is
488 * "16 bits or more". Consequently it is necessary to chunk the input to
489 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
490 * maximum value that can be stored in a uInt.) It is possible to set
491 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
492 * a performance advantage, because it reduces the amount of data accessed
493 * at each step and that may give the OS more time to page it in.
495 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
496 /* avail_in and avail_out are set below from 'size' */
497 png_ptr->zstream.avail_in = 0;
498 png_ptr->zstream.avail_out = 0;
500 /* Read directly into the output if it is available (this is set to
501 * a local buffer below if output is NULL).
504 png_ptr->zstream.next_out = output;
509 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
511 /* zlib INPUT BUFFER */
512 /* The setting of 'avail_in' used to be outside the loop; by setting it
513 * inside it is possible to chunk the input to zlib and simply rely on
514 * zlib to advance the 'next_in' pointer. This allows arbitrary
515 * amounts of data to be passed through zlib at the unavoidable cost of
516 * requiring a window save (memcpy of up to 32768 output bytes)
517 * every ZLIB_IO_MAX input bytes.
519 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
523 if (avail_in < avail)
524 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
527 png_ptr->zstream.avail_in = avail;
529 /* zlib OUTPUT BUFFER */
530 avail_out += png_ptr->zstream.avail_out; /* not written last time */
532 avail = ZLIB_IO_MAX; /* maximum zlib can process */
536 /* Reset the output buffer each time round if output is NULL and
537 * make available the full buffer, up to 'remaining_space'
539 png_ptr->zstream.next_out = local_buffer;
540 if ((sizeof local_buffer) < avail)
541 avail = (sizeof local_buffer);
544 if (avail_out < avail)
545 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
547 png_ptr->zstream.avail_out = avail;
550 /* zlib inflate call */
551 /* In fact 'avail_out' may be 0 at this point, that happens at the end
552 * of the read when the final LZ end code was not passed at the end of
553 * the previous chunk of input data. Tell zlib if we have reached the
554 * end of the output buffer.
556 ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH :
557 (finish ? Z_FINISH : Z_SYNC_FLUSH));
558 } while (ret == Z_OK);
560 /* For safety kill the local buffer pointer now */
562 png_ptr->zstream.next_out = NULL;
564 /* Claw back the 'size' and 'remaining_space' byte counts. */
565 avail_in += png_ptr->zstream.avail_in;
566 avail_out += png_ptr->zstream.avail_out;
568 /* Update the input and output sizes; the updated values are the amount
569 * consumed or written, effectively the inverse of what zlib uses.
572 *output_size_ptr -= avail_out;
575 *input_size_ptr -= avail_in;
577 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
578 png_zstream_error(png_ptr, ret);
584 /* This is a bad internal error. The recovery assigns to the zstream msg
585 * pointer, which is not owned by the caller, but this is safe; it's only
588 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
589 return Z_STREAM_ERROR;
593 #if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED)
595 * Decompress trailing data in a chunk. The assumption is that read_buffer
596 * points at an allocated area holding the contents of a chunk with a
597 * trailing compressed part. What we get back is an allocated area
598 * holding the original prefix part and an uncompressed version of the
599 * trailing part (the malloc area passed in is freed).
602 png_decompress_chunk(png_structrp png_ptr,
603 png_uint_32 chunklength, png_uint_32 prefix_size,
604 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
605 int terminate /*add a '\0' to the end of the uncompressed data*/)
607 /* TODO: implement different limits for different types of chunk.
609 * The caller supplies *newlength set to the maximum length of the
610 * uncompressed data, but this routine allocates space for the prefix and
611 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
612 * limited only by the maximum chunk size.
614 png_alloc_size_t limit = PNG_SIZE_MAX;
616 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
617 if (png_ptr->user_chunk_malloc_max > 0 &&
618 png_ptr->user_chunk_malloc_max < limit)
619 limit = png_ptr->user_chunk_malloc_max;
620 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
621 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
622 limit = PNG_USER_CHUNK_MALLOC_MAX;
625 if (limit >= prefix_size + (terminate != 0))
629 limit -= prefix_size + (terminate != 0);
631 if (limit < *newlength)
634 /* Now try to claim the stream. */
635 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
639 png_uint_32 lzsize = chunklength - prefix_size;
641 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
642 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
643 /* output: */ NULL, newlength);
645 if (ret == Z_STREAM_END)
647 /* Use 'inflateReset' here, not 'inflateReset2' because this
648 * preserves the previously decided window size (otherwise it would
649 * be necessary to store the previous window size.) In practice
650 * this doesn't matter anyway, because png_inflate will call inflate
651 * with Z_FINISH in almost all cases, so the window will not be
654 if (inflateReset(&png_ptr->zstream) == Z_OK)
656 /* Because of the limit checks above we know that the new,
657 * expanded, size will fit in a size_t (let alone an
658 * png_alloc_size_t). Use png_malloc_base here to avoid an
661 png_alloc_size_t new_size = *newlength;
662 png_alloc_size_t buffer_size = prefix_size + new_size +
664 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
669 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
670 png_ptr->read_buffer + prefix_size, &lzsize,
671 text + prefix_size, newlength);
673 if (ret == Z_STREAM_END)
675 if (new_size == *newlength)
678 text[prefix_size + *newlength] = 0;
681 memcpy(text, png_ptr->read_buffer, prefix_size);
684 png_bytep old_ptr = png_ptr->read_buffer;
686 png_ptr->read_buffer = text;
687 png_ptr->read_buffer_size = buffer_size;
688 text = old_ptr; /* freed below */
694 /* The size changed on the second read, there can be no
695 * guarantee that anything is correct at this point.
696 * The 'msg' pointer has been set to "unexpected end of
697 * LZ stream", which is fine, but return an error code
698 * that the caller won't accept.
700 ret = PNG_UNEXPECTED_ZLIB_RETURN;
704 else if (ret == Z_OK)
705 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
707 /* Free the text pointer (this is the old read_buffer on
710 png_free(png_ptr, text);
712 /* This really is very benign, but it's still an error because
713 * the extra space may otherwise be used as a Trojan Horse.
715 if (ret == Z_STREAM_END &&
716 chunklength - prefix_size != lzsize)
717 png_chunk_benign_error(png_ptr, "extra compressed data");
722 /* Out of memory allocating the buffer */
724 png_zstream_error(png_ptr, Z_MEM_ERROR);
730 /* inflateReset failed, store the error message */
731 png_zstream_error(png_ptr, ret);
733 if (ret == Z_STREAM_END)
734 ret = PNG_UNEXPECTED_ZLIB_RETURN;
738 else if (ret == Z_OK)
739 ret = PNG_UNEXPECTED_ZLIB_RETURN;
741 /* Release the claimed stream */
745 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
746 ret = PNG_UNEXPECTED_ZLIB_RETURN;
753 /* Application/configuration limits exceeded */
754 png_zstream_error(png_ptr, Z_MEM_ERROR);
758 #endif /* READ_zTXt || READ_iTXt */
759 #endif /* READ_COMPRESSED_TEXT */
761 #ifdef PNG_READ_iCCP_SUPPORTED
762 /* Perform a partial read and decompress, producing 'avail_out' bytes and
763 * reading from the current chunk as required.
766 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
767 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
770 if (png_ptr->zowner == png_ptr->chunk_name)
774 /* next_in and avail_in must have been initialized by the caller. */
775 png_ptr->zstream.next_out = next_out;
776 png_ptr->zstream.avail_out = 0; /* set in the loop */
780 if (png_ptr->zstream.avail_in == 0)
782 if (read_size > *chunk_bytes)
783 read_size = (uInt)*chunk_bytes;
784 *chunk_bytes -= read_size;
787 png_crc_read(png_ptr, read_buffer, read_size);
789 png_ptr->zstream.next_in = read_buffer;
790 png_ptr->zstream.avail_in = read_size;
793 if (png_ptr->zstream.avail_out == 0)
795 uInt avail = ZLIB_IO_MAX;
796 if (avail > *out_size)
797 avail = (uInt)*out_size;
800 png_ptr->zstream.avail_out = avail;
803 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
804 * the available output is produced; this allows reading of truncated
807 ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ?
808 Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
810 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
812 *out_size += png_ptr->zstream.avail_out;
813 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
815 /* Ensure the error message pointer is always set: */
816 png_zstream_error(png_ptr, ret);
822 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
823 return Z_STREAM_ERROR;
828 /* Read and check the IDHR chunk */
831 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
834 png_uint_32 width, height;
835 int bit_depth, color_type, compression_type, filter_type;
838 png_debug(1, "in png_handle_IHDR");
840 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
841 png_chunk_error(png_ptr, "out of place");
843 /* Check the length */
845 png_chunk_error(png_ptr, "invalid");
847 png_ptr->mode |= PNG_HAVE_IHDR;
849 png_crc_read(png_ptr, buf, 13);
850 png_crc_finish(png_ptr, 0);
852 width = png_get_uint_31(png_ptr, buf);
853 height = png_get_uint_31(png_ptr, buf + 4);
856 compression_type = buf[10];
857 filter_type = buf[11];
858 interlace_type = buf[12];
860 /* Set internal variables */
861 png_ptr->width = width;
862 png_ptr->height = height;
863 png_ptr->bit_depth = (png_byte)bit_depth;
864 png_ptr->interlaced = (png_byte)interlace_type;
865 png_ptr->color_type = (png_byte)color_type;
866 #ifdef PNG_MNG_FEATURES_SUPPORTED
867 png_ptr->filter_type = (png_byte)filter_type;
869 png_ptr->compression_type = (png_byte)compression_type;
871 /* Find number of channels */
872 switch (png_ptr->color_type)
874 default: /* invalid, png_set_IHDR calls png_error */
875 case PNG_COLOR_TYPE_GRAY:
876 case PNG_COLOR_TYPE_PALETTE:
877 png_ptr->channels = 1;
880 case PNG_COLOR_TYPE_RGB:
881 png_ptr->channels = 3;
884 case PNG_COLOR_TYPE_GRAY_ALPHA:
885 png_ptr->channels = 2;
888 case PNG_COLOR_TYPE_RGB_ALPHA:
889 png_ptr->channels = 4;
893 /* Set up other useful info */
894 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
895 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
896 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
897 png_debug1(3, "channels = %d", png_ptr->channels);
898 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
899 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
900 color_type, interlace_type, compression_type, filter_type);
903 /* Read and check the palette */
905 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
907 png_color palette[PNG_MAX_PALETTE_LENGTH];
908 int max_palette_length, num, i;
909 #ifdef PNG_POINTER_INDEXING_SUPPORTED
913 png_debug(1, "in png_handle_PLTE");
915 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
916 png_chunk_error(png_ptr, "missing IHDR");
918 /* Moved to before the 'after IDAT' check below because otherwise duplicate
919 * PLTE chunks are potentially ignored (the spec says there shall not be more
920 * than one PLTE, the error is not treated as benign, so this check trumps
921 * the requirement that PLTE appears before IDAT.)
923 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
924 png_chunk_error(png_ptr, "duplicate");
926 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
928 /* This is benign because the non-benign error happened before, when an
929 * IDAT was encountered in a color-mapped image with no PLTE.
931 png_crc_finish(png_ptr, length);
932 png_chunk_benign_error(png_ptr, "out of place");
936 png_ptr->mode |= PNG_HAVE_PLTE;
938 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
940 png_crc_finish(png_ptr, length);
941 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
945 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
946 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
948 png_crc_finish(png_ptr, length);
953 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
955 png_crc_finish(png_ptr, length);
957 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
958 png_chunk_benign_error(png_ptr, "invalid");
961 png_chunk_error(png_ptr, "invalid");
966 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
967 num = (int)length / 3;
969 /* If the palette has 256 or fewer entries but is too large for the bit
970 * depth, we don't issue an error, to preserve the behavior of previous
971 * libpng versions. We silently truncate the unused extra palette entries
974 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
975 max_palette_length = (1 << png_ptr->bit_depth);
977 max_palette_length = PNG_MAX_PALETTE_LENGTH;
979 if (num > max_palette_length)
980 num = max_palette_length;
982 #ifdef PNG_POINTER_INDEXING_SUPPORTED
983 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
987 png_crc_read(png_ptr, buf, 3);
988 pal_ptr->red = buf[0];
989 pal_ptr->green = buf[1];
990 pal_ptr->blue = buf[2];
993 for (i = 0; i < num; i++)
997 png_crc_read(png_ptr, buf, 3);
998 /* Don't depend upon png_color being any order */
999 palette[i].red = buf[0];
1000 palette[i].green = buf[1];
1001 palette[i].blue = buf[2];
1005 /* If we actually need the PLTE chunk (ie for a paletted image), we do
1006 * whatever the normal CRC configuration tells us. However, if we
1007 * have an RGB image, the PLTE can be considered ancillary, so
1008 * we will act as though it is.
1010 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1011 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1014 png_crc_finish(png_ptr, (int) length - num * 3);
1017 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1018 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
1020 /* If we don't want to use the data from an ancillary chunk,
1021 * we have two options: an error abort, or a warning and we
1022 * ignore the data in this chunk (which should be OK, since
1023 * it's considered ancillary for a RGB or RGBA image).
1025 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
1026 * chunk type to determine whether to check the ancillary or the critical
1029 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
1031 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
1035 png_chunk_error(png_ptr, "CRC error");
1038 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1039 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1040 png_chunk_warning(png_ptr, "CRC error");
1044 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1045 * own copy of the palette. This has the side effect that when png_start_row
1046 * is called (this happens after any call to png_read_update_info) the
1047 * info_ptr palette gets changed. This is extremely unexpected and
1050 * Fix this by not sharing the palette in this way.
1052 png_set_PLTE(png_ptr, info_ptr, palette, num);
1054 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1055 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1056 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1057 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1058 * therefore does a benign error if the erroneous condition is detected *and*
1059 * cancels the tRNS if the benign error returns. The alternative is to
1060 * amend the standard since it would be rather hypocritical of the standards
1061 * maintainers to ignore it.
1063 #ifdef PNG_READ_tRNS_SUPPORTED
1064 if (png_ptr->num_trans > 0 ||
1065 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1067 /* Cancel this because otherwise it would be used if the transforms
1068 * require it. Don't cancel the 'valid' flag because this would prevent
1069 * detection of duplicate chunks.
1071 png_ptr->num_trans = 0;
1073 if (info_ptr != NULL)
1074 info_ptr->num_trans = 0;
1076 png_chunk_benign_error(png_ptr, "tRNS must be after");
1080 #ifdef PNG_READ_hIST_SUPPORTED
1081 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1082 png_chunk_benign_error(png_ptr, "hIST must be after");
1085 #ifdef PNG_READ_bKGD_SUPPORTED
1086 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1087 png_chunk_benign_error(png_ptr, "bKGD must be after");
1092 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1094 png_debug(1, "in png_handle_IEND");
1096 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1097 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1098 png_chunk_error(png_ptr, "out of place");
1100 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1102 png_crc_finish(png_ptr, length);
1105 png_chunk_benign_error(png_ptr, "invalid");
1107 PNG_UNUSED(info_ptr)
1110 #ifdef PNG_READ_gAMA_SUPPORTED
1112 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1114 png_fixed_point igamma;
1117 png_debug(1, "in png_handle_gAMA");
1119 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1120 png_chunk_error(png_ptr, "missing IHDR");
1122 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1124 png_crc_finish(png_ptr, length);
1125 png_chunk_benign_error(png_ptr, "out of place");
1131 png_crc_finish(png_ptr, length);
1132 png_chunk_benign_error(png_ptr, "invalid");
1136 png_crc_read(png_ptr, buf, 4);
1138 if (png_crc_finish(png_ptr, 0) != 0)
1141 igamma = png_get_fixed_point(NULL, buf);
1143 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1144 png_colorspace_sync(png_ptr, info_ptr);
1148 #ifdef PNG_READ_sBIT_SUPPORTED
1150 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1152 unsigned int truelen, i;
1153 png_byte sample_depth;
1156 png_debug(1, "in png_handle_sBIT");
1158 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1159 png_chunk_error(png_ptr, "missing IHDR");
1161 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1163 png_crc_finish(png_ptr, length);
1164 png_chunk_benign_error(png_ptr, "out of place");
1168 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1170 png_crc_finish(png_ptr, length);
1171 png_chunk_benign_error(png_ptr, "duplicate");
1175 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1183 truelen = png_ptr->channels;
1184 sample_depth = png_ptr->bit_depth;
1187 if (length != truelen || length > 4)
1189 png_chunk_benign_error(png_ptr, "invalid");
1190 png_crc_finish(png_ptr, length);
1194 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1195 png_crc_read(png_ptr, buf, truelen);
1197 if (png_crc_finish(png_ptr, 0) != 0)
1200 for (i=0; i<truelen; ++i)
1202 if (buf[i] == 0 || buf[i] > sample_depth)
1204 png_chunk_benign_error(png_ptr, "invalid");
1209 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1211 png_ptr->sig_bit.red = buf[0];
1212 png_ptr->sig_bit.green = buf[1];
1213 png_ptr->sig_bit.blue = buf[2];
1214 png_ptr->sig_bit.alpha = buf[3];
1219 png_ptr->sig_bit.gray = buf[0];
1220 png_ptr->sig_bit.red = buf[0];
1221 png_ptr->sig_bit.green = buf[0];
1222 png_ptr->sig_bit.blue = buf[0];
1223 png_ptr->sig_bit.alpha = buf[1];
1226 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1230 #ifdef PNG_READ_cHRM_SUPPORTED
1232 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1237 png_debug(1, "in png_handle_cHRM");
1239 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1240 png_chunk_error(png_ptr, "missing IHDR");
1242 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1244 png_crc_finish(png_ptr, length);
1245 png_chunk_benign_error(png_ptr, "out of place");
1251 png_crc_finish(png_ptr, length);
1252 png_chunk_benign_error(png_ptr, "invalid");
1256 png_crc_read(png_ptr, buf, 32);
1258 if (png_crc_finish(png_ptr, 0) != 0)
1261 xy.whitex = png_get_fixed_point(NULL, buf);
1262 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1263 xy.redx = png_get_fixed_point(NULL, buf + 8);
1264 xy.redy = png_get_fixed_point(NULL, buf + 12);
1265 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1266 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1267 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1268 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1270 if (xy.whitex == PNG_FIXED_ERROR ||
1271 xy.whitey == PNG_FIXED_ERROR ||
1272 xy.redx == PNG_FIXED_ERROR ||
1273 xy.redy == PNG_FIXED_ERROR ||
1274 xy.greenx == PNG_FIXED_ERROR ||
1275 xy.greeny == PNG_FIXED_ERROR ||
1276 xy.bluex == PNG_FIXED_ERROR ||
1277 xy.bluey == PNG_FIXED_ERROR)
1279 png_chunk_benign_error(png_ptr, "invalid values");
1283 /* If a colorspace error has already been output skip this chunk */
1284 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1287 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1289 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1290 png_colorspace_sync(png_ptr, info_ptr);
1291 png_chunk_benign_error(png_ptr, "duplicate");
1295 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1296 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1297 1/*prefer cHRM values*/);
1298 png_colorspace_sync(png_ptr, info_ptr);
1302 #ifdef PNG_READ_sRGB_SUPPORTED
1304 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1308 png_debug(1, "in png_handle_sRGB");
1310 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1311 png_chunk_error(png_ptr, "missing IHDR");
1313 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1315 png_crc_finish(png_ptr, length);
1316 png_chunk_benign_error(png_ptr, "out of place");
1322 png_crc_finish(png_ptr, length);
1323 png_chunk_benign_error(png_ptr, "invalid");
1327 png_crc_read(png_ptr, &intent, 1);
1329 if (png_crc_finish(png_ptr, 0) != 0)
1332 /* If a colorspace error has already been output skip this chunk */
1333 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1336 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1339 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1341 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1342 png_colorspace_sync(png_ptr, info_ptr);
1343 png_chunk_benign_error(png_ptr, "too many profiles");
1347 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1348 png_colorspace_sync(png_ptr, info_ptr);
1350 #endif /* READ_sRGB */
1352 #ifdef PNG_READ_iCCP_SUPPORTED
1354 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1355 /* Note: this does not properly handle profiles that are > 64K under DOS */
1357 png_const_charp errmsg = NULL; /* error message output, or no error */
1358 int finished = 0; /* crc checked */
1360 png_debug(1, "in png_handle_iCCP");
1362 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1363 png_chunk_error(png_ptr, "missing IHDR");
1365 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1367 png_crc_finish(png_ptr, length);
1368 png_chunk_benign_error(png_ptr, "out of place");
1372 /* Consistent with all the above colorspace handling an obviously *invalid*
1373 * chunk is just ignored, so does not invalidate the color space. An
1374 * alternative is to set the 'invalid' flags at the start of this routine
1375 * and only clear them in they were not set before and all the tests pass.
1376 * The minimum 'deflate' stream is assumed to be just the 2 byte header and
1377 * 4 byte checksum. The keyword must be at least one character and there is
1378 * a terminator (0) byte and the compression method.
1382 png_crc_finish(png_ptr, length);
1383 png_chunk_benign_error(png_ptr, "too short");
1387 /* If a colorspace error has already been output skip this chunk */
1388 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1390 png_crc_finish(png_ptr, length);
1394 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1397 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1399 uInt read_length, keyword_length;
1402 /* Find the keyword; the keyword plus separator and compression method
1403 * bytes can be at most 81 characters long.
1405 read_length = 81; /* maximum */
1406 if (read_length > length)
1407 read_length = (uInt)length;
1409 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1410 length -= read_length;
1413 while (keyword_length < 80 && keyword_length < read_length &&
1414 keyword[keyword_length] != 0)
1417 /* TODO: make the keyword checking common */
1418 if (keyword_length >= 1 && keyword_length <= 79)
1420 /* We only understand '0' compression - deflate - so if we get a
1421 * different value we can't safely decode the chunk.
1423 if (keyword_length+1 < read_length &&
1424 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1426 read_length -= keyword_length+2;
1428 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1430 Byte profile_header[132];
1431 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1432 png_alloc_size_t size = (sizeof profile_header);
1434 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1435 png_ptr->zstream.avail_in = read_length;
1436 (void)png_inflate_read(png_ptr, local_buffer,
1437 (sizeof local_buffer), &length, profile_header, &size,
1438 0/*finish: don't, because the output is too small*/);
1442 /* We have the ICC profile header; do the basic header checks.
1444 const png_uint_32 profile_length =
1445 png_get_uint_32(profile_header);
1447 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1448 keyword, profile_length) != 0)
1450 /* The length is apparently ok, so we can check the 132
1453 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1454 keyword, profile_length, profile_header,
1455 png_ptr->color_type) != 0)
1457 /* Now read the tag table; a variable size buffer is
1458 * needed at this point, allocate one for the whole
1459 * profile. The header check has already validated
1460 * that none of these stuff will overflow.
1462 const png_uint_32 tag_count = png_get_uint_32(
1463 profile_header+128);
1464 png_bytep profile = png_read_buffer(png_ptr,
1465 profile_length, 2/*silent*/);
1467 if (profile != NULL)
1469 memcpy(profile, profile_header,
1470 (sizeof profile_header));
1472 size = 12 * tag_count;
1474 (void)png_inflate_read(png_ptr, local_buffer,
1475 (sizeof local_buffer), &length,
1476 profile + (sizeof profile_header), &size, 0);
1478 /* Still expect a buffer error because we expect
1479 * there to be some tag data!
1483 if (png_icc_check_tag_table(png_ptr,
1484 &png_ptr->colorspace, keyword, profile_length,
1487 /* The profile has been validated for basic
1488 * security issues, so read the whole thing in.
1490 size = profile_length - (sizeof profile_header)
1493 (void)png_inflate_read(png_ptr, local_buffer,
1494 (sizeof local_buffer), &length,
1495 profile + (sizeof profile_header) +
1496 12 * tag_count, &size, 1/*finish*/);
1498 if (length > 0 && !(png_ptr->flags &
1499 PNG_FLAG_BENIGN_ERRORS_WARN))
1500 errmsg = "extra compressed data";
1502 /* But otherwise allow extra data: */
1507 /* This can be handled completely, so
1510 png_chunk_warning(png_ptr,
1511 "extra compressed data");
1514 png_crc_finish(png_ptr, length);
1517 # if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 0
1518 /* Check for a match against sRGB */
1519 png_icc_set_sRGB(png_ptr,
1520 &png_ptr->colorspace, profile,
1521 png_ptr->zstream.adler);
1524 /* Steal the profile for info_ptr. */
1525 if (info_ptr != NULL)
1527 png_free_data(png_ptr, info_ptr,
1530 info_ptr->iccp_name = png_voidcast(char*,
1531 png_malloc_base(png_ptr,
1533 if (info_ptr->iccp_name != NULL)
1535 memcpy(info_ptr->iccp_name, keyword,
1537 info_ptr->iccp_proflen =
1539 info_ptr->iccp_profile = profile;
1540 png_ptr->read_buffer = NULL; /*steal*/
1541 info_ptr->free_me |= PNG_FREE_ICCP;
1542 info_ptr->valid |= PNG_INFO_iCCP;
1547 png_ptr->colorspace.flags |=
1548 PNG_COLORSPACE_INVALID;
1549 errmsg = "out of memory";
1553 /* else the profile remains in the read
1554 * buffer which gets reused for subsequent
1558 if (info_ptr != NULL)
1559 png_colorspace_sync(png_ptr, info_ptr);
1563 png_ptr->zowner = 0;
1569 errmsg = "truncated";
1571 #ifndef __COVERITY__
1573 errmsg = png_ptr->zstream.msg;
1577 /* else png_icc_check_tag_table output an error */
1580 else /* profile truncated */
1581 errmsg = png_ptr->zstream.msg;
1585 errmsg = "out of memory";
1588 /* else png_icc_check_header output an error */
1591 /* else png_icc_check_length output an error */
1594 else /* profile truncated */
1595 errmsg = png_ptr->zstream.msg;
1597 /* Release the stream */
1598 png_ptr->zowner = 0;
1601 else /* png_inflate_claim failed */
1602 errmsg = png_ptr->zstream.msg;
1606 errmsg = "bad compression method"; /* or missing */
1610 errmsg = "bad keyword";
1614 errmsg = "too many profiles";
1616 /* Failure: the reason is in 'errmsg' */
1618 png_crc_finish(png_ptr, length);
1620 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1621 png_colorspace_sync(png_ptr, info_ptr);
1622 if (errmsg != NULL) /* else already output */
1623 png_chunk_benign_error(png_ptr, errmsg);
1625 #endif /* READ_iCCP */
1627 #ifdef PNG_READ_sPLT_SUPPORTED
1629 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1630 /* Note: this does not properly handle chunks that are > 64K under DOS */
1632 png_bytep entry_start, buffer;
1633 png_sPLT_t new_palette;
1635 png_uint_32 data_length;
1637 png_uint_32 skip = 0;
1641 png_debug(1, "in png_handle_sPLT");
1643 #ifdef PNG_USER_LIMITS_SUPPORTED
1644 if (png_ptr->user_chunk_cache_max != 0)
1646 if (png_ptr->user_chunk_cache_max == 1)
1648 png_crc_finish(png_ptr, length);
1652 if (--png_ptr->user_chunk_cache_max == 1)
1654 png_warning(png_ptr, "No space in chunk cache for sPLT");
1655 png_crc_finish(png_ptr, length);
1661 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1662 png_chunk_error(png_ptr, "missing IHDR");
1664 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1666 png_crc_finish(png_ptr, length);
1667 png_chunk_benign_error(png_ptr, "out of place");
1671 #ifdef PNG_MAX_MALLOC_64K
1672 if (length > 65535U)
1674 png_crc_finish(png_ptr, length);
1675 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1680 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1683 png_crc_finish(png_ptr, length);
1684 png_chunk_benign_error(png_ptr, "out of memory");
1689 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1690 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1691 * potential breakage point if the types in pngconf.h aren't exactly right.
1693 png_crc_read(png_ptr, buffer, length);
1695 if (png_crc_finish(png_ptr, skip) != 0)
1700 for (entry_start = buffer; *entry_start; entry_start++)
1701 /* Empty loop to find end of name */ ;
1705 /* A sample depth should follow the separator, and we should be on it */
1706 if (length < 2U || entry_start > buffer + (length - 2U))
1708 png_warning(png_ptr, "malformed sPLT chunk");
1712 new_palette.depth = *entry_start++;
1713 entry_size = (new_palette.depth == 8 ? 6 : 10);
1714 /* This must fit in a png_uint_32 because it is derived from the original
1715 * chunk data length.
1717 data_length = length - (png_uint_32)(entry_start - buffer);
1719 /* Integrity-check the data length */
1720 if ((data_length % entry_size) != 0)
1722 png_warning(png_ptr, "sPLT chunk has bad length");
1726 dl = (png_int_32)(data_length / entry_size);
1727 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1731 png_warning(png_ptr, "sPLT chunk too long");
1735 new_palette.nentries = (png_int_32)(data_length / entry_size);
1737 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
1738 png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
1740 if (new_palette.entries == NULL)
1742 png_warning(png_ptr, "sPLT chunk requires too much memory");
1746 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1747 for (i = 0; i < new_palette.nentries; i++)
1749 pp = new_palette.entries + i;
1751 if (new_palette.depth == 8)
1753 pp->red = *entry_start++;
1754 pp->green = *entry_start++;
1755 pp->blue = *entry_start++;
1756 pp->alpha = *entry_start++;
1761 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1762 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1763 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1764 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1767 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1770 pp = new_palette.entries;
1772 for (i = 0; i < new_palette.nentries; i++)
1775 if (new_palette.depth == 8)
1777 pp[i].red = *entry_start++;
1778 pp[i].green = *entry_start++;
1779 pp[i].blue = *entry_start++;
1780 pp[i].alpha = *entry_start++;
1785 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1786 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1787 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1788 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1791 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1795 /* Discard all chunk data except the name and stash that */
1796 new_palette.name = (png_charp)buffer;
1798 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1800 png_free(png_ptr, new_palette.entries);
1802 #endif /* READ_sPLT */
1804 #ifdef PNG_READ_tRNS_SUPPORTED
1806 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1808 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1810 png_debug(1, "in png_handle_tRNS");
1812 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1813 png_chunk_error(png_ptr, "missing IHDR");
1815 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1817 png_crc_finish(png_ptr, length);
1818 png_chunk_benign_error(png_ptr, "out of place");
1822 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1824 png_crc_finish(png_ptr, length);
1825 png_chunk_benign_error(png_ptr, "duplicate");
1829 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1835 png_crc_finish(png_ptr, length);
1836 png_chunk_benign_error(png_ptr, "invalid");
1840 png_crc_read(png_ptr, buf, 2);
1841 png_ptr->num_trans = 1;
1842 png_ptr->trans_color.gray = png_get_uint_16(buf);
1845 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1851 png_crc_finish(png_ptr, length);
1852 png_chunk_benign_error(png_ptr, "invalid");
1856 png_crc_read(png_ptr, buf, length);
1857 png_ptr->num_trans = 1;
1858 png_ptr->trans_color.red = png_get_uint_16(buf);
1859 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1860 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1863 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1865 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1867 /* TODO: is this actually an error in the ISO spec? */
1868 png_crc_finish(png_ptr, length);
1869 png_chunk_benign_error(png_ptr, "out of place");
1873 if (length > (unsigned int) png_ptr->num_palette ||
1874 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1877 png_crc_finish(png_ptr, length);
1878 png_chunk_benign_error(png_ptr, "invalid");
1882 png_crc_read(png_ptr, readbuf, length);
1883 png_ptr->num_trans = (png_uint_16)length;
1888 png_crc_finish(png_ptr, length);
1889 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1893 if (png_crc_finish(png_ptr, 0) != 0)
1895 png_ptr->num_trans = 0;
1899 /* TODO: this is a horrible side effect in the palette case because the
1900 * png_struct ends up with a pointer to the tRNS buffer owned by the
1901 * png_info. Fix this.
1903 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1904 &(png_ptr->trans_color));
1908 #ifdef PNG_READ_bKGD_SUPPORTED
1910 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1912 unsigned int truelen;
1914 png_color_16 background;
1916 png_debug(1, "in png_handle_bKGD");
1918 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1919 png_chunk_error(png_ptr, "missing IHDR");
1921 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1922 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1923 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1925 png_crc_finish(png_ptr, length);
1926 png_chunk_benign_error(png_ptr, "out of place");
1930 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1932 png_crc_finish(png_ptr, length);
1933 png_chunk_benign_error(png_ptr, "duplicate");
1937 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1940 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1946 if (length != truelen)
1948 png_crc_finish(png_ptr, length);
1949 png_chunk_benign_error(png_ptr, "invalid");
1953 png_crc_read(png_ptr, buf, truelen);
1955 if (png_crc_finish(png_ptr, 0) != 0)
1958 /* We convert the index value into RGB components so that we can allow
1959 * arbitrary RGB values for background when we have transparency, and
1960 * so it is easy to determine the RGB values of the background color
1961 * from the info_ptr struct.
1963 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1965 background.index = buf[0];
1967 if (info_ptr != NULL && info_ptr->num_palette != 0)
1969 if (buf[0] >= info_ptr->num_palette)
1971 png_chunk_benign_error(png_ptr, "invalid index");
1975 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1976 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1977 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1981 background.red = background.green = background.blue = 0;
1983 background.gray = 0;
1986 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1988 background.index = 0;
1992 background.gray = png_get_uint_16(buf);
1997 background.index = 0;
1998 background.red = png_get_uint_16(buf);
1999 background.green = png_get_uint_16(buf + 2);
2000 background.blue = png_get_uint_16(buf + 4);
2001 background.gray = 0;
2004 png_set_bKGD(png_ptr, info_ptr, &background);
2008 #ifdef PNG_READ_hIST_SUPPORTED
2010 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2012 unsigned int num, i;
2013 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
2015 png_debug(1, "in png_handle_hIST");
2017 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2018 png_chunk_error(png_ptr, "missing IHDR");
2020 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
2021 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
2023 png_crc_finish(png_ptr, length);
2024 png_chunk_benign_error(png_ptr, "out of place");
2028 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
2030 png_crc_finish(png_ptr, length);
2031 png_chunk_benign_error(png_ptr, "duplicate");
2037 if (num != (unsigned int) png_ptr->num_palette ||
2038 num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
2040 png_crc_finish(png_ptr, length);
2041 png_chunk_benign_error(png_ptr, "invalid");
2045 for (i = 0; i < num; i++)
2049 png_crc_read(png_ptr, buf, 2);
2050 readbuf[i] = png_get_uint_16(buf);
2053 if (png_crc_finish(png_ptr, 0) != 0)
2056 png_set_hIST(png_ptr, info_ptr, readbuf);
2060 #ifdef PNG_READ_pHYs_SUPPORTED
2062 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2065 png_uint_32 res_x, res_y;
2068 png_debug(1, "in png_handle_pHYs");
2070 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2071 png_chunk_error(png_ptr, "missing IHDR");
2073 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2075 png_crc_finish(png_ptr, length);
2076 png_chunk_benign_error(png_ptr, "out of place");
2080 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2082 png_crc_finish(png_ptr, length);
2083 png_chunk_benign_error(png_ptr, "duplicate");
2089 png_crc_finish(png_ptr, length);
2090 png_chunk_benign_error(png_ptr, "invalid");
2094 png_crc_read(png_ptr, buf, 9);
2096 if (png_crc_finish(png_ptr, 0) != 0)
2099 res_x = png_get_uint_32(buf);
2100 res_y = png_get_uint_32(buf + 4);
2102 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2106 #ifdef PNG_READ_oFFs_SUPPORTED
2108 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2111 png_int_32 offset_x, offset_y;
2114 png_debug(1, "in png_handle_oFFs");
2116 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2117 png_chunk_error(png_ptr, "missing IHDR");
2119 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2121 png_crc_finish(png_ptr, length);
2122 png_chunk_benign_error(png_ptr, "out of place");
2126 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2128 png_crc_finish(png_ptr, length);
2129 png_chunk_benign_error(png_ptr, "duplicate");
2135 png_crc_finish(png_ptr, length);
2136 png_chunk_benign_error(png_ptr, "invalid");
2140 png_crc_read(png_ptr, buf, 9);
2142 if (png_crc_finish(png_ptr, 0) != 0)
2145 offset_x = png_get_int_32(buf);
2146 offset_y = png_get_int_32(buf + 4);
2148 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2152 #ifdef PNG_READ_pCAL_SUPPORTED
2153 /* Read the pCAL chunk (described in the PNG Extensions document) */
2155 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2158 png_byte type, nparams;
2159 png_bytep buffer, buf, units, endptr;
2163 png_debug(1, "in png_handle_pCAL");
2165 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2166 png_chunk_error(png_ptr, "missing IHDR");
2168 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2170 png_crc_finish(png_ptr, length);
2171 png_chunk_benign_error(png_ptr, "out of place");
2175 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2177 png_crc_finish(png_ptr, length);
2178 png_chunk_benign_error(png_ptr, "duplicate");
2182 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2185 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2189 png_crc_finish(png_ptr, length);
2190 png_chunk_benign_error(png_ptr, "out of memory");
2194 png_crc_read(png_ptr, buffer, length);
2196 if (png_crc_finish(png_ptr, 0) != 0)
2199 buffer[length] = 0; /* Null terminate the last string */
2201 png_debug(3, "Finding end of pCAL purpose string");
2202 for (buf = buffer; *buf; buf++)
2205 endptr = buffer + length;
2207 /* We need to have at least 12 bytes after the purpose string
2208 * in order to get the parameter information.
2210 if (endptr - buf <= 12)
2212 png_chunk_benign_error(png_ptr, "invalid");
2216 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2217 X0 = png_get_int_32((png_bytep)buf+1);
2218 X1 = png_get_int_32((png_bytep)buf+5);
2223 png_debug(3, "Checking pCAL equation type and number of parameters");
2224 /* Check that we have the right number of parameters for known
2227 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2228 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2229 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2230 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2232 png_chunk_benign_error(png_ptr, "invalid parameter count");
2236 else if (type >= PNG_EQUATION_LAST)
2238 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2241 for (buf = units; *buf; buf++)
2242 /* Empty loop to move past the units string. */ ;
2244 png_debug(3, "Allocating pCAL parameters array");
2246 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2247 nparams * (sizeof (png_charp))));
2251 png_chunk_benign_error(png_ptr, "out of memory");
2255 /* Get pointers to the start of each parameter string. */
2256 for (i = 0; i < nparams; i++)
2258 buf++; /* Skip the null string terminator from previous parameter. */
2260 png_debug1(3, "Reading pCAL parameter %d", i);
2262 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2263 /* Empty loop to move past each parameter string */ ;
2265 /* Make sure we haven't run out of data yet */
2268 png_free(png_ptr, params);
2269 png_chunk_benign_error(png_ptr, "invalid data");
2274 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2275 (png_charp)units, params);
2277 png_free(png_ptr, params);
2281 #ifdef PNG_READ_sCAL_SUPPORTED
2282 /* Read the sCAL chunk */
2284 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2290 png_debug(1, "in png_handle_sCAL");
2292 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2293 png_chunk_error(png_ptr, "missing IHDR");
2295 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2297 png_crc_finish(png_ptr, length);
2298 png_chunk_benign_error(png_ptr, "out of place");
2302 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2304 png_crc_finish(png_ptr, length);
2305 png_chunk_benign_error(png_ptr, "duplicate");
2309 /* Need unit type, width, \0, height: minimum 4 bytes */
2310 else if (length < 4)
2312 png_crc_finish(png_ptr, length);
2313 png_chunk_benign_error(png_ptr, "invalid");
2317 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2320 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2324 png_chunk_benign_error(png_ptr, "out of memory");
2325 png_crc_finish(png_ptr, length);
2329 png_crc_read(png_ptr, buffer, length);
2330 buffer[length] = 0; /* Null terminate the last string */
2332 if (png_crc_finish(png_ptr, 0) != 0)
2335 /* Validate the unit. */
2336 if (buffer[0] != 1 && buffer[0] != 2)
2338 png_chunk_benign_error(png_ptr, "invalid unit");
2342 /* Validate the ASCII numbers, need two ASCII numbers separated by
2343 * a '\0' and they need to fit exactly in the chunk data.
2348 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2349 i >= length || buffer[i++] != 0)
2350 png_chunk_benign_error(png_ptr, "bad width format");
2352 else if (PNG_FP_IS_POSITIVE(state) == 0)
2353 png_chunk_benign_error(png_ptr, "non-positive width");
2357 png_size_t heighti = i;
2360 if (png_check_fp_number((png_const_charp)buffer, length,
2361 &state, &i) == 0 || i != length)
2362 png_chunk_benign_error(png_ptr, "bad height format");
2364 else if (PNG_FP_IS_POSITIVE(state) == 0)
2365 png_chunk_benign_error(png_ptr, "non-positive height");
2368 /* This is the (only) success case. */
2369 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2370 (png_charp)buffer+1, (png_charp)buffer+heighti);
2375 #ifdef PNG_READ_tIME_SUPPORTED
2377 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2382 png_debug(1, "in png_handle_tIME");
2384 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2385 png_chunk_error(png_ptr, "missing IHDR");
2387 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2389 png_crc_finish(png_ptr, length);
2390 png_chunk_benign_error(png_ptr, "duplicate");
2394 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2395 png_ptr->mode |= PNG_AFTER_IDAT;
2399 png_crc_finish(png_ptr, length);
2400 png_chunk_benign_error(png_ptr, "invalid");
2404 png_crc_read(png_ptr, buf, 7);
2406 if (png_crc_finish(png_ptr, 0) != 0)
2409 mod_time.second = buf[6];
2410 mod_time.minute = buf[5];
2411 mod_time.hour = buf[4];
2412 mod_time.day = buf[3];
2413 mod_time.month = buf[2];
2414 mod_time.year = png_get_uint_16(buf);
2416 png_set_tIME(png_ptr, info_ptr, &mod_time);
2420 #ifdef PNG_READ_tEXt_SUPPORTED
2421 /* Note: this does not properly handle chunks that are > 64K under DOS */
2423 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2429 png_uint_32 skip = 0;
2431 png_debug(1, "in png_handle_tEXt");
2433 #ifdef PNG_USER_LIMITS_SUPPORTED
2434 if (png_ptr->user_chunk_cache_max != 0)
2436 if (png_ptr->user_chunk_cache_max == 1)
2438 png_crc_finish(png_ptr, length);
2442 if (--png_ptr->user_chunk_cache_max == 1)
2444 png_crc_finish(png_ptr, length);
2445 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2451 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2452 png_chunk_error(png_ptr, "missing IHDR");
2454 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2455 png_ptr->mode |= PNG_AFTER_IDAT;
2457 #ifdef PNG_MAX_MALLOC_64K
2458 if (length > 65535U)
2460 png_crc_finish(png_ptr, length);
2461 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2466 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2470 png_chunk_benign_error(png_ptr, "out of memory");
2474 png_crc_read(png_ptr, buffer, length);
2476 if (png_crc_finish(png_ptr, skip) != 0)
2479 key = (png_charp)buffer;
2482 for (text = key; *text; text++)
2483 /* Empty loop to find end of key */ ;
2485 if (text != key + length)
2488 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2489 text_info.key = key;
2490 text_info.lang = NULL;
2491 text_info.lang_key = NULL;
2492 text_info.itxt_length = 0;
2493 text_info.text = text;
2494 text_info.text_length = strlen(text);
2496 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2497 png_warning(png_ptr, "Insufficient memory to process text chunk");
2501 #ifdef PNG_READ_zTXt_SUPPORTED
2502 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2504 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2506 png_const_charp errmsg = NULL;
2508 png_uint_32 keyword_length;
2510 png_debug(1, "in png_handle_zTXt");
2512 #ifdef PNG_USER_LIMITS_SUPPORTED
2513 if (png_ptr->user_chunk_cache_max != 0)
2515 if (png_ptr->user_chunk_cache_max == 1)
2517 png_crc_finish(png_ptr, length);
2521 if (--png_ptr->user_chunk_cache_max == 1)
2523 png_crc_finish(png_ptr, length);
2524 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2530 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2531 png_chunk_error(png_ptr, "missing IHDR");
2533 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2534 png_ptr->mode |= PNG_AFTER_IDAT;
2536 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2540 png_crc_finish(png_ptr, length);
2541 png_chunk_benign_error(png_ptr, "out of memory");
2545 png_crc_read(png_ptr, buffer, length);
2547 if (png_crc_finish(png_ptr, 0) != 0)
2550 /* TODO: also check that the keyword contents match the spec! */
2551 for (keyword_length = 0;
2552 keyword_length < length && buffer[keyword_length] != 0;
2554 /* Empty loop to find end of name */ ;
2556 if (keyword_length > 79 || keyword_length < 1)
2557 errmsg = "bad keyword";
2559 /* zTXt must have some LZ data after the keyword, although it may expand to
2560 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2563 else if (keyword_length + 3 > length)
2564 errmsg = "truncated";
2566 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2567 errmsg = "unknown compression type";
2571 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2573 /* TODO: at present png_decompress_chunk imposes a single application
2574 * level memory limit, this should be split to different values for iCCP
2577 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2578 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2582 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
2583 * for the extra compression type byte and the fact that it isn't
2584 * necessarily '\0' terminated.
2586 buffer = png_ptr->read_buffer;
2587 buffer[uncompressed_length+(keyword_length+2)] = 0;
2589 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2590 text.key = (png_charp)buffer;
2591 text.text = (png_charp)(buffer + keyword_length+2);
2592 text.text_length = uncompressed_length;
2593 text.itxt_length = 0;
2595 text.lang_key = NULL;
2597 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2598 errmsg = "insufficient memory";
2602 errmsg = png_ptr->zstream.msg;
2606 png_chunk_benign_error(png_ptr, errmsg);
2610 #ifdef PNG_READ_iTXt_SUPPORTED
2611 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2613 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2615 png_const_charp errmsg = NULL;
2617 png_uint_32 prefix_length;
2619 png_debug(1, "in png_handle_iTXt");
2621 #ifdef PNG_USER_LIMITS_SUPPORTED
2622 if (png_ptr->user_chunk_cache_max != 0)
2624 if (png_ptr->user_chunk_cache_max == 1)
2626 png_crc_finish(png_ptr, length);
2630 if (--png_ptr->user_chunk_cache_max == 1)
2632 png_crc_finish(png_ptr, length);
2633 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2639 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2640 png_chunk_error(png_ptr, "missing IHDR");
2642 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2643 png_ptr->mode |= PNG_AFTER_IDAT;
2645 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2649 png_crc_finish(png_ptr, length);
2650 png_chunk_benign_error(png_ptr, "out of memory");
2654 png_crc_read(png_ptr, buffer, length);
2656 if (png_crc_finish(png_ptr, 0) != 0)
2659 /* First the keyword. */
2660 for (prefix_length=0;
2661 prefix_length < length && buffer[prefix_length] != 0;
2665 /* Perform a basic check on the keyword length here. */
2666 if (prefix_length > 79 || prefix_length < 1)
2667 errmsg = "bad keyword";
2669 /* Expect keyword, compression flag, compression type, language, translated
2670 * keyword (both may be empty but are 0 terminated) then the text, which may
2673 else if (prefix_length + 5 > length)
2674 errmsg = "truncated";
2676 else if (buffer[prefix_length+1] == 0 ||
2677 (buffer[prefix_length+1] == 1 &&
2678 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2680 int compressed = buffer[prefix_length+1] != 0;
2681 png_uint_32 language_offset, translated_keyword_offset;
2682 png_alloc_size_t uncompressed_length = 0;
2684 /* Now the language tag */
2686 language_offset = prefix_length;
2688 for (; prefix_length < length && buffer[prefix_length] != 0;
2692 /* WARNING: the length may be invalid here, this is checked below. */
2693 translated_keyword_offset = ++prefix_length;
2695 for (; prefix_length < length && buffer[prefix_length] != 0;
2699 /* prefix_length should now be at the trailing '\0' of the translated
2700 * keyword, but it may already be over the end. None of this arithmetic
2701 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2702 * systems the available allocation may overflow.
2706 if (compressed == 0 && prefix_length <= length)
2707 uncompressed_length = length - prefix_length;
2709 else if (compressed != 0 && prefix_length < length)
2711 uncompressed_length = PNG_SIZE_MAX;
2713 /* TODO: at present png_decompress_chunk imposes a single application
2714 * level memory limit, this should be split to different values for
2715 * iCCP and text chunks.
2717 if (png_decompress_chunk(png_ptr, length, prefix_length,
2718 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2719 buffer = png_ptr->read_buffer;
2722 errmsg = png_ptr->zstream.msg;
2726 errmsg = "truncated";
2732 buffer[uncompressed_length+prefix_length] = 0;
2734 if (compressed == 0)
2735 text.compression = PNG_ITXT_COMPRESSION_NONE;
2738 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2740 text.key = (png_charp)buffer;
2741 text.lang = (png_charp)buffer + language_offset;
2742 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2743 text.text = (png_charp)buffer + prefix_length;
2744 text.text_length = 0;
2745 text.itxt_length = uncompressed_length;
2747 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2748 errmsg = "insufficient memory";
2753 errmsg = "bad compression info";
2756 png_chunk_benign_error(png_ptr, errmsg);
2760 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2761 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2763 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2765 png_alloc_size_t limit = PNG_SIZE_MAX;
2767 if (png_ptr->unknown_chunk.data != NULL)
2769 png_free(png_ptr, png_ptr->unknown_chunk.data);
2770 png_ptr->unknown_chunk.data = NULL;
2773 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
2774 if (png_ptr->user_chunk_malloc_max > 0 &&
2775 png_ptr->user_chunk_malloc_max < limit)
2776 limit = png_ptr->user_chunk_malloc_max;
2778 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2779 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2780 limit = PNG_USER_CHUNK_MALLOC_MAX;
2783 if (length <= limit)
2785 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2786 /* The following is safe because of the PNG_SIZE_MAX init above */
2787 png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
2788 /* 'mode' is a flag array, only the bottom four bits matter here */
2789 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2792 png_ptr->unknown_chunk.data = NULL;
2796 /* Do a 'warn' here - it is handled below. */
2797 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2798 png_malloc_warn(png_ptr, length));
2802 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2804 /* This is benign because we clean up correctly */
2805 png_crc_finish(png_ptr, length);
2806 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2813 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2814 png_crc_finish(png_ptr, 0);
2818 #endif /* READ_UNKNOWN_CHUNKS */
2820 /* Handle an unknown, or known but disabled, chunk */
2822 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2823 png_uint_32 length, int keep)
2825 int handled = 0; /* the chunk was handled */
2827 png_debug(1, "in png_handle_unknown");
2829 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2830 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2831 * the bug which meant that setting a non-default behavior for a specific
2832 * chunk would be ignored (the default was always used unless a user
2833 * callback was installed).
2835 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2836 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2837 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2838 * This is just an optimization to avoid multiple calls to the lookup
2841 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2842 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2843 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2847 /* One of the following methods will read the chunk or skip it (at least one
2848 * of these is always defined because this is the only way to switch on
2849 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2851 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2852 /* The user callback takes precedence over the chunk keep value, but the
2853 * keep value is still required to validate a save of a critical chunk.
2855 if (png_ptr->read_user_chunk_fn != NULL)
2857 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2859 /* Callback to user unknown chunk handler */
2860 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2861 &png_ptr->unknown_chunk);
2864 * negative: An error occurred; png_chunk_error will be called.
2865 * zero: The chunk was not handled, the chunk will be discarded
2866 * unless png_set_keep_unknown_chunks has been used to set
2867 * a 'keep' behavior for this particular chunk, in which
2868 * case that will be used. A critical chunk will cause an
2869 * error at this point unless it is to be saved.
2870 * positive: The chunk was handled, libpng will ignore/discard it.
2873 png_chunk_error(png_ptr, "error in user chunk");
2877 /* If the keep value is 'default' or 'never' override it, but
2878 * still error out on critical chunks unless the keep value is
2879 * 'always' While this is weird it is the behavior in 1.4.12.
2880 * A possible improvement would be to obey the value set for the
2881 * chunk, but this would be an API change that would probably
2882 * damage some applications.
2884 * The png_app_warning below catches the case that matters, where
2885 * the application has not set specific save or ignore for this
2886 * chunk or global save or ignore.
2888 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2890 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2891 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2893 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2894 png_app_warning(png_ptr,
2895 "forcing save of an unhandled chunk;"
2896 " please call png_set_keep_unknown_chunks");
2897 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
2900 keep = PNG_HANDLE_CHUNK_IF_SAFE;
2904 else /* chunk was handled */
2907 /* Critical chunks can be safely discarded at this point. */
2908 keep = PNG_HANDLE_CHUNK_NEVER;
2913 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
2917 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
2918 # endif /* READ_USER_CHUNKS */
2920 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
2922 /* keep is currently just the per-chunk setting, if there was no
2923 * setting change it to the global default now (not that this may
2924 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
2925 * if not simply skip the chunk.
2927 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
2928 keep = png_ptr->unknown_default;
2930 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2931 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2932 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2934 if (png_cache_unknown_chunk(png_ptr, length) == 0)
2935 keep = PNG_HANDLE_CHUNK_NEVER;
2939 png_crc_finish(png_ptr, length);
2942 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
2943 # error no method to support READ_UNKNOWN_CHUNKS
2947 /* If here there is no read callback pointer set and no support is
2948 * compiled in to just save the unknown chunks, so simply skip this
2949 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
2950 * the app has erroneously asked for unknown chunk saving when there
2953 if (keep > PNG_HANDLE_CHUNK_NEVER)
2954 png_app_error(png_ptr, "no unknown chunk support available");
2956 png_crc_finish(png_ptr, length);
2960 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
2961 /* Now store the chunk in the chunk list if appropriate, and if the limits
2964 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2965 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2966 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2968 # ifdef PNG_USER_LIMITS_SUPPORTED
2969 switch (png_ptr->user_chunk_cache_max)
2972 png_ptr->user_chunk_cache_max = 1;
2973 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2976 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
2977 * chunk being skipped, now there will be a hard error below.
2981 default: /* not at limit */
2982 --(png_ptr->user_chunk_cache_max);
2984 case 0: /* no limit */
2985 # endif /* USER_LIMITS */
2986 /* Here when the limit isn't reached or when limits are compiled
2987 * out; store the chunk.
2989 png_set_unknown_chunks(png_ptr, info_ptr,
2990 &png_ptr->unknown_chunk, 1);
2992 # ifdef PNG_USER_LIMITS_SUPPORTED
2997 # else /* no store support: the chunk must be handled by the user callback */
2998 PNG_UNUSED(info_ptr)
3001 /* Regardless of the error handling below the cached data (if any) can be
3002 * freed now. Notice that the data is not freed if there is a png_error, but
3003 * it will be freed by destroy_read_struct.
3005 if (png_ptr->unknown_chunk.data != NULL)
3006 png_free(png_ptr, png_ptr->unknown_chunk.data);
3007 png_ptr->unknown_chunk.data = NULL;
3009 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
3010 /* There is no support to read an unknown chunk, so just skip it. */
3011 png_crc_finish(png_ptr, length);
3012 PNG_UNUSED(info_ptr)
3014 #endif /* !READ_UNKNOWN_CHUNKS */
3016 /* Check for unhandled critical chunks */
3017 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
3018 png_chunk_error(png_ptr, "unhandled critical chunk");
3021 /* This function is called to verify that a chunk name is valid.
3022 * This function can't have the "critical chunk check" incorporated
3023 * into it, since in the future we will need to be able to call user
3024 * functions to handle unknown critical chunks after we check that
3025 * the chunk name itself is valid.
3028 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
3030 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
3034 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
3038 png_debug(1, "in png_check_chunk_name");
3040 for (i=1; i<=4; ++i)
3042 int c = chunk_name & 0xff;
3044 if (c < 65 || c > 122 || (c > 90 && c < 97))
3045 png_chunk_error(png_ptr, "invalid chunk type");
3051 /* Combines the row recently read in with the existing pixels in the row. This
3052 * routine takes care of alpha and transparency if requested. This routine also
3053 * handles the two methods of progressive display of interlaced images,
3054 * depending on the 'display' value; if 'display' is true then the whole row
3055 * (dp) is filled from the start by replicating the available pixels. If
3056 * 'display' is false only those pixels present in the pass are filled in.
3059 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3061 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3062 png_const_bytep sp = png_ptr->row_buf + 1;
3063 png_alloc_size_t row_width = png_ptr->width;
3064 unsigned int pass = png_ptr->pass;
3065 png_bytep end_ptr = 0;
3066 png_byte end_byte = 0;
3067 unsigned int end_mask;
3069 png_debug(1, "in png_combine_row");
3071 /* Added in 1.5.6: it should not be possible to enter this routine until at
3072 * least one row has been read from the PNG data and transformed.
3074 if (pixel_depth == 0)
3075 png_error(png_ptr, "internal row logic error");
3077 /* Added in 1.5.4: the pixel depth should match the information returned by
3078 * any call to png_read_update_info at this point. Do not continue if we got
3081 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3082 PNG_ROWBYTES(pixel_depth, row_width))
3083 png_error(png_ptr, "internal row size calculation error");
3085 /* Don't expect this to ever happen: */
3087 png_error(png_ptr, "internal row width error");
3089 /* Preserve the last byte in cases where only part of it will be overwritten,
3090 * the multiply below may overflow, we don't care because ANSI-C guarantees
3091 * we get the low bits.
3093 end_mask = (pixel_depth * row_width) & 7;
3096 /* end_ptr == NULL is a flag to say do nothing */
3097 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3098 end_byte = *end_ptr;
3099 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3100 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3101 /* little-endian byte */
3102 end_mask = 0xff << end_mask;
3104 else /* big-endian byte */
3106 end_mask = 0xff >> end_mask;
3107 /* end_mask is now the bits to *keep* from the destination row */
3110 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3111 * will also happen if interlacing isn't supported or if the application
3112 * does not call png_set_interlace_handling(). In the latter cases the
3113 * caller just gets a sequence of the unexpanded rows from each interlace
3116 #ifdef PNG_READ_INTERLACING_SUPPORTED
3117 if (png_ptr->interlaced != 0 &&
3118 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3119 pass < 6 && (display == 0 ||
3120 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3121 (display == 1 && (pass & 1) != 0)))
3123 /* Narrow images may have no bits in a pass; the caller should handle
3124 * this, but this test is cheap:
3126 if (row_width <= PNG_PASS_START_COL(pass))
3129 if (pixel_depth < 8)
3131 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3132 * into 32 bits, then a single loop over the bytes using the four byte
3133 * values in the 32-bit mask can be used. For the 'display' option the
3134 * expanded mask may also not require any masking within a byte. To
3135 * make this work the PACKSWAP option must be taken into account - it
3136 * simply requires the pixels to be reversed in each byte.
3138 * The 'regular' case requires a mask for each of the first 6 passes,
3139 * the 'display' case does a copy for the even passes in the range
3140 * 0..6. This has already been handled in the test above.
3142 * The masks are arranged as four bytes with the first byte to use in
3143 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3144 * not) of the pixels in each byte.
3146 * NOTE: the whole of this logic depends on the caller of this function
3147 * only calling it on rows appropriate to the pass. This function only
3148 * understands the 'x' logic; the 'y' logic is handled by the caller.
3150 * The following defines allow generation of compile time constant bit
3151 * masks for each pixel depth and each possibility of swapped or not
3152 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3153 * is in the range 0..7; and the result is 1 if the pixel is to be
3154 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3155 * for the block method.
3157 * With some compilers a compile time expression of the general form:
3159 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3161 * Produces warnings with values of 'shift' in the range 33 to 63
3162 * because the right hand side of the ?: expression is evaluated by
3163 * the compiler even though it isn't used. Microsoft Visual C (various
3164 * versions) and the Intel C compiler are known to do this. To avoid
3165 * this the following macros are used in 1.5.6. This is a temporary
3166 * solution to avoid destabilizing the code during the release process.
3168 # if PNG_USE_COMPILE_TIME_MASKS
3169 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3170 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3172 # define PNG_LSR(x,s) ((x)>>(s))
3173 # define PNG_LSL(x,s) ((x)<<(s))
3175 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3176 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3177 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3178 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3180 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3181 * little endian - the first pixel is at bit 0 - however the extra
3182 * parameter 's' can be set to cause the mask position to be swapped
3183 * within each byte, to match the PNG format. This is done by XOR of
3184 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3186 # define PIXEL_MASK(p,x,d,s) \
3187 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3189 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3191 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3192 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3194 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3195 * cases the result needs replicating, for the 4-bpp case the above
3196 * generates a full 32 bits.
3198 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3200 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3201 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3202 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3204 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3205 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3206 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3208 #if PNG_USE_COMPILE_TIME_MASKS
3209 /* Utility macros to construct all the masks for a depth/swap
3210 * combination. The 's' parameter says whether the format is PNG
3211 * (big endian bytes) or not. Only the three odd-numbered passes are
3212 * required for the display/block algorithm.
3214 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3215 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3217 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3219 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3221 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3224 static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3226 /* Little-endian byte masks for PACKSWAP */
3227 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3228 /* Normal (big-endian byte) masks - PNG format */
3229 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3232 /* display_mask has only three entries for the odd passes, so index by
3235 static PNG_CONST png_uint_32 display_mask[2][3][3] =
3237 /* Little-endian byte masks for PACKSWAP */
3238 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3239 /* Normal (big-endian byte) masks - PNG format */
3240 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3243 # define MASK(pass,depth,display,png)\
3244 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3245 row_mask[png][DEPTH_INDEX(depth)][pass])
3247 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3248 /* This is the runtime alternative: it seems unlikely that this will
3249 * ever be either smaller or faster than the compile time approach.
3251 # define MASK(pass,depth,display,png)\
3252 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3253 #endif /* !USE_COMPILE_TIME_MASKS */
3255 /* Use the appropriate mask to copy the required bits. In some cases
3256 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3257 * the number of pixels, but the code copies bytes, so it is necessary
3258 * to special case the end.
3260 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3263 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3264 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3265 mask = MASK(pass, pixel_depth, display, 0);
3269 mask = MASK(pass, pixel_depth, display, 1);
3275 /* It doesn't matter in the following if png_uint_32 has more than
3276 * 32 bits because the high bits always match those in m<<24; it is,
3277 * however, essential to use OR here, not +, because of this.
3280 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3283 if (m != 0) /* something to copy */
3286 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3291 /* NOTE: this may overwrite the last byte with garbage if the image
3292 * is not an exact number of bytes wide; libpng has always done
3295 if (row_width <= pixels_per_byte)
3296 break; /* May need to restore part of the last byte */
3298 row_width -= pixels_per_byte;
3304 else /* pixel_depth >= 8 */
3306 unsigned int bytes_to_copy, bytes_to_jump;
3308 /* Validate the depth - it must be a multiple of 8 */
3309 if (pixel_depth & 7)
3310 png_error(png_ptr, "invalid user transform pixel depth");
3312 pixel_depth >>= 3; /* now in bytes */
3313 row_width *= pixel_depth;
3315 /* Regardless of pass number the Adam 7 interlace always results in a
3316 * fixed number of pixels to copy then to skip. There may be a
3317 * different number of pixels to skip at the start though.
3320 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3322 row_width -= offset;
3327 /* Work out the bytes to copy. */
3330 /* When doing the 'block' algorithm the pixel in the pass gets
3331 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3332 * passes are skipped above - the entire expanded row is copied.
3334 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3336 /* But don't allow this number to exceed the actual row width. */
3337 if (bytes_to_copy > row_width)
3338 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3341 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3342 bytes_to_copy = pixel_depth;
3344 /* In Adam7 there is a constant offset between where the pixels go. */
3345 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3347 /* And simply copy these bytes. Some optimization is possible here,
3348 * depending on the value of 'bytes_to_copy'. Special case the low
3349 * byte counts, which we know to be frequent.
3351 * Notice that these cases all 'return' rather than 'break' - this
3352 * avoids an unnecessary test on whether to restore the last byte
3355 switch (bytes_to_copy)
3362 if (row_width <= bytes_to_jump)
3365 dp += bytes_to_jump;
3366 sp += bytes_to_jump;
3367 row_width -= bytes_to_jump;
3371 /* There is a possibility of a partial copy at the end here; this
3372 * slows the code down somewhat.
3376 dp[0] = sp[0], dp[1] = sp[1];
3378 if (row_width <= bytes_to_jump)
3381 sp += bytes_to_jump;
3382 dp += bytes_to_jump;
3383 row_width -= bytes_to_jump;
3385 while (row_width > 1);
3387 /* And there can only be one byte left at this point: */
3392 /* This can only be the RGB case, so each copy is exactly one
3393 * pixel and it is not necessary to check for a partial copy.
3397 dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
3399 if (row_width <= bytes_to_jump)
3402 sp += bytes_to_jump;
3403 dp += bytes_to_jump;
3404 row_width -= bytes_to_jump;
3408 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3409 /* Check for double byte alignment and, if possible, use a
3410 * 16-bit copy. Don't attempt this for narrow images - ones that
3411 * are less than an interlace panel wide. Don't attempt it for
3412 * wide bytes_to_copy either - use the memcpy there.
3414 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3415 png_isaligned(dp, png_uint_16) &&
3416 png_isaligned(sp, png_uint_16) &&
3417 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3418 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3420 /* Everything is aligned for png_uint_16 copies, but try for
3421 * png_uint_32 first.
3423 if (png_isaligned(dp, png_uint_32) &&
3424 png_isaligned(sp, png_uint_32) &&
3425 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3426 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3428 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3429 png_const_uint_32p sp32 = png_aligncastconst(
3430 png_const_uint_32p, sp);
3431 size_t skip = (bytes_to_jump-bytes_to_copy) /
3432 (sizeof (png_uint_32));
3436 size_t c = bytes_to_copy;
3440 c -= (sizeof (png_uint_32));
3444 if (row_width <= bytes_to_jump)
3449 row_width -= bytes_to_jump;
3451 while (bytes_to_copy <= row_width);
3453 /* Get to here when the row_width truncates the final copy.
3454 * There will be 1-3 bytes left to copy, so don't try the
3455 * 16-bit loop below.
3457 dp = (png_bytep)dp32;
3458 sp = (png_const_bytep)sp32;
3461 while (--row_width > 0);
3465 /* Else do it in 16-bit quantities, but only if the size is
3470 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3471 png_const_uint_16p sp16 = png_aligncastconst(
3472 png_const_uint_16p, sp);
3473 size_t skip = (bytes_to_jump-bytes_to_copy) /
3474 (sizeof (png_uint_16));
3478 size_t c = bytes_to_copy;
3482 c -= (sizeof (png_uint_16));
3486 if (row_width <= bytes_to_jump)
3491 row_width -= bytes_to_jump;
3493 while (bytes_to_copy <= row_width);
3495 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3496 dp = (png_bytep)dp16;
3497 sp = (png_const_bytep)sp16;
3500 while (--row_width > 0);
3504 #endif /* ALIGN_TYPE code */
3506 /* The true default - use a memcpy: */
3509 memcpy(dp, sp, bytes_to_copy);
3511 if (row_width <= bytes_to_jump)
3514 sp += bytes_to_jump;
3515 dp += bytes_to_jump;
3516 row_width -= bytes_to_jump;
3517 if (bytes_to_copy > row_width)
3518 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3523 } /* pixel_depth >= 8 */
3525 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3528 #endif /* READ_INTERLACING */
3530 /* If here then the switch above wasn't used so just memcpy the whole row
3531 * from the temporary row buffer (notice that this overwrites the end of the
3532 * destination row if it is a partial byte.)
3534 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3536 /* Restore the overwritten bits from the last byte if necessary. */
3537 if (end_ptr != NULL)
3538 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3541 #ifdef PNG_READ_INTERLACING_SUPPORTED
3543 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3544 png_uint_32 transformations /* Because these may affect the byte layout */)
3546 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3547 /* Offset to next interlace block */
3548 static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3550 png_debug(1, "in png_do_read_interlace");
3551 if (row != NULL && row_info != NULL)
3553 png_uint_32 final_width;
3555 final_width = row_info->width * png_pass_inc[pass];
3557 switch (row_info->pixel_depth)
3561 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
3562 png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
3564 int s_start, s_end, s_inc;
3565 int jstop = png_pass_inc[pass];
3570 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3571 if ((transformations & PNG_PACKSWAP) != 0)
3573 sshift = (int)((row_info->width + 7) & 0x07);
3574 dshift = (int)((final_width + 7) & 0x07);
3583 sshift = 7 - (int)((row_info->width + 7) & 0x07);
3584 dshift = 7 - (int)((final_width + 7) & 0x07);
3590 for (i = 0; i < row_info->width; i++)
3592 v = (png_byte)((*sp >> sshift) & 0x01);
3593 for (j = 0; j < jstop; j++)
3595 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3597 *dp = (png_byte)(tmp & 0xff);
3599 if (dshift == s_end)
3609 if (sshift == s_end)
3623 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3624 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3626 int s_start, s_end, s_inc;
3627 int jstop = png_pass_inc[pass];
3630 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3631 if ((transformations & PNG_PACKSWAP) != 0)
3633 sshift = (int)(((row_info->width + 3) & 0x03) << 1);
3634 dshift = (int)(((final_width + 3) & 0x03) << 1);
3643 sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
3644 dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
3650 for (i = 0; i < row_info->width; i++)
3655 v = (png_byte)((*sp >> sshift) & 0x03);
3656 for (j = 0; j < jstop; j++)
3658 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3660 *dp = (png_byte)(tmp & 0xff);
3662 if (dshift == s_end)
3672 if (sshift == s_end)
3686 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
3687 png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
3689 int s_start, s_end, s_inc;
3691 int jstop = png_pass_inc[pass];
3693 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3694 if ((transformations & PNG_PACKSWAP) != 0)
3696 sshift = (int)(((row_info->width + 1) & 0x01) << 2);
3697 dshift = (int)(((final_width + 1) & 0x01) << 2);
3706 sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
3707 dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
3713 for (i = 0; i < row_info->width; i++)
3715 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
3718 for (j = 0; j < jstop; j++)
3720 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
3722 *dp = (png_byte)(tmp & 0xff);
3724 if (dshift == s_end)
3734 if (sshift == s_end)
3748 png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
3750 png_bytep sp = row + (png_size_t)(row_info->width - 1)
3753 png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
3755 int jstop = png_pass_inc[pass];
3758 for (i = 0; i < row_info->width; i++)
3760 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
3763 memcpy(v, sp, pixel_bytes);
3765 for (j = 0; j < jstop; j++)
3767 memcpy(dp, v, pixel_bytes);
3777 row_info->width = final_width;
3778 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
3780 #ifndef PNG_READ_PACKSWAP_SUPPORTED
3781 PNG_UNUSED(transformations) /* Silence compiler warning */
3784 #endif /* READ_INTERLACING */
3787 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
3788 png_const_bytep prev_row)
3791 png_size_t istop = row_info->rowbytes;
3792 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3793 png_bytep rp = row + bpp;
3795 PNG_UNUSED(prev_row)
3797 for (i = bpp; i < istop; i++)
3799 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
3805 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
3806 png_const_bytep prev_row)
3809 png_size_t istop = row_info->rowbytes;
3811 png_const_bytep pp = prev_row;
3813 for (i = 0; i < istop; i++)
3815 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
3821 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
3822 png_const_bytep prev_row)
3826 png_const_bytep pp = prev_row;
3827 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3828 png_size_t istop = row_info->rowbytes - bpp;
3830 for (i = 0; i < bpp; i++)
3832 *rp = (png_byte)(((int)(*rp) +
3833 ((int)(*pp++) / 2 )) & 0xff);
3838 for (i = 0; i < istop; i++)
3840 *rp = (png_byte)(((int)(*rp) +
3841 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
3848 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
3849 png_const_bytep prev_row)
3851 png_bytep rp_end = row + row_info->rowbytes;
3854 /* First pixel/byte */
3857 *row++ = (png_byte)a;
3860 while (row < rp_end)
3862 int b, pa, pb, pc, p;
3864 a &= 0xff; /* From previous iteration or start */
3875 pa = p < 0 ? -p : p;
3876 pb = pc < 0 ? -pc : pc;
3877 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3880 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
3881 * ones in the case of a tie.
3883 if (pb < pa) pa = pb, a = b;
3886 /* Calculate the current pixel in a, and move the previous row pixel to c
3887 * for the next time round the loop
3891 *row++ = (png_byte)a;
3896 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
3897 png_const_bytep prev_row)
3899 int bpp = (row_info->pixel_depth + 7) >> 3;
3900 png_bytep rp_end = row + bpp;
3902 /* Process the first pixel in the row completely (this is the same as 'up'
3903 * because there is only one candidate predictor for the first row).
3905 while (row < rp_end)
3907 int a = *row + *prev_row++;
3908 *row++ = (png_byte)a;
3912 rp_end += row_info->rowbytes - bpp;
3914 while (row < rp_end)
3916 int a, b, c, pa, pb, pc, p;
3918 c = *(prev_row - bpp);
3930 pa = p < 0 ? -p : p;
3931 pb = pc < 0 ? -pc : pc;
3932 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3935 if (pb < pa) pa = pb, a = b;
3939 *row++ = (png_byte)a;
3944 png_init_filter_functions(png_structrp pp)
3945 /* This function is called once for every PNG image (except for PNG images
3946 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
3947 * implementations required to reverse the filtering of PNG rows. Reversing
3948 * the filter is the first transformation performed on the row data. It is
3949 * performed in place, therefore an implementation can be selected based on
3950 * the image pixel format. If the implementation depends on image width then
3951 * take care to ensure that it works correctly if the image is interlaced -
3952 * interlacing causes the actual row width to vary.
3955 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
3957 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
3958 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
3959 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
3961 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3962 png_read_filter_row_paeth_1byte_pixel;
3964 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3965 png_read_filter_row_paeth_multibyte_pixel;
3967 #ifdef PNG_FILTER_OPTIMIZATIONS
3968 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
3969 * call to install hardware optimizations for the above functions; simply
3970 * replace whatever elements of the pp->read_filter[] array with a hardware
3971 * specific (or, for that matter, generic) optimization.
3973 * To see an example of this examine what configure.ac does when
3974 * --enable-arm-neon is specified on the command line.
3976 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
3981 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
3982 png_const_bytep prev_row, int filter)
3984 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
3985 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
3986 * implementations. See png_init_filter_functions above.
3988 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
3990 if (pp->read_filter[0] == NULL)
3991 png_init_filter_functions(pp);
3993 pp->read_filter[filter-1](row_info, row, prev_row);
3997 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
3999 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
4000 png_alloc_size_t avail_out)
4002 /* Loop reading IDATs and decompressing the result into output[avail_out] */
4003 png_ptr->zstream.next_out = output;
4004 png_ptr->zstream.avail_out = 0; /* safety: set below */
4012 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
4014 if (png_ptr->zstream.avail_in == 0)
4019 while (png_ptr->idat_size == 0)
4021 png_crc_finish(png_ptr, 0);
4023 png_ptr->idat_size = png_read_chunk_header(png_ptr);
4024 /* This is an error even in the 'check' case because the code just
4025 * consumed a non-IDAT header.
4027 if (png_ptr->chunk_name != png_IDAT)
4028 png_error(png_ptr, "Not enough image data");
4031 avail_in = png_ptr->IDAT_read_size;
4033 if (avail_in > png_ptr->idat_size)
4034 avail_in = (uInt)png_ptr->idat_size;
4036 /* A PNG with a gradually increasing IDAT size will defeat this attempt
4037 * to minimize memory usage by causing lots of re-allocs, but
4038 * realistically doing IDAT_read_size re-allocs is not likely to be a
4041 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
4043 png_crc_read(png_ptr, buffer, avail_in);
4044 png_ptr->idat_size -= avail_in;
4046 png_ptr->zstream.next_in = buffer;
4047 png_ptr->zstream.avail_in = avail_in;
4050 /* And set up the output side. */
4051 if (output != NULL) /* standard read */
4053 uInt out = ZLIB_IO_MAX;
4055 if (out > avail_out)
4056 out = (uInt)avail_out;
4059 png_ptr->zstream.avail_out = out;
4062 else /* after last row, checking for end */
4064 png_ptr->zstream.next_out = tmpbuf;
4065 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4068 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4069 * process. If the LZ stream is truncated the sequential reader will
4070 * terminally damage the stream, above, by reading the chunk header of the
4071 * following chunk (it then exits with png_error).
4073 * TODO: deal more elegantly with truncated IDAT lists.
4075 ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);
4077 /* Take the unconsumed output back. */
4079 avail_out += png_ptr->zstream.avail_out;
4081 else /* avail_out counts the extra bytes */
4082 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4084 png_ptr->zstream.avail_out = 0;
4086 if (ret == Z_STREAM_END)
4088 /* Do this for safety; we won't read any more into this row. */
4089 png_ptr->zstream.next_out = NULL;
4091 png_ptr->mode |= PNG_AFTER_IDAT;
4092 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4094 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4095 png_chunk_benign_error(png_ptr, "Extra compressed data");
4101 png_zstream_error(png_ptr, ret);
4104 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4108 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4112 } while (avail_out > 0);
4116 /* The stream ended before the image; this is the same as too few IDATs so
4117 * should be handled the same way.
4120 png_error(png_ptr, "Not enough image data");
4122 else /* the deflate stream contained extra data */
4123 png_chunk_benign_error(png_ptr, "Too much image data");
4128 png_read_finish_IDAT(png_structrp png_ptr)
4130 /* We don't need any more data and the stream should have ended, however the
4131 * LZ end code may actually not have been processed. In this case we must
4132 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4133 * may still remain to be consumed.
4135 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4137 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4138 * the compressed stream, but the stream may be damaged too, so even after
4139 * this call we may need to terminate the zstream ownership.
4141 png_read_IDAT_data(png_ptr, NULL, 0);
4142 png_ptr->zstream.next_out = NULL; /* safety */
4144 /* Now clear everything out for safety; the following may not have been
4147 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4149 png_ptr->mode |= PNG_AFTER_IDAT;
4150 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4154 /* If the zstream has not been released do it now *and* terminate the reading
4155 * of the final IDAT chunk.
4157 if (png_ptr->zowner == png_IDAT)
4159 /* Always do this; the pointers otherwise point into the read buffer. */
4160 png_ptr->zstream.next_in = NULL;
4161 png_ptr->zstream.avail_in = 0;
4163 /* Now we no longer own the zstream. */
4164 png_ptr->zowner = 0;
4166 /* The slightly weird semantics of the sequential IDAT reading is that we
4167 * are always in or at the end of an IDAT chunk, so we always need to do a
4168 * crc_finish here. If idat_size is non-zero we also need to read the
4169 * spurious bytes at the end of the chunk now.
4171 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4176 png_read_finish_row(png_structrp png_ptr)
4178 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4180 /* Start of interlace block */
4181 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4183 /* Offset to next interlace block */
4184 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4186 /* Start of interlace block in the y direction */
4187 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4189 /* Offset to next interlace block in the y direction */
4190 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4192 png_debug(1, "in png_read_finish_row");
4193 png_ptr->row_number++;
4194 if (png_ptr->row_number < png_ptr->num_rows)
4197 if (png_ptr->interlaced != 0)
4199 png_ptr->row_number = 0;
4201 /* TO DO: don't do this if prev_row isn't needed (requires
4202 * read-ahead of the next row's filter byte.
4204 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4210 if (png_ptr->pass >= 7)
4213 png_ptr->iwidth = (png_ptr->width +
4214 png_pass_inc[png_ptr->pass] - 1 -
4215 png_pass_start[png_ptr->pass]) /
4216 png_pass_inc[png_ptr->pass];
4218 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4220 png_ptr->num_rows = (png_ptr->height +
4221 png_pass_yinc[png_ptr->pass] - 1 -
4222 png_pass_ystart[png_ptr->pass]) /
4223 png_pass_yinc[png_ptr->pass];
4226 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4227 break; /* libpng deinterlacing sees every row */
4229 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4231 if (png_ptr->pass < 7)
4235 /* Here after at the end of the last row of the last pass. */
4236 png_read_finish_IDAT(png_ptr);
4238 #endif /* SEQUENTIAL_READ */
4241 png_read_start_row(png_structrp png_ptr)
4243 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4245 /* Start of interlace block */
4246 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4248 /* Offset to next interlace block */
4249 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4251 /* Start of interlace block in the y direction */
4252 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4254 /* Offset to next interlace block in the y direction */
4255 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4257 int max_pixel_depth;
4258 png_size_t row_bytes;
4260 png_debug(1, "in png_read_start_row");
4262 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4263 png_init_read_transformations(png_ptr);
4265 if (png_ptr->interlaced != 0)
4267 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4268 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4269 png_pass_ystart[0]) / png_pass_yinc[0];
4272 png_ptr->num_rows = png_ptr->height;
4274 png_ptr->iwidth = (png_ptr->width +
4275 png_pass_inc[png_ptr->pass] - 1 -
4276 png_pass_start[png_ptr->pass]) /
4277 png_pass_inc[png_ptr->pass];
4282 png_ptr->num_rows = png_ptr->height;
4283 png_ptr->iwidth = png_ptr->width;
4286 max_pixel_depth = png_ptr->pixel_depth;
4288 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4289 * calculations to calculate the final pixel depth, then
4290 * png_do_read_transforms actually does the transforms. This means that the
4291 * code which effectively calculates this value is actually repeated in three
4292 * separate places. They must all match. Innocent changes to the order of
4293 * transformations can and will break libpng in a way that causes memory
4298 #ifdef PNG_READ_PACK_SUPPORTED
4299 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4300 max_pixel_depth = 8;
4303 #ifdef PNG_READ_EXPAND_SUPPORTED
4304 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4306 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4308 if (png_ptr->num_trans != 0)
4309 max_pixel_depth = 32;
4312 max_pixel_depth = 24;
4315 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4317 if (max_pixel_depth < 8)
4318 max_pixel_depth = 8;
4320 if (png_ptr->num_trans != 0)
4321 max_pixel_depth *= 2;
4324 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4326 if (png_ptr->num_trans != 0)
4328 max_pixel_depth *= 4;
4329 max_pixel_depth /= 3;
4335 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4336 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4338 # ifdef PNG_READ_EXPAND_SUPPORTED
4339 /* In fact it is an error if it isn't supported, but checking is
4342 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4344 if (png_ptr->bit_depth < 16)
4345 max_pixel_depth *= 2;
4349 png_ptr->transformations &= ~PNG_EXPAND_16;
4353 #ifdef PNG_READ_FILLER_SUPPORTED
4354 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4356 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4358 if (max_pixel_depth <= 8)
4359 max_pixel_depth = 16;
4362 max_pixel_depth = 32;
4365 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4366 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4368 if (max_pixel_depth <= 32)
4369 max_pixel_depth = 32;
4372 max_pixel_depth = 64;
4377 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4378 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4381 #ifdef PNG_READ_EXPAND_SUPPORTED
4382 (png_ptr->num_trans != 0 &&
4383 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4385 #ifdef PNG_READ_FILLER_SUPPORTED
4386 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4388 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4390 if (max_pixel_depth <= 16)
4391 max_pixel_depth = 32;
4394 max_pixel_depth = 64;
4399 if (max_pixel_depth <= 8)
4401 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4402 max_pixel_depth = 32;
4405 max_pixel_depth = 24;
4408 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4409 max_pixel_depth = 64;
4412 max_pixel_depth = 48;
4417 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4418 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4419 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4421 int user_pixel_depth = png_ptr->user_transform_depth *
4422 png_ptr->user_transform_channels;
4424 if (user_pixel_depth > max_pixel_depth)
4425 max_pixel_depth = user_pixel_depth;
4429 /* This value is stored in png_struct and double checked in the row read
4432 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4433 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4435 /* Align the width on the next larger 8 pixels. Mainly used
4438 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4439 /* Calculate the maximum bytes needed, adding a byte and a pixel
4442 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4443 1 + ((max_pixel_depth + 7) >> 3);
4445 #ifdef PNG_MAX_MALLOC_64K
4446 if (row_bytes > (png_uint_32)65536L)
4447 png_error(png_ptr, "This image requires a row greater than 64KB");
4450 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4452 png_free(png_ptr, png_ptr->big_row_buf);
4453 png_free(png_ptr, png_ptr->big_prev_row);
4455 if (png_ptr->interlaced != 0)
4456 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4460 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4462 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4464 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4465 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4466 * of padding before and after row_buf; treat prev_row similarly.
4467 * NOTE: the alignment is to the start of the pixels, one beyond the start
4468 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4469 * was incorrect; the filter byte was aligned, which had the exact
4470 * opposite effect of that intended.
4473 png_bytep temp = png_ptr->big_row_buf + 32;
4474 int extra = (int)((temp - (png_bytep)0) & 0x0f);
4475 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4477 temp = png_ptr->big_prev_row + 32;
4478 extra = (int)((temp - (png_bytep)0) & 0x0f);
4479 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4483 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4484 png_ptr->row_buf = png_ptr->big_row_buf + 31;
4485 png_ptr->prev_row = png_ptr->big_prev_row + 31;
4487 png_ptr->old_big_row_buf_size = row_bytes + 48;
4490 #ifdef PNG_MAX_MALLOC_64K
4491 if (png_ptr->rowbytes > 65535)
4492 png_error(png_ptr, "This image requires a row greater than 64KB");
4495 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4496 png_error(png_ptr, "Row has too many bytes to allocate in memory");
4498 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4500 png_debug1(3, "width = %u,", png_ptr->width);
4501 png_debug1(3, "height = %u,", png_ptr->height);
4502 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4503 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4504 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4505 png_debug1(3, "irowbytes = %lu",
4506 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4508 /* The sequential reader needs a buffer for IDAT, but the progressive reader
4509 * does not, so free the read buffer now regardless; the sequential reader
4510 * reallocates it on demand.
4512 if (png_ptr->read_buffer != 0)
4514 png_bytep buffer = png_ptr->read_buffer;
4516 png_ptr->read_buffer_size = 0;
4517 png_ptr->read_buffer = NULL;
4518 png_free(png_ptr, buffer);
4521 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4522 * value from the stream (note that this will result in a fatal error if the
4523 * IDAT stream has a bogus deflate header window_bits value, but this should
4524 * not be happening any longer!)
4526 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4527 png_error(png_ptr, png_ptr->zstream.msg);
4529 png_ptr->flags |= PNG_FLAG_ROW_INIT;