2 /* pngrutil.c - utilities to read a PNG file
4 * Copyright (c) 2018 Cosmin Truta
5 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6 * Copyright (c) 1996-1997 Andreas Dilger
7 * 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.
22 #ifdef PNG_READ_SUPPORTED
25 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
27 png_uint_32 uval = png_get_uint_32(buf);
29 if (uval > PNG_UINT_31_MAX)
30 png_error(png_ptr, "PNG unsigned integer out of range");
35 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
36 /* The following is a variation on the above for use with the fixed
37 * point values used for gAMA and cHRM. Instead of png_error it
38 * issues a warning and returns (-1) - an invalid value because both
39 * gAMA and cHRM use *unsigned* integers for fixed point values.
41 #define PNG_FIXED_ERROR (-1)
43 static png_fixed_point /* PRIVATE */
44 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
46 png_uint_32 uval = png_get_uint_32(buf);
48 if (uval <= PNG_UINT_31_MAX)
49 return (png_fixed_point)uval; /* known to be in range */
51 /* The caller can turn off the warning by passing NULL. */
53 png_warning(png_ptr, "PNG fixed point integer out of range");
55 return PNG_FIXED_ERROR;
59 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
60 /* NOTE: the read macros will obscure these definitions, so that if
61 * PNG_USE_READ_MACROS is set the library will not use them internally,
62 * but the APIs will still be available externally.
64 * The parentheses around "PNGAPI function_name" in the following three
65 * functions are necessary because they allow the macros to co-exist with
66 * these (unused but exported) functions.
69 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
71 png_get_uint_32)(png_const_bytep buf)
74 ((png_uint_32)(*(buf )) << 24) +
75 ((png_uint_32)(*(buf + 1)) << 16) +
76 ((png_uint_32)(*(buf + 2)) << 8) +
77 ((png_uint_32)(*(buf + 3)) ) ;
82 /* Grab a signed 32-bit integer from a buffer in big-endian format. The
83 * data is stored in the PNG file in two's complement format and there
84 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
85 * the following code does a two's complement to native conversion.
88 png_get_int_32)(png_const_bytep buf)
90 png_uint_32 uval = png_get_uint_32(buf);
91 if ((uval & 0x80000000) == 0) /* non-negative */
92 return (png_int_32)uval;
94 uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */
95 if ((uval & 0x80000000) == 0) /* no overflow */
96 return -(png_int_32)uval;
97 /* The following has to be safe; this function only gets called on PNG data
98 * and if we get here that data is invalid. 0 is the most safe value and
99 * if not then an attacker would surely just generate a PNG with 0 instead.
104 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
106 png_get_uint_16)(png_const_bytep buf)
108 /* ANSI-C requires an int value to accommodate at least 16 bits so this
109 * works and allows the compiler not to worry about possible narrowing
110 * on 32-bit systems. (Pre-ANSI systems did not make integers smaller
111 * than 16 bits either.)
114 ((unsigned int)(*buf) << 8) +
115 ((unsigned int)(*(buf + 1)));
117 return (png_uint_16)val;
120 #endif /* READ_INT_FUNCTIONS */
122 /* Read and check the PNG file signature */
124 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
126 size_t num_checked, num_to_check;
128 /* Exit if the user application does not expect a signature. */
129 if (png_ptr->sig_bytes >= 8)
132 num_checked = png_ptr->sig_bytes;
133 num_to_check = 8 - num_checked;
135 #ifdef PNG_IO_STATE_SUPPORTED
136 png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
139 /* The signature must be serialized in a single I/O call. */
140 png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
141 png_ptr->sig_bytes = 8;
143 if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
145 if (num_checked < 4 &&
146 png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
147 png_error(png_ptr, "Not a PNG file");
149 png_error(png_ptr, "PNG file corrupted by ASCII conversion");
152 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
155 /* Read the chunk header (length + type name).
156 * Put the type name into png_ptr->chunk_name, and return the length.
158 png_uint_32 /* PRIVATE */
159 png_read_chunk_header(png_structrp png_ptr)
164 #ifdef PNG_IO_STATE_SUPPORTED
165 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
168 /* Read the length and the chunk name.
169 * This must be performed in a single I/O call.
171 png_read_data(png_ptr, buf, 8);
172 length = png_get_uint_31(png_ptr, buf);
174 /* Put the chunk name into png_ptr->chunk_name. */
175 png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
177 png_debug2(0, "Reading %lx chunk, length = %lu",
178 (unsigned long)png_ptr->chunk_name, (unsigned long)length);
180 /* Reset the crc and run it over the chunk name. */
181 png_reset_crc(png_ptr);
182 png_calculate_crc(png_ptr, buf + 4, 4);
184 /* Check to see if chunk name is valid. */
185 png_check_chunk_name(png_ptr, png_ptr->chunk_name);
187 /* Check for too-large chunk length */
188 png_check_chunk_length(png_ptr, length);
190 #ifdef PNG_IO_STATE_SUPPORTED
191 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
197 /* Read data, and (optionally) run it through the CRC. */
199 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
204 png_read_data(png_ptr, buf, length);
205 png_calculate_crc(png_ptr, buf, length);
208 /* Optionally skip data and then check the CRC. Depending on whether we
209 * are reading an ancillary or critical chunk, and how the program has set
210 * things up, we may calculate the CRC on the data and print a message.
211 * Returns '1' if there was a CRC error, '0' otherwise.
214 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
216 /* The size of the local buffer for inflate is a good guess as to a
217 * reasonable size to use for buffering reads from the application.
222 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
224 len = (sizeof tmpbuf);
229 png_crc_read(png_ptr, tmpbuf, len);
232 if (png_crc_error(png_ptr) != 0)
234 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
235 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
236 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
238 png_chunk_warning(png_ptr, "CRC error");
242 png_chunk_error(png_ptr, "CRC error");
250 /* Compare the CRC stored in the PNG file with that calculated by libpng from
251 * the data it has read thus far.
254 png_crc_error(png_structrp png_ptr)
256 png_byte crc_bytes[4];
260 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
262 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
263 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
269 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
273 #ifdef PNG_IO_STATE_SUPPORTED
274 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
277 /* The chunk CRC must be serialized in a single I/O call. */
278 png_read_data(png_ptr, crc_bytes, 4);
282 crc = png_get_uint_32(crc_bytes);
283 return ((int)(crc != png_ptr->crc));
290 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
291 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
292 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
293 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
294 /* Manage the read buffer; this simply reallocates the buffer if it is not small
295 * enough (or if it is not allocated). The routine returns a pointer to the
296 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
297 * it will call png_error (via png_malloc) on failure. (warn == 2 means
301 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
303 png_bytep buffer = png_ptr->read_buffer;
305 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
307 png_ptr->read_buffer = NULL;
308 png_ptr->read_buffer = NULL;
309 png_ptr->read_buffer_size = 0;
310 png_free(png_ptr, buffer);
316 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
320 memset(buffer, 0, new_size); /* just in case */
321 png_ptr->read_buffer = buffer;
322 png_ptr->read_buffer_size = new_size;
325 else if (warn < 2) /* else silent */
328 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
331 png_chunk_error(png_ptr, "insufficient memory to read chunk");
337 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
339 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
340 * decompression. Returns Z_OK on success, else a zlib error code. It checks
341 * the owner but, in final release builds, just issues a warning if some other
342 * chunk apparently owns the stream. Prior to release it does a png_error.
345 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
347 if (png_ptr->zowner != 0)
351 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
352 /* So the message that results is "<chunk> using zstream"; this is an
353 * internal error, but is very useful for debugging. i18n requirements
356 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
357 #if PNG_RELEASE_BUILD
358 png_chunk_warning(png_ptr, msg);
361 png_chunk_error(png_ptr, msg);
365 /* Implementation note: unlike 'png_deflate_claim' this internal function
366 * does not take the size of the data as an argument. Some efficiency could
367 * be gained by using this when it is known *if* the zlib stream itself does
368 * not record the number; however, this is an illusion: the original writer
369 * of the PNG may have selected a lower window size, and we really must
370 * follow that because, for systems with with limited capabilities, we
371 * would otherwise reject the application's attempts to use a smaller window
372 * size (zlib doesn't have an interface to say "this or lower"!).
374 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
375 * reset, therefore it is necessary to always allocate the maximum window
376 * size with earlier zlibs just in case later compressed chunks need it.
379 int ret; /* zlib return code */
380 #if ZLIB_VERNUM >= 0x1240
383 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
384 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
388 png_ptr->zstream_start = 0; /* fixed window size */
393 png_ptr->zstream_start = 1;
397 #endif /* ZLIB_VERNUM >= 0x1240 */
399 /* Set this for safety, just in case the previous owner left pointers to
400 * memory allocations.
402 png_ptr->zstream.next_in = NULL;
403 png_ptr->zstream.avail_in = 0;
404 png_ptr->zstream.next_out = NULL;
405 png_ptr->zstream.avail_out = 0;
407 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
409 #if ZLIB_VERNUM >= 0x1240
410 ret = inflateReset2(&png_ptr->zstream, window_bits);
412 ret = inflateReset(&png_ptr->zstream);
418 #if ZLIB_VERNUM >= 0x1240
419 ret = inflateInit2(&png_ptr->zstream, window_bits);
421 ret = inflateInit(&png_ptr->zstream);
425 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
428 #if ZLIB_VERNUM >= 0x1290 && \
429 defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32)
430 if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
431 /* Turn off validation of the ADLER32 checksum in IDAT chunks */
432 ret = inflateValidate(&png_ptr->zstream, 0);
436 png_ptr->zowner = owner;
439 png_zstream_error(png_ptr, ret);
449 #if ZLIB_VERNUM >= 0x1240
450 /* Handle the start of the inflate stream if we called inflateInit2(strm,0);
451 * in this case some zlib versions skip validation of the CINFO field and, in
452 * certain circumstances, libpng may end up displaying an invalid image, in
453 * contrast to implementations that call zlib in the normal way (e.g. libpng
457 png_zlib_inflate(png_structrp png_ptr, int flush)
459 if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0)
461 if ((*png_ptr->zstream.next_in >> 4) > 7)
463 png_ptr->zstream.msg = "invalid window size (libpng)";
467 png_ptr->zstream_start = 0;
470 return inflate(&png_ptr->zstream, flush);
472 #endif /* Zlib >= 1.2.4 */
474 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
475 #if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED)
476 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
477 * allow the caller to do multiple calls if required. If the 'finish' flag is
478 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
479 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
480 * Z_OK or Z_STREAM_END will be returned on success.
482 * The input and output sizes are updated to the actual amounts of data consumed
483 * or written, not the amount available (as in a z_stream). The data pointers
484 * are not changed, so the next input is (data+input_size) and the next
485 * available output is (output+output_size).
488 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
489 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
490 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
492 if (png_ptr->zowner == owner) /* Else not claimed */
495 png_alloc_size_t avail_out = *output_size_ptr;
496 png_uint_32 avail_in = *input_size_ptr;
498 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
499 * can't even necessarily handle 65536 bytes) because the type uInt is
500 * "16 bits or more". Consequently it is necessary to chunk the input to
501 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
502 * maximum value that can be stored in a uInt.) It is possible to set
503 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
504 * a performance advantage, because it reduces the amount of data accessed
505 * at each step and that may give the OS more time to page it in.
507 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
508 /* avail_in and avail_out are set below from 'size' */
509 png_ptr->zstream.avail_in = 0;
510 png_ptr->zstream.avail_out = 0;
512 /* Read directly into the output if it is available (this is set to
513 * a local buffer below if output is NULL).
516 png_ptr->zstream.next_out = output;
521 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
523 /* zlib INPUT BUFFER */
524 /* The setting of 'avail_in' used to be outside the loop; by setting it
525 * inside it is possible to chunk the input to zlib and simply rely on
526 * zlib to advance the 'next_in' pointer. This allows arbitrary
527 * amounts of data to be passed through zlib at the unavoidable cost of
528 * requiring a window save (memcpy of up to 32768 output bytes)
529 * every ZLIB_IO_MAX input bytes.
531 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
535 if (avail_in < avail)
536 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
539 png_ptr->zstream.avail_in = avail;
541 /* zlib OUTPUT BUFFER */
542 avail_out += png_ptr->zstream.avail_out; /* not written last time */
544 avail = ZLIB_IO_MAX; /* maximum zlib can process */
548 /* Reset the output buffer each time round if output is NULL and
549 * make available the full buffer, up to 'remaining_space'
551 png_ptr->zstream.next_out = local_buffer;
552 if ((sizeof local_buffer) < avail)
553 avail = (sizeof local_buffer);
556 if (avail_out < avail)
557 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
559 png_ptr->zstream.avail_out = avail;
562 /* zlib inflate call */
563 /* In fact 'avail_out' may be 0 at this point, that happens at the end
564 * of the read when the final LZ end code was not passed at the end of
565 * the previous chunk of input data. Tell zlib if we have reached the
566 * end of the output buffer.
568 ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH :
569 (finish ? Z_FINISH : Z_SYNC_FLUSH));
570 } while (ret == Z_OK);
572 /* For safety kill the local buffer pointer now */
574 png_ptr->zstream.next_out = NULL;
576 /* Claw back the 'size' and 'remaining_space' byte counts. */
577 avail_in += png_ptr->zstream.avail_in;
578 avail_out += png_ptr->zstream.avail_out;
580 /* Update the input and output sizes; the updated values are the amount
581 * consumed or written, effectively the inverse of what zlib uses.
584 *output_size_ptr -= avail_out;
587 *input_size_ptr -= avail_in;
589 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
590 png_zstream_error(png_ptr, ret);
596 /* This is a bad internal error. The recovery assigns to the zstream msg
597 * pointer, which is not owned by the caller, but this is safe; it's only
600 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
601 return Z_STREAM_ERROR;
606 * Decompress trailing data in a chunk. The assumption is that read_buffer
607 * points at an allocated area holding the contents of a chunk with a
608 * trailing compressed part. What we get back is an allocated area
609 * holding the original prefix part and an uncompressed version of the
610 * trailing part (the malloc area passed in is freed).
613 png_decompress_chunk(png_structrp png_ptr,
614 png_uint_32 chunklength, png_uint_32 prefix_size,
615 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
616 int terminate /*add a '\0' to the end of the uncompressed data*/)
618 /* TODO: implement different limits for different types of chunk.
620 * The caller supplies *newlength set to the maximum length of the
621 * uncompressed data, but this routine allocates space for the prefix and
622 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
623 * limited only by the maximum chunk size.
625 png_alloc_size_t limit = PNG_SIZE_MAX;
627 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
628 if (png_ptr->user_chunk_malloc_max > 0 &&
629 png_ptr->user_chunk_malloc_max < limit)
630 limit = png_ptr->user_chunk_malloc_max;
631 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
632 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
633 limit = PNG_USER_CHUNK_MALLOC_MAX;
636 if (limit >= prefix_size + (terminate != 0))
640 limit -= prefix_size + (terminate != 0);
642 if (limit < *newlength)
645 /* Now try to claim the stream. */
646 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
650 png_uint_32 lzsize = chunklength - prefix_size;
652 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
653 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
654 /* output: */ NULL, newlength);
656 if (ret == Z_STREAM_END)
658 /* Use 'inflateReset' here, not 'inflateReset2' because this
659 * preserves the previously decided window size (otherwise it would
660 * be necessary to store the previous window size.) In practice
661 * this doesn't matter anyway, because png_inflate will call inflate
662 * with Z_FINISH in almost all cases, so the window will not be
665 if (inflateReset(&png_ptr->zstream) == Z_OK)
667 /* Because of the limit checks above we know that the new,
668 * expanded, size will fit in a size_t (let alone an
669 * png_alloc_size_t). Use png_malloc_base here to avoid an
672 png_alloc_size_t new_size = *newlength;
673 png_alloc_size_t buffer_size = prefix_size + new_size +
675 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
680 memset(text, 0, buffer_size);
682 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
683 png_ptr->read_buffer + prefix_size, &lzsize,
684 text + prefix_size, newlength);
686 if (ret == Z_STREAM_END)
688 if (new_size == *newlength)
691 text[prefix_size + *newlength] = 0;
694 memcpy(text, png_ptr->read_buffer, prefix_size);
697 png_bytep old_ptr = png_ptr->read_buffer;
699 png_ptr->read_buffer = text;
700 png_ptr->read_buffer_size = buffer_size;
701 text = old_ptr; /* freed below */
707 /* The size changed on the second read, there can be no
708 * guarantee that anything is correct at this point.
709 * The 'msg' pointer has been set to "unexpected end of
710 * LZ stream", which is fine, but return an error code
711 * that the caller won't accept.
713 ret = PNG_UNEXPECTED_ZLIB_RETURN;
717 else if (ret == Z_OK)
718 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
720 /* Free the text pointer (this is the old read_buffer on
723 png_free(png_ptr, text);
725 /* This really is very benign, but it's still an error because
726 * the extra space may otherwise be used as a Trojan Horse.
728 if (ret == Z_STREAM_END &&
729 chunklength - prefix_size != lzsize)
730 png_chunk_benign_error(png_ptr, "extra compressed data");
735 /* Out of memory allocating the buffer */
737 png_zstream_error(png_ptr, Z_MEM_ERROR);
743 /* inflateReset failed, store the error message */
744 png_zstream_error(png_ptr, ret);
745 ret = PNG_UNEXPECTED_ZLIB_RETURN;
749 else if (ret == Z_OK)
750 ret = PNG_UNEXPECTED_ZLIB_RETURN;
752 /* Release the claimed stream */
756 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
757 ret = PNG_UNEXPECTED_ZLIB_RETURN;
764 /* Application/configuration limits exceeded */
765 png_zstream_error(png_ptr, Z_MEM_ERROR);
769 #endif /* READ_zTXt || READ_iTXt */
770 #endif /* READ_COMPRESSED_TEXT */
772 #ifdef PNG_READ_iCCP_SUPPORTED
773 /* Perform a partial read and decompress, producing 'avail_out' bytes and
774 * reading from the current chunk as required.
777 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
778 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
781 if (png_ptr->zowner == png_ptr->chunk_name)
785 /* next_in and avail_in must have been initialized by the caller. */
786 png_ptr->zstream.next_out = next_out;
787 png_ptr->zstream.avail_out = 0; /* set in the loop */
791 if (png_ptr->zstream.avail_in == 0)
793 if (read_size > *chunk_bytes)
794 read_size = (uInt)*chunk_bytes;
795 *chunk_bytes -= read_size;
798 png_crc_read(png_ptr, read_buffer, read_size);
800 png_ptr->zstream.next_in = read_buffer;
801 png_ptr->zstream.avail_in = read_size;
804 if (png_ptr->zstream.avail_out == 0)
806 uInt avail = ZLIB_IO_MAX;
807 if (avail > *out_size)
808 avail = (uInt)*out_size;
811 png_ptr->zstream.avail_out = avail;
814 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
815 * the available output is produced; this allows reading of truncated
818 ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ?
819 Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
821 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
823 *out_size += png_ptr->zstream.avail_out;
824 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
826 /* Ensure the error message pointer is always set: */
827 png_zstream_error(png_ptr, ret);
833 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
834 return Z_STREAM_ERROR;
837 #endif /* READ_iCCP */
839 /* Read and check the IDHR chunk */
842 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
845 png_uint_32 width, height;
846 int bit_depth, color_type, compression_type, filter_type;
849 png_debug(1, "in png_handle_IHDR");
851 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
852 png_chunk_error(png_ptr, "out of place");
854 /* Check the length */
856 png_chunk_error(png_ptr, "invalid");
858 png_ptr->mode |= PNG_HAVE_IHDR;
860 png_crc_read(png_ptr, buf, 13);
861 png_crc_finish(png_ptr, 0);
863 width = png_get_uint_31(png_ptr, buf);
864 height = png_get_uint_31(png_ptr, buf + 4);
867 compression_type = buf[10];
868 filter_type = buf[11];
869 interlace_type = buf[12];
871 /* Set internal variables */
872 png_ptr->width = width;
873 png_ptr->height = height;
874 png_ptr->bit_depth = (png_byte)bit_depth;
875 png_ptr->interlaced = (png_byte)interlace_type;
876 png_ptr->color_type = (png_byte)color_type;
877 #ifdef PNG_MNG_FEATURES_SUPPORTED
878 png_ptr->filter_type = (png_byte)filter_type;
880 png_ptr->compression_type = (png_byte)compression_type;
882 /* Find number of channels */
883 switch (png_ptr->color_type)
885 default: /* invalid, png_set_IHDR calls png_error */
886 case PNG_COLOR_TYPE_GRAY:
887 case PNG_COLOR_TYPE_PALETTE:
888 png_ptr->channels = 1;
891 case PNG_COLOR_TYPE_RGB:
892 png_ptr->channels = 3;
895 case PNG_COLOR_TYPE_GRAY_ALPHA:
896 png_ptr->channels = 2;
899 case PNG_COLOR_TYPE_RGB_ALPHA:
900 png_ptr->channels = 4;
904 /* Set up other useful info */
905 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
906 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
907 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
908 png_debug1(3, "channels = %d", png_ptr->channels);
909 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
910 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
911 color_type, interlace_type, compression_type, filter_type);
914 /* Read and check the palette */
916 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
918 png_color palette[PNG_MAX_PALETTE_LENGTH];
919 int max_palette_length, num, i;
920 #ifdef PNG_POINTER_INDEXING_SUPPORTED
924 png_debug(1, "in png_handle_PLTE");
926 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
927 png_chunk_error(png_ptr, "missing IHDR");
929 /* Moved to before the 'after IDAT' check below because otherwise duplicate
930 * PLTE chunks are potentially ignored (the spec says there shall not be more
931 * than one PLTE, the error is not treated as benign, so this check trumps
932 * the requirement that PLTE appears before IDAT.)
934 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
935 png_chunk_error(png_ptr, "duplicate");
937 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
939 /* This is benign because the non-benign error happened before, when an
940 * IDAT was encountered in a color-mapped image with no PLTE.
942 png_crc_finish(png_ptr, length);
943 png_chunk_benign_error(png_ptr, "out of place");
947 png_ptr->mode |= PNG_HAVE_PLTE;
949 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
951 png_crc_finish(png_ptr, length);
952 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
956 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
957 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
959 png_crc_finish(png_ptr, length);
964 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
966 png_crc_finish(png_ptr, length);
968 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
969 png_chunk_benign_error(png_ptr, "invalid");
972 png_chunk_error(png_ptr, "invalid");
977 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
978 num = (int)length / 3;
980 /* If the palette has 256 or fewer entries but is too large for the bit
981 * depth, we don't issue an error, to preserve the behavior of previous
982 * libpng versions. We silently truncate the unused extra palette entries
985 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
986 max_palette_length = (1 << png_ptr->bit_depth);
988 max_palette_length = PNG_MAX_PALETTE_LENGTH;
990 if (num > max_palette_length)
991 num = max_palette_length;
993 #ifdef PNG_POINTER_INDEXING_SUPPORTED
994 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
998 png_crc_read(png_ptr, buf, 3);
999 pal_ptr->red = buf[0];
1000 pal_ptr->green = buf[1];
1001 pal_ptr->blue = buf[2];
1004 for (i = 0; i < num; i++)
1008 png_crc_read(png_ptr, buf, 3);
1009 /* Don't depend upon png_color being any order */
1010 palette[i].red = buf[0];
1011 palette[i].green = buf[1];
1012 palette[i].blue = buf[2];
1016 /* If we actually need the PLTE chunk (ie for a paletted image), we do
1017 * whatever the normal CRC configuration tells us. However, if we
1018 * have an RGB image, the PLTE can be considered ancillary, so
1019 * we will act as though it is.
1021 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1022 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1025 png_crc_finish(png_ptr, (png_uint_32) (length - (unsigned int)num * 3));
1028 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
1029 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
1031 /* If we don't want to use the data from an ancillary chunk,
1032 * we have two options: an error abort, or a warning and we
1033 * ignore the data in this chunk (which should be OK, since
1034 * it's considered ancillary for a RGB or RGBA image).
1036 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
1037 * chunk type to determine whether to check the ancillary or the critical
1040 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
1042 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
1046 png_chunk_error(png_ptr, "CRC error");
1049 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1050 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1051 png_chunk_warning(png_ptr, "CRC error");
1055 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1056 * own copy of the palette. This has the side effect that when png_start_row
1057 * is called (this happens after any call to png_read_update_info) the
1058 * info_ptr palette gets changed. This is extremely unexpected and
1061 * Fix this by not sharing the palette in this way.
1063 png_set_PLTE(png_ptr, info_ptr, palette, num);
1065 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1066 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1067 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1068 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1069 * therefore does a benign error if the erroneous condition is detected *and*
1070 * cancels the tRNS if the benign error returns. The alternative is to
1071 * amend the standard since it would be rather hypocritical of the standards
1072 * maintainers to ignore it.
1074 #ifdef PNG_READ_tRNS_SUPPORTED
1075 if (png_ptr->num_trans > 0 ||
1076 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1078 /* Cancel this because otherwise it would be used if the transforms
1079 * require it. Don't cancel the 'valid' flag because this would prevent
1080 * detection of duplicate chunks.
1082 png_ptr->num_trans = 0;
1084 if (info_ptr != NULL)
1085 info_ptr->num_trans = 0;
1087 png_chunk_benign_error(png_ptr, "tRNS must be after");
1091 #ifdef PNG_READ_hIST_SUPPORTED
1092 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1093 png_chunk_benign_error(png_ptr, "hIST must be after");
1096 #ifdef PNG_READ_bKGD_SUPPORTED
1097 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1098 png_chunk_benign_error(png_ptr, "bKGD must be after");
1103 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1105 png_debug(1, "in png_handle_IEND");
1107 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1108 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1109 png_chunk_error(png_ptr, "out of place");
1111 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1113 png_crc_finish(png_ptr, length);
1116 png_chunk_benign_error(png_ptr, "invalid");
1118 PNG_UNUSED(info_ptr)
1121 #ifdef PNG_READ_gAMA_SUPPORTED
1123 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1125 png_fixed_point igamma;
1128 png_debug(1, "in png_handle_gAMA");
1130 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1131 png_chunk_error(png_ptr, "missing IHDR");
1133 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1135 png_crc_finish(png_ptr, length);
1136 png_chunk_benign_error(png_ptr, "out of place");
1142 png_crc_finish(png_ptr, length);
1143 png_chunk_benign_error(png_ptr, "invalid");
1147 png_crc_read(png_ptr, buf, 4);
1149 if (png_crc_finish(png_ptr, 0) != 0)
1152 igamma = png_get_fixed_point(NULL, buf);
1154 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1155 png_colorspace_sync(png_ptr, info_ptr);
1159 #ifdef PNG_READ_sBIT_SUPPORTED
1161 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1163 unsigned int truelen, i;
1164 png_byte sample_depth;
1167 png_debug(1, "in png_handle_sBIT");
1169 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1170 png_chunk_error(png_ptr, "missing IHDR");
1172 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1174 png_crc_finish(png_ptr, length);
1175 png_chunk_benign_error(png_ptr, "out of place");
1179 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1181 png_crc_finish(png_ptr, length);
1182 png_chunk_benign_error(png_ptr, "duplicate");
1186 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1194 truelen = png_ptr->channels;
1195 sample_depth = png_ptr->bit_depth;
1198 if (length != truelen || length > 4)
1200 png_chunk_benign_error(png_ptr, "invalid");
1201 png_crc_finish(png_ptr, length);
1205 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1206 png_crc_read(png_ptr, buf, truelen);
1208 if (png_crc_finish(png_ptr, 0) != 0)
1211 for (i=0; i<truelen; ++i)
1213 if (buf[i] == 0 || buf[i] > sample_depth)
1215 png_chunk_benign_error(png_ptr, "invalid");
1220 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1222 png_ptr->sig_bit.red = buf[0];
1223 png_ptr->sig_bit.green = buf[1];
1224 png_ptr->sig_bit.blue = buf[2];
1225 png_ptr->sig_bit.alpha = buf[3];
1230 png_ptr->sig_bit.gray = buf[0];
1231 png_ptr->sig_bit.red = buf[0];
1232 png_ptr->sig_bit.green = buf[0];
1233 png_ptr->sig_bit.blue = buf[0];
1234 png_ptr->sig_bit.alpha = buf[1];
1237 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1241 #ifdef PNG_READ_cHRM_SUPPORTED
1243 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1248 png_debug(1, "in png_handle_cHRM");
1250 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1251 png_chunk_error(png_ptr, "missing IHDR");
1253 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1255 png_crc_finish(png_ptr, length);
1256 png_chunk_benign_error(png_ptr, "out of place");
1262 png_crc_finish(png_ptr, length);
1263 png_chunk_benign_error(png_ptr, "invalid");
1267 png_crc_read(png_ptr, buf, 32);
1269 if (png_crc_finish(png_ptr, 0) != 0)
1272 xy.whitex = png_get_fixed_point(NULL, buf);
1273 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1274 xy.redx = png_get_fixed_point(NULL, buf + 8);
1275 xy.redy = png_get_fixed_point(NULL, buf + 12);
1276 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1277 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1278 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1279 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1281 if (xy.whitex == PNG_FIXED_ERROR ||
1282 xy.whitey == PNG_FIXED_ERROR ||
1283 xy.redx == PNG_FIXED_ERROR ||
1284 xy.redy == PNG_FIXED_ERROR ||
1285 xy.greenx == PNG_FIXED_ERROR ||
1286 xy.greeny == PNG_FIXED_ERROR ||
1287 xy.bluex == PNG_FIXED_ERROR ||
1288 xy.bluey == PNG_FIXED_ERROR)
1290 png_chunk_benign_error(png_ptr, "invalid values");
1294 /* If a colorspace error has already been output skip this chunk */
1295 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1298 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1300 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1301 png_colorspace_sync(png_ptr, info_ptr);
1302 png_chunk_benign_error(png_ptr, "duplicate");
1306 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1307 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1308 1/*prefer cHRM values*/);
1309 png_colorspace_sync(png_ptr, info_ptr);
1313 #ifdef PNG_READ_sRGB_SUPPORTED
1315 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1319 png_debug(1, "in png_handle_sRGB");
1321 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1322 png_chunk_error(png_ptr, "missing IHDR");
1324 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1326 png_crc_finish(png_ptr, length);
1327 png_chunk_benign_error(png_ptr, "out of place");
1333 png_crc_finish(png_ptr, length);
1334 png_chunk_benign_error(png_ptr, "invalid");
1338 png_crc_read(png_ptr, &intent, 1);
1340 if (png_crc_finish(png_ptr, 0) != 0)
1343 /* If a colorspace error has already been output skip this chunk */
1344 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1347 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1350 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1352 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1353 png_colorspace_sync(png_ptr, info_ptr);
1354 png_chunk_benign_error(png_ptr, "too many profiles");
1358 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1359 png_colorspace_sync(png_ptr, info_ptr);
1361 #endif /* READ_sRGB */
1363 #ifdef PNG_READ_iCCP_SUPPORTED
1365 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1366 /* Note: this does not properly handle profiles that are > 64K under DOS */
1368 png_const_charp errmsg = NULL; /* error message output, or no error */
1369 int finished = 0; /* crc checked */
1371 png_debug(1, "in png_handle_iCCP");
1373 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1374 png_chunk_error(png_ptr, "missing IHDR");
1376 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1378 png_crc_finish(png_ptr, length);
1379 png_chunk_benign_error(png_ptr, "out of place");
1383 /* Consistent with all the above colorspace handling an obviously *invalid*
1384 * chunk is just ignored, so does not invalidate the color space. An
1385 * alternative is to set the 'invalid' flags at the start of this routine
1386 * and only clear them in they were not set before and all the tests pass.
1389 /* The keyword must be at least one character and there is a
1390 * terminator (0) byte and the compression method byte, and the
1391 * 'zlib' datastream is at least 11 bytes.
1395 png_crc_finish(png_ptr, length);
1396 png_chunk_benign_error(png_ptr, "too short");
1400 /* If a colorspace error has already been output skip this chunk */
1401 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1403 png_crc_finish(png_ptr, length);
1407 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1410 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1412 uInt read_length, keyword_length;
1415 /* Find the keyword; the keyword plus separator and compression method
1416 * bytes can be at most 81 characters long.
1418 read_length = 81; /* maximum */
1419 if (read_length > length)
1420 read_length = (uInt)length;
1422 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1423 length -= read_length;
1425 /* The minimum 'zlib' stream is assumed to be just the 2 byte header,
1426 * 5 bytes minimum 'deflate' stream, and the 4 byte checksum.
1430 png_crc_finish(png_ptr, length);
1431 png_chunk_benign_error(png_ptr, "too short");
1436 while (keyword_length < 80 && keyword_length < read_length &&
1437 keyword[keyword_length] != 0)
1440 /* TODO: make the keyword checking common */
1441 if (keyword_length >= 1 && keyword_length <= 79)
1443 /* We only understand '0' compression - deflate - so if we get a
1444 * different value we can't safely decode the chunk.
1446 if (keyword_length+1 < read_length &&
1447 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1449 read_length -= keyword_length+2;
1451 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1453 Byte profile_header[132]={0};
1454 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1455 png_alloc_size_t size = (sizeof profile_header);
1457 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1458 png_ptr->zstream.avail_in = read_length;
1459 (void)png_inflate_read(png_ptr, local_buffer,
1460 (sizeof local_buffer), &length, profile_header, &size,
1461 0/*finish: don't, because the output is too small*/);
1465 /* We have the ICC profile header; do the basic header checks.
1467 png_uint_32 profile_length = png_get_uint_32(profile_header);
1469 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1470 keyword, profile_length) != 0)
1472 /* The length is apparently ok, so we can check the 132
1475 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1476 keyword, profile_length, profile_header,
1477 png_ptr->color_type) != 0)
1479 /* Now read the tag table; a variable size buffer is
1480 * needed at this point, allocate one for the whole
1481 * profile. The header check has already validated
1482 * that none of this stuff will overflow.
1484 png_uint_32 tag_count =
1485 png_get_uint_32(profile_header + 128);
1486 png_bytep profile = png_read_buffer(png_ptr,
1487 profile_length, 2/*silent*/);
1489 if (profile != NULL)
1491 memcpy(profile, profile_header,
1492 (sizeof profile_header));
1494 size = 12 * tag_count;
1496 (void)png_inflate_read(png_ptr, local_buffer,
1497 (sizeof local_buffer), &length,
1498 profile + (sizeof profile_header), &size, 0);
1500 /* Still expect a buffer error because we expect
1501 * there to be some tag data!
1505 if (png_icc_check_tag_table(png_ptr,
1506 &png_ptr->colorspace, keyword, profile_length,
1509 /* The profile has been validated for basic
1510 * security issues, so read the whole thing in.
1512 size = profile_length - (sizeof profile_header)
1515 (void)png_inflate_read(png_ptr, local_buffer,
1516 (sizeof local_buffer), &length,
1517 profile + (sizeof profile_header) +
1518 12 * tag_count, &size, 1/*finish*/);
1520 if (length > 0 && !(png_ptr->flags &
1521 PNG_FLAG_BENIGN_ERRORS_WARN))
1522 errmsg = "extra compressed data";
1524 /* But otherwise allow extra data: */
1529 /* This can be handled completely, so
1532 png_chunk_warning(png_ptr,
1533 "extra compressed data");
1536 png_crc_finish(png_ptr, length);
1539 # if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 0
1540 /* Check for a match against sRGB */
1541 png_icc_set_sRGB(png_ptr,
1542 &png_ptr->colorspace, profile,
1543 png_ptr->zstream.adler);
1546 /* Steal the profile for info_ptr. */
1547 if (info_ptr != NULL)
1549 png_free_data(png_ptr, info_ptr,
1552 info_ptr->iccp_name = png_voidcast(char*,
1553 png_malloc_base(png_ptr,
1555 if (info_ptr->iccp_name != NULL)
1557 memcpy(info_ptr->iccp_name, keyword,
1559 info_ptr->iccp_proflen =
1561 info_ptr->iccp_profile = profile;
1562 png_ptr->read_buffer = NULL; /*steal*/
1563 info_ptr->free_me |= PNG_FREE_ICCP;
1564 info_ptr->valid |= PNG_INFO_iCCP;
1569 png_ptr->colorspace.flags |=
1570 PNG_COLORSPACE_INVALID;
1571 errmsg = "out of memory";
1575 /* else the profile remains in the read
1576 * buffer which gets reused for subsequent
1580 if (info_ptr != NULL)
1581 png_colorspace_sync(png_ptr, info_ptr);
1585 png_ptr->zowner = 0;
1590 errmsg = png_ptr->zstream.msg;
1592 /* else png_icc_check_tag_table output an error */
1594 else /* profile truncated */
1595 errmsg = png_ptr->zstream.msg;
1599 errmsg = "out of memory";
1602 /* else png_icc_check_header output an error */
1605 /* else png_icc_check_length output an error */
1608 else /* profile truncated */
1609 errmsg = png_ptr->zstream.msg;
1611 /* Release the stream */
1612 png_ptr->zowner = 0;
1615 else /* png_inflate_claim failed */
1616 errmsg = png_ptr->zstream.msg;
1620 errmsg = "bad compression method"; /* or missing */
1624 errmsg = "bad keyword";
1628 errmsg = "too many profiles";
1630 /* Failure: the reason is in 'errmsg' */
1632 png_crc_finish(png_ptr, length);
1634 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1635 png_colorspace_sync(png_ptr, info_ptr);
1636 if (errmsg != NULL) /* else already output */
1637 png_chunk_benign_error(png_ptr, errmsg);
1639 #endif /* READ_iCCP */
1641 #ifdef PNG_READ_sPLT_SUPPORTED
1643 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1644 /* Note: this does not properly handle chunks that are > 64K under DOS */
1646 png_bytep entry_start, buffer;
1647 png_sPLT_t new_palette;
1649 png_uint_32 data_length;
1651 png_uint_32 skip = 0;
1655 png_debug(1, "in png_handle_sPLT");
1657 #ifdef PNG_USER_LIMITS_SUPPORTED
1658 if (png_ptr->user_chunk_cache_max != 0)
1660 if (png_ptr->user_chunk_cache_max == 1)
1662 png_crc_finish(png_ptr, length);
1666 if (--png_ptr->user_chunk_cache_max == 1)
1668 png_warning(png_ptr, "No space in chunk cache for sPLT");
1669 png_crc_finish(png_ptr, length);
1675 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1676 png_chunk_error(png_ptr, "missing IHDR");
1678 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1680 png_crc_finish(png_ptr, length);
1681 png_chunk_benign_error(png_ptr, "out of place");
1685 #ifdef PNG_MAX_MALLOC_64K
1686 if (length > 65535U)
1688 png_crc_finish(png_ptr, length);
1689 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1694 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1697 png_crc_finish(png_ptr, length);
1698 png_chunk_benign_error(png_ptr, "out of memory");
1703 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1704 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1705 * potential breakage point if the types in pngconf.h aren't exactly right.
1707 png_crc_read(png_ptr, buffer, length);
1709 if (png_crc_finish(png_ptr, skip) != 0)
1714 for (entry_start = buffer; *entry_start; entry_start++)
1715 /* Empty loop to find end of name */ ;
1719 /* A sample depth should follow the separator, and we should be on it */
1720 if (length < 2U || entry_start > buffer + (length - 2U))
1722 png_warning(png_ptr, "malformed sPLT chunk");
1726 new_palette.depth = *entry_start++;
1727 entry_size = (new_palette.depth == 8 ? 6 : 10);
1728 /* This must fit in a png_uint_32 because it is derived from the original
1729 * chunk data length.
1731 data_length = length - (png_uint_32)(entry_start - buffer);
1733 /* Integrity-check the data length */
1734 if ((data_length % (unsigned int)entry_size) != 0)
1736 png_warning(png_ptr, "sPLT chunk has bad length");
1740 dl = (png_uint_32)(data_length / (unsigned int)entry_size);
1741 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1745 png_warning(png_ptr, "sPLT chunk too long");
1749 new_palette.nentries = (png_int_32)(data_length / (unsigned int)entry_size);
1751 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
1752 (png_alloc_size_t) new_palette.nentries * (sizeof (png_sPLT_entry)));
1754 if (new_palette.entries == NULL)
1756 png_warning(png_ptr, "sPLT chunk requires too much memory");
1760 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1761 for (i = 0; i < new_palette.nentries; i++)
1763 pp = new_palette.entries + i;
1765 if (new_palette.depth == 8)
1767 pp->red = *entry_start++;
1768 pp->green = *entry_start++;
1769 pp->blue = *entry_start++;
1770 pp->alpha = *entry_start++;
1775 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1776 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1777 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1778 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1781 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1784 pp = new_palette.entries;
1786 for (i = 0; i < new_palette.nentries; i++)
1789 if (new_palette.depth == 8)
1791 pp[i].red = *entry_start++;
1792 pp[i].green = *entry_start++;
1793 pp[i].blue = *entry_start++;
1794 pp[i].alpha = *entry_start++;
1799 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1800 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1801 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1802 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1805 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1809 /* Discard all chunk data except the name and stash that */
1810 new_palette.name = (png_charp)buffer;
1812 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1814 png_free(png_ptr, new_palette.entries);
1816 #endif /* READ_sPLT */
1818 #ifdef PNG_READ_tRNS_SUPPORTED
1820 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1822 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1824 png_debug(1, "in png_handle_tRNS");
1826 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1827 png_chunk_error(png_ptr, "missing IHDR");
1829 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1831 png_crc_finish(png_ptr, length);
1832 png_chunk_benign_error(png_ptr, "out of place");
1836 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1838 png_crc_finish(png_ptr, length);
1839 png_chunk_benign_error(png_ptr, "duplicate");
1843 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1849 png_crc_finish(png_ptr, length);
1850 png_chunk_benign_error(png_ptr, "invalid");
1854 png_crc_read(png_ptr, buf, 2);
1855 png_ptr->num_trans = 1;
1856 png_ptr->trans_color.gray = png_get_uint_16(buf);
1859 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1865 png_crc_finish(png_ptr, length);
1866 png_chunk_benign_error(png_ptr, "invalid");
1870 png_crc_read(png_ptr, buf, length);
1871 png_ptr->num_trans = 1;
1872 png_ptr->trans_color.red = png_get_uint_16(buf);
1873 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1874 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1877 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1879 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1881 /* TODO: is this actually an error in the ISO spec? */
1882 png_crc_finish(png_ptr, length);
1883 png_chunk_benign_error(png_ptr, "out of place");
1887 if (length > (unsigned int) png_ptr->num_palette ||
1888 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1891 png_crc_finish(png_ptr, length);
1892 png_chunk_benign_error(png_ptr, "invalid");
1896 png_crc_read(png_ptr, readbuf, length);
1897 png_ptr->num_trans = (png_uint_16)length;
1902 png_crc_finish(png_ptr, length);
1903 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1907 if (png_crc_finish(png_ptr, 0) != 0)
1909 png_ptr->num_trans = 0;
1913 /* TODO: this is a horrible side effect in the palette case because the
1914 * png_struct ends up with a pointer to the tRNS buffer owned by the
1915 * png_info. Fix this.
1917 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1918 &(png_ptr->trans_color));
1922 #ifdef PNG_READ_bKGD_SUPPORTED
1924 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1926 unsigned int truelen;
1928 png_color_16 background;
1930 png_debug(1, "in png_handle_bKGD");
1932 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1933 png_chunk_error(png_ptr, "missing IHDR");
1935 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1936 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1937 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1939 png_crc_finish(png_ptr, length);
1940 png_chunk_benign_error(png_ptr, "out of place");
1944 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1946 png_crc_finish(png_ptr, length);
1947 png_chunk_benign_error(png_ptr, "duplicate");
1951 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1954 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1960 if (length != truelen)
1962 png_crc_finish(png_ptr, length);
1963 png_chunk_benign_error(png_ptr, "invalid");
1967 png_crc_read(png_ptr, buf, truelen);
1969 if (png_crc_finish(png_ptr, 0) != 0)
1972 /* We convert the index value into RGB components so that we can allow
1973 * arbitrary RGB values for background when we have transparency, and
1974 * so it is easy to determine the RGB values of the background color
1975 * from the info_ptr struct.
1977 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1979 background.index = buf[0];
1981 if (info_ptr != NULL && info_ptr->num_palette != 0)
1983 if (buf[0] >= info_ptr->num_palette)
1985 png_chunk_benign_error(png_ptr, "invalid index");
1989 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1990 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1991 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1995 background.red = background.green = background.blue = 0;
1997 background.gray = 0;
2000 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
2002 if (png_ptr->bit_depth <= 8)
2004 if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth))
2006 png_chunk_benign_error(png_ptr, "invalid gray level");
2011 background.index = 0;
2015 background.gray = png_get_uint_16(buf);
2020 if (png_ptr->bit_depth <= 8)
2022 if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0)
2024 png_chunk_benign_error(png_ptr, "invalid color");
2029 background.index = 0;
2030 background.red = png_get_uint_16(buf);
2031 background.green = png_get_uint_16(buf + 2);
2032 background.blue = png_get_uint_16(buf + 4);
2033 background.gray = 0;
2036 png_set_bKGD(png_ptr, info_ptr, &background);
2040 #ifdef PNG_READ_eXIf_SUPPORTED
2042 png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2046 png_debug(1, "in png_handle_eXIf");
2048 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2049 png_chunk_error(png_ptr, "missing IHDR");
2053 png_crc_finish(png_ptr, length);
2054 png_chunk_benign_error(png_ptr, "too short");
2058 else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0)
2060 png_crc_finish(png_ptr, length);
2061 png_chunk_benign_error(png_ptr, "duplicate");
2065 info_ptr->free_me |= PNG_FREE_EXIF;
2067 info_ptr->eXIf_buf = png_voidcast(png_bytep,
2068 png_malloc_warn(png_ptr, length));
2070 if (info_ptr->eXIf_buf == NULL)
2072 png_crc_finish(png_ptr, length);
2073 png_chunk_benign_error(png_ptr, "out of memory");
2077 for (i = 0; i < length; i++)
2080 png_crc_read(png_ptr, buf, 1);
2081 info_ptr->eXIf_buf[i] = buf[0];
2082 if (i == 1 && buf[0] != 'M' && buf[0] != 'I'
2083 && info_ptr->eXIf_buf[0] != buf[0])
2085 png_crc_finish(png_ptr, length);
2086 png_chunk_benign_error(png_ptr, "incorrect byte-order specifier");
2087 png_free(png_ptr, info_ptr->eXIf_buf);
2088 info_ptr->eXIf_buf = NULL;
2093 if (png_crc_finish(png_ptr, 0) != 0)
2096 png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf);
2098 png_free(png_ptr, info_ptr->eXIf_buf);
2099 info_ptr->eXIf_buf = NULL;
2103 #ifdef PNG_READ_hIST_SUPPORTED
2105 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2107 unsigned int num, i;
2108 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
2110 png_debug(1, "in png_handle_hIST");
2112 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2113 png_chunk_error(png_ptr, "missing IHDR");
2115 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
2116 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
2118 png_crc_finish(png_ptr, length);
2119 png_chunk_benign_error(png_ptr, "out of place");
2123 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
2125 png_crc_finish(png_ptr, length);
2126 png_chunk_benign_error(png_ptr, "duplicate");
2132 if (num != (unsigned int) png_ptr->num_palette ||
2133 num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
2135 png_crc_finish(png_ptr, length);
2136 png_chunk_benign_error(png_ptr, "invalid");
2140 for (i = 0; i < num; i++)
2144 png_crc_read(png_ptr, buf, 2);
2145 readbuf[i] = png_get_uint_16(buf);
2148 if (png_crc_finish(png_ptr, 0) != 0)
2151 png_set_hIST(png_ptr, info_ptr, readbuf);
2155 #ifdef PNG_READ_pHYs_SUPPORTED
2157 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2160 png_uint_32 res_x, res_y;
2163 png_debug(1, "in png_handle_pHYs");
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_pHYs) != 0)
2177 png_crc_finish(png_ptr, length);
2178 png_chunk_benign_error(png_ptr, "duplicate");
2184 png_crc_finish(png_ptr, length);
2185 png_chunk_benign_error(png_ptr, "invalid");
2189 png_crc_read(png_ptr, buf, 9);
2191 if (png_crc_finish(png_ptr, 0) != 0)
2194 res_x = png_get_uint_32(buf);
2195 res_y = png_get_uint_32(buf + 4);
2197 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2201 #ifdef PNG_READ_oFFs_SUPPORTED
2203 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2206 png_int_32 offset_x, offset_y;
2209 png_debug(1, "in png_handle_oFFs");
2211 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2212 png_chunk_error(png_ptr, "missing IHDR");
2214 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2216 png_crc_finish(png_ptr, length);
2217 png_chunk_benign_error(png_ptr, "out of place");
2221 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2223 png_crc_finish(png_ptr, length);
2224 png_chunk_benign_error(png_ptr, "duplicate");
2230 png_crc_finish(png_ptr, length);
2231 png_chunk_benign_error(png_ptr, "invalid");
2235 png_crc_read(png_ptr, buf, 9);
2237 if (png_crc_finish(png_ptr, 0) != 0)
2240 offset_x = png_get_int_32(buf);
2241 offset_y = png_get_int_32(buf + 4);
2243 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2247 #ifdef PNG_READ_pCAL_SUPPORTED
2248 /* Read the pCAL chunk (described in the PNG Extensions document) */
2250 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2253 png_byte type, nparams;
2254 png_bytep buffer, buf, units, endptr;
2258 png_debug(1, "in png_handle_pCAL");
2260 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2261 png_chunk_error(png_ptr, "missing IHDR");
2263 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2265 png_crc_finish(png_ptr, length);
2266 png_chunk_benign_error(png_ptr, "out of place");
2270 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2272 png_crc_finish(png_ptr, length);
2273 png_chunk_benign_error(png_ptr, "duplicate");
2277 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2280 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2284 png_crc_finish(png_ptr, length);
2285 png_chunk_benign_error(png_ptr, "out of memory");
2289 png_crc_read(png_ptr, buffer, length);
2291 if (png_crc_finish(png_ptr, 0) != 0)
2294 buffer[length] = 0; /* Null terminate the last string */
2296 png_debug(3, "Finding end of pCAL purpose string");
2297 for (buf = buffer; *buf; buf++)
2300 endptr = buffer + length;
2302 /* We need to have at least 12 bytes after the purpose string
2303 * in order to get the parameter information.
2305 if (endptr - buf <= 12)
2307 png_chunk_benign_error(png_ptr, "invalid");
2311 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2312 X0 = png_get_int_32((png_bytep)buf+1);
2313 X1 = png_get_int_32((png_bytep)buf+5);
2318 png_debug(3, "Checking pCAL equation type and number of parameters");
2319 /* Check that we have the right number of parameters for known
2322 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2323 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2324 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2325 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2327 png_chunk_benign_error(png_ptr, "invalid parameter count");
2331 else if (type >= PNG_EQUATION_LAST)
2333 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2336 for (buf = units; *buf; buf++)
2337 /* Empty loop to move past the units string. */ ;
2339 png_debug(3, "Allocating pCAL parameters array");
2341 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2342 nparams * (sizeof (png_charp))));
2346 png_chunk_benign_error(png_ptr, "out of memory");
2350 /* Get pointers to the start of each parameter string. */
2351 for (i = 0; i < nparams; i++)
2353 buf++; /* Skip the null string terminator from previous parameter. */
2355 png_debug1(3, "Reading pCAL parameter %d", i);
2357 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2358 /* Empty loop to move past each parameter string */ ;
2360 /* Make sure we haven't run out of data yet */
2363 png_free(png_ptr, params);
2364 png_chunk_benign_error(png_ptr, "invalid data");
2369 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2370 (png_charp)units, params);
2372 png_free(png_ptr, params);
2376 #ifdef PNG_READ_sCAL_SUPPORTED
2377 /* Read the sCAL chunk */
2379 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2385 png_debug(1, "in png_handle_sCAL");
2387 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2388 png_chunk_error(png_ptr, "missing IHDR");
2390 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2392 png_crc_finish(png_ptr, length);
2393 png_chunk_benign_error(png_ptr, "out of place");
2397 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2399 png_crc_finish(png_ptr, length);
2400 png_chunk_benign_error(png_ptr, "duplicate");
2404 /* Need unit type, width, \0, height: minimum 4 bytes */
2405 else if (length < 4)
2407 png_crc_finish(png_ptr, length);
2408 png_chunk_benign_error(png_ptr, "invalid");
2412 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2415 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2419 png_chunk_benign_error(png_ptr, "out of memory");
2420 png_crc_finish(png_ptr, length);
2424 png_crc_read(png_ptr, buffer, length);
2425 buffer[length] = 0; /* Null terminate the last string */
2427 if (png_crc_finish(png_ptr, 0) != 0)
2430 /* Validate the unit. */
2431 if (buffer[0] != 1 && buffer[0] != 2)
2433 png_chunk_benign_error(png_ptr, "invalid unit");
2437 /* Validate the ASCII numbers, need two ASCII numbers separated by
2438 * a '\0' and they need to fit exactly in the chunk data.
2443 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2444 i >= length || buffer[i++] != 0)
2445 png_chunk_benign_error(png_ptr, "bad width format");
2447 else if (PNG_FP_IS_POSITIVE(state) == 0)
2448 png_chunk_benign_error(png_ptr, "non-positive width");
2455 if (png_check_fp_number((png_const_charp)buffer, length,
2456 &state, &i) == 0 || i != length)
2457 png_chunk_benign_error(png_ptr, "bad height format");
2459 else if (PNG_FP_IS_POSITIVE(state) == 0)
2460 png_chunk_benign_error(png_ptr, "non-positive height");
2463 /* This is the (only) success case. */
2464 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2465 (png_charp)buffer+1, (png_charp)buffer+heighti);
2470 #ifdef PNG_READ_tIME_SUPPORTED
2472 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2477 png_debug(1, "in png_handle_tIME");
2479 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2480 png_chunk_error(png_ptr, "missing IHDR");
2482 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2484 png_crc_finish(png_ptr, length);
2485 png_chunk_benign_error(png_ptr, "duplicate");
2489 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2490 png_ptr->mode |= PNG_AFTER_IDAT;
2494 png_crc_finish(png_ptr, length);
2495 png_chunk_benign_error(png_ptr, "invalid");
2499 png_crc_read(png_ptr, buf, 7);
2501 if (png_crc_finish(png_ptr, 0) != 0)
2504 mod_time.second = buf[6];
2505 mod_time.minute = buf[5];
2506 mod_time.hour = buf[4];
2507 mod_time.day = buf[3];
2508 mod_time.month = buf[2];
2509 mod_time.year = png_get_uint_16(buf);
2511 png_set_tIME(png_ptr, info_ptr, &mod_time);
2515 #ifdef PNG_READ_tEXt_SUPPORTED
2516 /* Note: this does not properly handle chunks that are > 64K under DOS */
2518 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2524 png_uint_32 skip = 0;
2526 png_debug(1, "in png_handle_tEXt");
2528 #ifdef PNG_USER_LIMITS_SUPPORTED
2529 if (png_ptr->user_chunk_cache_max != 0)
2531 if (png_ptr->user_chunk_cache_max == 1)
2533 png_crc_finish(png_ptr, length);
2537 if (--png_ptr->user_chunk_cache_max == 1)
2539 png_crc_finish(png_ptr, length);
2540 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2546 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2547 png_chunk_error(png_ptr, "missing IHDR");
2549 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2550 png_ptr->mode |= PNG_AFTER_IDAT;
2552 #ifdef PNG_MAX_MALLOC_64K
2553 if (length > 65535U)
2555 png_crc_finish(png_ptr, length);
2556 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2561 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2565 png_chunk_benign_error(png_ptr, "out of memory");
2569 png_crc_read(png_ptr, buffer, length);
2571 if (png_crc_finish(png_ptr, skip) != 0)
2574 key = (png_charp)buffer;
2577 for (text = key; *text; text++)
2578 /* Empty loop to find end of key */ ;
2580 if (text != key + length)
2583 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2584 text_info.key = key;
2585 text_info.lang = NULL;
2586 text_info.lang_key = NULL;
2587 text_info.itxt_length = 0;
2588 text_info.text = text;
2589 text_info.text_length = strlen(text);
2591 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2592 png_warning(png_ptr, "Insufficient memory to process text chunk");
2596 #ifdef PNG_READ_zTXt_SUPPORTED
2597 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2599 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2601 png_const_charp errmsg = NULL;
2603 png_uint_32 keyword_length;
2605 png_debug(1, "in png_handle_zTXt");
2607 #ifdef PNG_USER_LIMITS_SUPPORTED
2608 if (png_ptr->user_chunk_cache_max != 0)
2610 if (png_ptr->user_chunk_cache_max == 1)
2612 png_crc_finish(png_ptr, length);
2616 if (--png_ptr->user_chunk_cache_max == 1)
2618 png_crc_finish(png_ptr, length);
2619 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2625 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2626 png_chunk_error(png_ptr, "missing IHDR");
2628 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2629 png_ptr->mode |= PNG_AFTER_IDAT;
2631 /* Note, "length" is sufficient here; we won't be adding
2632 * a null terminator later.
2634 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2638 png_crc_finish(png_ptr, length);
2639 png_chunk_benign_error(png_ptr, "out of memory");
2643 png_crc_read(png_ptr, buffer, length);
2645 if (png_crc_finish(png_ptr, 0) != 0)
2648 /* TODO: also check that the keyword contents match the spec! */
2649 for (keyword_length = 0;
2650 keyword_length < length && buffer[keyword_length] != 0;
2652 /* Empty loop to find end of name */ ;
2654 if (keyword_length > 79 || keyword_length < 1)
2655 errmsg = "bad keyword";
2657 /* zTXt must have some LZ data after the keyword, although it may expand to
2658 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2661 else if (keyword_length + 3 > length)
2662 errmsg = "truncated";
2664 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2665 errmsg = "unknown compression type";
2669 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2671 /* TODO: at present png_decompress_chunk imposes a single application
2672 * level memory limit, this should be split to different values for iCCP
2675 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2676 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2680 if (png_ptr->read_buffer == NULL)
2681 errmsg="Read failure in png_handle_zTXt";
2684 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk
2685 * except for the extra compression type byte and the fact that
2686 * it isn't necessarily '\0' terminated.
2688 buffer = png_ptr->read_buffer;
2689 buffer[uncompressed_length+(keyword_length+2)] = 0;
2691 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2692 text.key = (png_charp)buffer;
2693 text.text = (png_charp)(buffer + keyword_length+2);
2694 text.text_length = uncompressed_length;
2695 text.itxt_length = 0;
2697 text.lang_key = NULL;
2699 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2700 errmsg = "insufficient memory";
2705 errmsg = png_ptr->zstream.msg;
2709 png_chunk_benign_error(png_ptr, errmsg);
2713 #ifdef PNG_READ_iTXt_SUPPORTED
2714 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2716 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2718 png_const_charp errmsg = NULL;
2720 png_uint_32 prefix_length;
2722 png_debug(1, "in png_handle_iTXt");
2724 #ifdef PNG_USER_LIMITS_SUPPORTED
2725 if (png_ptr->user_chunk_cache_max != 0)
2727 if (png_ptr->user_chunk_cache_max == 1)
2729 png_crc_finish(png_ptr, length);
2733 if (--png_ptr->user_chunk_cache_max == 1)
2735 png_crc_finish(png_ptr, length);
2736 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2742 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2743 png_chunk_error(png_ptr, "missing IHDR");
2745 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2746 png_ptr->mode |= PNG_AFTER_IDAT;
2748 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2752 png_crc_finish(png_ptr, length);
2753 png_chunk_benign_error(png_ptr, "out of memory");
2757 png_crc_read(png_ptr, buffer, length);
2759 if (png_crc_finish(png_ptr, 0) != 0)
2762 /* First the keyword. */
2763 for (prefix_length=0;
2764 prefix_length < length && buffer[prefix_length] != 0;
2768 /* Perform a basic check on the keyword length here. */
2769 if (prefix_length > 79 || prefix_length < 1)
2770 errmsg = "bad keyword";
2772 /* Expect keyword, compression flag, compression type, language, translated
2773 * keyword (both may be empty but are 0 terminated) then the text, which may
2776 else if (prefix_length + 5 > length)
2777 errmsg = "truncated";
2779 else if (buffer[prefix_length+1] == 0 ||
2780 (buffer[prefix_length+1] == 1 &&
2781 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2783 int compressed = buffer[prefix_length+1] != 0;
2784 png_uint_32 language_offset, translated_keyword_offset;
2785 png_alloc_size_t uncompressed_length = 0;
2787 /* Now the language tag */
2789 language_offset = prefix_length;
2791 for (; prefix_length < length && buffer[prefix_length] != 0;
2795 /* WARNING: the length may be invalid here, this is checked below. */
2796 translated_keyword_offset = ++prefix_length;
2798 for (; prefix_length < length && buffer[prefix_length] != 0;
2802 /* prefix_length should now be at the trailing '\0' of the translated
2803 * keyword, but it may already be over the end. None of this arithmetic
2804 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2805 * systems the available allocation may overflow.
2809 if (compressed == 0 && prefix_length <= length)
2810 uncompressed_length = length - prefix_length;
2812 else if (compressed != 0 && prefix_length < length)
2814 uncompressed_length = PNG_SIZE_MAX;
2816 /* TODO: at present png_decompress_chunk imposes a single application
2817 * level memory limit, this should be split to different values for
2818 * iCCP and text chunks.
2820 if (png_decompress_chunk(png_ptr, length, prefix_length,
2821 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2822 buffer = png_ptr->read_buffer;
2825 errmsg = png_ptr->zstream.msg;
2829 errmsg = "truncated";
2835 buffer[uncompressed_length+prefix_length] = 0;
2837 if (compressed == 0)
2838 text.compression = PNG_ITXT_COMPRESSION_NONE;
2841 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2843 text.key = (png_charp)buffer;
2844 text.lang = (png_charp)buffer + language_offset;
2845 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2846 text.text = (png_charp)buffer + prefix_length;
2847 text.text_length = 0;
2848 text.itxt_length = uncompressed_length;
2850 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2851 errmsg = "insufficient memory";
2856 errmsg = "bad compression info";
2859 png_chunk_benign_error(png_ptr, errmsg);
2863 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2864 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2866 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2868 png_alloc_size_t limit = PNG_SIZE_MAX;
2870 if (png_ptr->unknown_chunk.data != NULL)
2872 png_free(png_ptr, png_ptr->unknown_chunk.data);
2873 png_ptr->unknown_chunk.data = NULL;
2876 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
2877 if (png_ptr->user_chunk_malloc_max > 0 &&
2878 png_ptr->user_chunk_malloc_max < limit)
2879 limit = png_ptr->user_chunk_malloc_max;
2881 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2882 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2883 limit = PNG_USER_CHUNK_MALLOC_MAX;
2886 if (length <= limit)
2888 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2889 /* The following is safe because of the PNG_SIZE_MAX init above */
2890 png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/;
2891 /* 'mode' is a flag array, only the bottom four bits matter here */
2892 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2895 png_ptr->unknown_chunk.data = NULL;
2899 /* Do a 'warn' here - it is handled below. */
2900 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2901 png_malloc_warn(png_ptr, length));
2905 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2907 /* This is benign because we clean up correctly */
2908 png_crc_finish(png_ptr, length);
2909 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2916 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2917 png_crc_finish(png_ptr, 0);
2921 #endif /* READ_UNKNOWN_CHUNKS */
2923 /* Handle an unknown, or known but disabled, chunk */
2925 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2926 png_uint_32 length, int keep)
2928 int handled = 0; /* the chunk was handled */
2930 png_debug(1, "in png_handle_unknown");
2932 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2933 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2934 * the bug which meant that setting a non-default behavior for a specific
2935 * chunk would be ignored (the default was always used unless a user
2936 * callback was installed).
2938 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2939 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2940 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2941 * This is just an optimization to avoid multiple calls to the lookup
2944 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2945 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2946 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2950 /* One of the following methods will read the chunk or skip it (at least one
2951 * of these is always defined because this is the only way to switch on
2952 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2954 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2955 /* The user callback takes precedence over the chunk keep value, but the
2956 * keep value is still required to validate a save of a critical chunk.
2958 if (png_ptr->read_user_chunk_fn != NULL)
2960 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2962 /* Callback to user unknown chunk handler */
2963 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2964 &png_ptr->unknown_chunk);
2967 * negative: An error occurred; png_chunk_error will be called.
2968 * zero: The chunk was not handled, the chunk will be discarded
2969 * unless png_set_keep_unknown_chunks has been used to set
2970 * a 'keep' behavior for this particular chunk, in which
2971 * case that will be used. A critical chunk will cause an
2972 * error at this point unless it is to be saved.
2973 * positive: The chunk was handled, libpng will ignore/discard it.
2976 png_chunk_error(png_ptr, "error in user chunk");
2980 /* If the keep value is 'default' or 'never' override it, but
2981 * still error out on critical chunks unless the keep value is
2982 * 'always' While this is weird it is the behavior in 1.4.12.
2983 * A possible improvement would be to obey the value set for the
2984 * chunk, but this would be an API change that would probably
2985 * damage some applications.
2987 * The png_app_warning below catches the case that matters, where
2988 * the application has not set specific save or ignore for this
2989 * chunk or global save or ignore.
2991 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2993 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2994 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2996 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2997 png_app_warning(png_ptr,
2998 "forcing save of an unhandled chunk;"
2999 " please call png_set_keep_unknown_chunks");
3000 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
3003 keep = PNG_HANDLE_CHUNK_IF_SAFE;
3007 else /* chunk was handled */
3010 /* Critical chunks can be safely discarded at this point. */
3011 keep = PNG_HANDLE_CHUNK_NEVER;
3016 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
3020 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
3021 # endif /* READ_USER_CHUNKS */
3023 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
3025 /* keep is currently just the per-chunk setting, if there was no
3026 * setting change it to the global default now (not that this may
3027 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
3028 * if not simply skip the chunk.
3030 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
3031 keep = png_ptr->unknown_default;
3033 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3034 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3035 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3037 if (png_cache_unknown_chunk(png_ptr, length) == 0)
3038 keep = PNG_HANDLE_CHUNK_NEVER;
3042 png_crc_finish(png_ptr, length);
3045 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
3046 # error no method to support READ_UNKNOWN_CHUNKS
3050 /* If here there is no read callback pointer set and no support is
3051 * compiled in to just save the unknown chunks, so simply skip this
3052 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
3053 * the app has erroneously asked for unknown chunk saving when there
3056 if (keep > PNG_HANDLE_CHUNK_NEVER)
3057 png_app_error(png_ptr, "no unknown chunk support available");
3059 png_crc_finish(png_ptr, length);
3063 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
3064 /* Now store the chunk in the chunk list if appropriate, and if the limits
3067 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3068 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3069 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3071 # ifdef PNG_USER_LIMITS_SUPPORTED
3072 switch (png_ptr->user_chunk_cache_max)
3075 png_ptr->user_chunk_cache_max = 1;
3076 png_chunk_benign_error(png_ptr, "no space in chunk cache");
3079 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
3080 * chunk being skipped, now there will be a hard error below.
3084 default: /* not at limit */
3085 --(png_ptr->user_chunk_cache_max);
3087 case 0: /* no limit */
3088 # endif /* USER_LIMITS */
3089 /* Here when the limit isn't reached or when limits are compiled
3090 * out; store the chunk.
3092 png_set_unknown_chunks(png_ptr, info_ptr,
3093 &png_ptr->unknown_chunk, 1);
3095 # ifdef PNG_USER_LIMITS_SUPPORTED
3100 # else /* no store support: the chunk must be handled by the user callback */
3101 PNG_UNUSED(info_ptr)
3104 /* Regardless of the error handling below the cached data (if any) can be
3105 * freed now. Notice that the data is not freed if there is a png_error, but
3106 * it will be freed by destroy_read_struct.
3108 if (png_ptr->unknown_chunk.data != NULL)
3109 png_free(png_ptr, png_ptr->unknown_chunk.data);
3110 png_ptr->unknown_chunk.data = NULL;
3112 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
3113 /* There is no support to read an unknown chunk, so just skip it. */
3114 png_crc_finish(png_ptr, length);
3115 PNG_UNUSED(info_ptr)
3117 #endif /* !READ_UNKNOWN_CHUNKS */
3119 /* Check for unhandled critical chunks */
3120 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
3121 png_chunk_error(png_ptr, "unhandled critical chunk");
3124 /* This function is called to verify that a chunk name is valid.
3125 * This function can't have the "critical chunk check" incorporated
3126 * into it, since in the future we will need to be able to call user
3127 * functions to handle unknown critical chunks after we check that
3128 * the chunk name itself is valid.
3131 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
3133 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
3137 png_check_chunk_name(png_const_structrp png_ptr, png_uint_32 chunk_name)
3140 png_uint_32 cn=chunk_name;
3142 png_debug(1, "in png_check_chunk_name");
3144 for (i=1; i<=4; ++i)
3148 if (c < 65 || c > 122 || (c > 90 && c < 97))
3149 png_chunk_error(png_ptr, "invalid chunk type");
3156 png_check_chunk_length(png_const_structrp png_ptr, png_uint_32 length)
3158 png_alloc_size_t limit = PNG_UINT_31_MAX;
3160 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
3161 if (png_ptr->user_chunk_malloc_max > 0 &&
3162 png_ptr->user_chunk_malloc_max < limit)
3163 limit = png_ptr->user_chunk_malloc_max;
3164 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
3165 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
3166 limit = PNG_USER_CHUNK_MALLOC_MAX;
3168 if (png_ptr->chunk_name == png_IDAT)
3170 png_alloc_size_t idat_limit = PNG_UINT_31_MAX;
3172 (size_t)png_ptr->width
3173 * (size_t)png_ptr->channels
3174 * (png_ptr->bit_depth > 8? 2: 1)
3176 + (png_ptr->interlaced? 6: 0);
3177 if (png_ptr->height > PNG_UINT_32_MAX/row_factor)
3178 idat_limit = PNG_UINT_31_MAX;
3180 idat_limit = png_ptr->height * row_factor;
3181 row_factor = row_factor > 32566? 32566 : row_factor;
3182 idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */
3183 idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;
3184 limit = limit < idat_limit? idat_limit : limit;
3189 png_debug2(0," length = %lu, limit = %lu",
3190 (unsigned long)length,(unsigned long)limit);
3191 png_chunk_error(png_ptr, "chunk data is too large");
3198 copy_src_to_dst(png_bytep dp, png_bytep sp, int width,
3199 int row_stride, int nplanes, PngPickColor *png_pickcolor)
3202 unsigned char *src = (unsigned char *)sp;
3203 unsigned char *dst = (unsigned char *)dp;
3205 unsigned long long sumRGBA[4] = {0, 0, 0, 0};
3206 const int const0 = 0;
3209 uint32x4_t sumR_32x4 = vmovq_n_u32 ( 0 );
3210 uint32x4_t sumG_32x4 = vmovq_n_u32 ( 0 );
3211 uint32x4_t sumB_32x4 = vmovq_n_u32 ( 0 );
3217 uint64x1x3_t sumRGB_64x1;
3219 for(j = 0; j < width-(width&0xf); j += 16)
3223 uint8x16x3_t rgb = vld3q_u8 ( src );
3225 R_8x16 = rgb.val[0];
3226 G_8x16 = rgb.val[1];
3227 B_8x16 = rgb.val[2];
3231 uint8x16x4_t rgb = vld4q_u8 ( src );
3233 R_8x16 = rgb.val[0];
3234 G_8x16 = rgb.val[1];
3235 B_8x16 = rgb.val[2];
3238 if(png_pickcolor && png_pickcolor->enable)
3240 if(png_pickcolor->perc > 0)
3242 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3243 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3244 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3246 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3247 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3248 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3250 else if( (png_pickcolor->x1 > j) && (png_pickcolor->x1 < j + 16) )
3252 int x = png_pickcolor->x1;
3253 unsigned char *from = sp + (png_pickcolor->x1 * nplanes);
3256 png_pickcolor->sumR += from[0];
3257 png_pickcolor->sumG += from[1];
3258 png_pickcolor->sumB += from[2];
3263 else if( (png_pickcolor->x2 >= j) && (png_pickcolor->x2 < j + 16) )
3266 unsigned char *from = sp + (j * nplanes);
3267 while(x <= png_pickcolor->x2)
3269 png_pickcolor->sumR += from[0];
3270 png_pickcolor->sumG += from[1];
3271 png_pickcolor->sumB += from[2];
3276 else if ( (j >= png_pickcolor->x1) && (j+15 <= png_pickcolor->x2) )
3278 uint16x8_t sumR_16x8 = vpaddlq_u8 ( R_8x16 );
3279 uint16x8_t sumG_16x8 = vpaddlq_u8 ( G_8x16 );
3280 uint16x8_t sumB_16x8 = vpaddlq_u8 ( B_8x16 );
3282 sumR_32x4 = vpadalq_u16 ( sumR_32x4, sumR_16x8 );
3283 sumG_32x4 = vpadalq_u16 ( sumG_32x4, sumG_16x8 );
3284 sumB_32x4 = vpadalq_u16 ( sumB_32x4, sumB_16x8 );
3287 dst += (nplanes*16);
3288 src += (nplanes*16);
3291 if(png_pickcolor && png_pickcolor->enable)
3294 uint64x2_t sumR_64x2 = vpaddlq_u32 ( sumR_32x4 );
3295 uint64x2_t sumG_64x2 = vpaddlq_u32 ( sumG_32x4 );
3296 uint64x2_t sumB_64x2 = vpaddlq_u32 ( sumB_32x4 );
3298 uint64x1_t sumR_Lo_64x1 = vget_low_u64 ( sumR_64x2 );
3299 uint64x1_t sumR_Hi_64x1 = vget_high_u64 ( sumR_64x2 );
3301 uint64x1_t sumG_Lo_64x1 = vget_low_u64 ( sumG_64x2 );
3302 uint64x1_t sumG_Hi_64x1 = vget_high_u64 ( sumG_64x2 );
3304 uint64x1_t sumB_Lo_64x1 = vget_low_u64 ( sumB_64x2 );
3305 uint64x1_t sumB_Hi_64x1 = vget_high_u64 ( sumB_64x2 );
3307 sumRGB_64x1.val[0] = vadd_u64 ( sumR_Lo_64x1, sumR_Hi_64x1 );
3308 sumRGB_64x1.val[1] = vadd_u64 ( sumG_Lo_64x1, sumG_Hi_64x1 );
3309 sumRGB_64x1.val[2] = vadd_u64 ( sumB_Lo_64x1, sumB_Hi_64x1 );
3311 vst3_u64( sumRGBA, sumRGB_64x1);
3313 png_pickcolor->sumR += sumRGBA[0];
3314 png_pickcolor->sumG += sumRGBA[1];
3315 png_pickcolor->sumB += sumRGBA[2];
3318 memcpy(dst, src, (width-j)*nplanes);
3319 if(png_pickcolor && png_pickcolor->enable)
3321 if(png_pickcolor->perc <= 0)
3323 if(j < png_pickcolor->x1)
3325 j = png_pickcolor->x1;
3326 dst = dp + (j*nplanes);
3328 width = png_pickcolor->x2;
3330 for(; j < width ; j ++)
3332 png_pickcolor->sumR += dst[0];
3333 png_pickcolor->sumG += dst[1];
3334 png_pickcolor->sumB += dst[2];
3340 void copy_row(png_bytep dp, png_bytep sp, int width, int pixel_bits, PngPickColor *png_pickcolor)
3342 int row_stride = PNG_ROWBYTES(pixel_bits, width);
3343 if(pixel_bits == 24 || pixel_bits == 32)
3345 copy_src_to_dst(dp, sp, width, row_stride, pixel_bits >> 3, png_pickcolor);
3349 memcpy(dp, sp, row_stride);
3354 #endif /* __TIZEN__ */
3356 /* Combines the row recently read in with the existing pixels in the row. This
3357 * routine takes care of alpha and transparency if requested. This routine also
3358 * handles the two methods of progressive display of interlaced images,
3359 * depending on the 'display' value; if 'display' is true then the whole row
3360 * (dp) is filled from the start by replicating the available pixels. If
3361 * 'display' is false only those pixels present in the pass are filled in.
3364 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3366 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3367 png_const_bytep sp = png_ptr->row_buf + 1;
3368 png_alloc_size_t row_width = png_ptr->width;
3369 unsigned int pass = png_ptr->pass;
3370 png_bytep end_ptr = 0;
3371 png_byte end_byte = 0;
3372 unsigned int end_mask;
3374 png_debug(1, "in png_combine_row");
3376 /* Added in 1.5.6: it should not be possible to enter this routine until at
3377 * least one row has been read from the PNG data and transformed.
3379 if (pixel_depth == 0)
3380 png_error(png_ptr, "internal row logic error");
3382 /* Added in 1.5.4: the pixel depth should match the information returned by
3383 * any call to png_read_update_info at this point. Do not continue if we got
3386 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3387 PNG_ROWBYTES(pixel_depth, row_width))
3388 png_error(png_ptr, "internal row size calculation error");
3390 /* Don't expect this to ever happen: */
3392 png_error(png_ptr, "internal row width error");
3394 /* Preserve the last byte in cases where only part of it will be overwritten,
3395 * the multiply below may overflow, we don't care because ANSI-C guarantees
3396 * we get the low bits.
3398 end_mask = (pixel_depth * row_width) & 7;
3401 /* end_ptr == NULL is a flag to say do nothing */
3402 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3403 end_byte = *end_ptr;
3404 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3405 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3406 /* little-endian byte */
3407 end_mask = (unsigned int)(0xff << end_mask);
3409 else /* big-endian byte */
3411 end_mask = 0xff >> end_mask;
3412 /* end_mask is now the bits to *keep* from the destination row */
3415 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3416 * will also happen if interlacing isn't supported or if the application
3417 * does not call png_set_interlace_handling(). In the latter cases the
3418 * caller just gets a sequence of the unexpanded rows from each interlace
3421 #ifdef PNG_READ_INTERLACING_SUPPORTED
3422 if (png_ptr->interlaced != 0 &&
3423 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3424 pass < 6 && (display == 0 ||
3425 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3426 (display == 1 && (pass & 1) != 0)))
3428 /* Narrow images may have no bits in a pass; the caller should handle
3429 * this, but this test is cheap:
3431 if (row_width <= PNG_PASS_START_COL(pass))
3434 if (pixel_depth < 8)
3436 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3437 * into 32 bits, then a single loop over the bytes using the four byte
3438 * values in the 32-bit mask can be used. For the 'display' option the
3439 * expanded mask may also not require any masking within a byte. To
3440 * make this work the PACKSWAP option must be taken into account - it
3441 * simply requires the pixels to be reversed in each byte.
3443 * The 'regular' case requires a mask for each of the first 6 passes,
3444 * the 'display' case does a copy for the even passes in the range
3445 * 0..6. This has already been handled in the test above.
3447 * The masks are arranged as four bytes with the first byte to use in
3448 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3449 * not) of the pixels in each byte.
3451 * NOTE: the whole of this logic depends on the caller of this function
3452 * only calling it on rows appropriate to the pass. This function only
3453 * understands the 'x' logic; the 'y' logic is handled by the caller.
3455 * The following defines allow generation of compile time constant bit
3456 * masks for each pixel depth and each possibility of swapped or not
3457 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3458 * is in the range 0..7; and the result is 1 if the pixel is to be
3459 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3460 * for the block method.
3462 * With some compilers a compile time expression of the general form:
3464 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3466 * Produces warnings with values of 'shift' in the range 33 to 63
3467 * because the right hand side of the ?: expression is evaluated by
3468 * the compiler even though it isn't used. Microsoft Visual C (various
3469 * versions) and the Intel C compiler are known to do this. To avoid
3470 * this the following macros are used in 1.5.6. This is a temporary
3471 * solution to avoid destabilizing the code during the release process.
3473 # if PNG_USE_COMPILE_TIME_MASKS
3474 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3475 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3477 # define PNG_LSR(x,s) ((x)>>(s))
3478 # define PNG_LSL(x,s) ((x)<<(s))
3480 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3481 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3482 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3483 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3485 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3486 * little endian - the first pixel is at bit 0 - however the extra
3487 * parameter 's' can be set to cause the mask position to be swapped
3488 * within each byte, to match the PNG format. This is done by XOR of
3489 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3491 # define PIXEL_MASK(p,x,d,s) \
3492 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3494 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3496 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3497 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3499 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3500 * cases the result needs replicating, for the 4-bpp case the above
3501 * generates a full 32 bits.
3503 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3505 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3506 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3507 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3509 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3510 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3511 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3513 #if PNG_USE_COMPILE_TIME_MASKS
3514 /* Utility macros to construct all the masks for a depth/swap
3515 * combination. The 's' parameter says whether the format is PNG
3516 * (big endian bytes) or not. Only the three odd-numbered passes are
3517 * required for the display/block algorithm.
3519 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3520 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3522 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3524 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3526 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3529 static const png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3531 /* Little-endian byte masks for PACKSWAP */
3532 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3533 /* Normal (big-endian byte) masks - PNG format */
3534 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3537 /* display_mask has only three entries for the odd passes, so index by
3540 static const png_uint_32 display_mask[2][3][3] =
3542 /* Little-endian byte masks for PACKSWAP */
3543 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3544 /* Normal (big-endian byte) masks - PNG format */
3545 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3548 # define MASK(pass,depth,display,png)\
3549 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3550 row_mask[png][DEPTH_INDEX(depth)][pass])
3552 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3553 /* This is the runtime alternative: it seems unlikely that this will
3554 * ever be either smaller or faster than the compile time approach.
3556 # define MASK(pass,depth,display,png)\
3557 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3558 #endif /* !USE_COMPILE_TIME_MASKS */
3560 /* Use the appropriate mask to copy the required bits. In some cases
3561 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3562 * the number of pixels, but the code copies bytes, so it is necessary
3563 * to special case the end.
3565 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3568 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3569 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3570 mask = MASK(pass, pixel_depth, display, 0);
3574 mask = MASK(pass, pixel_depth, display, 1);
3580 /* It doesn't matter in the following if png_uint_32 has more than
3581 * 32 bits because the high bits always match those in m<<24; it is,
3582 * however, essential to use OR here, not +, because of this.
3585 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3588 if (m != 0) /* something to copy */
3591 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3596 /* NOTE: this may overwrite the last byte with garbage if the image
3597 * is not an exact number of bytes wide; libpng has always done
3600 if (row_width <= pixels_per_byte)
3601 break; /* May need to restore part of the last byte */
3603 row_width -= pixels_per_byte;
3609 else /* pixel_depth >= 8 */
3611 unsigned int bytes_to_copy, bytes_to_jump;
3613 /* Validate the depth - it must be a multiple of 8 */
3614 if (pixel_depth & 7)
3615 png_error(png_ptr, "invalid user transform pixel depth");
3617 pixel_depth >>= 3; /* now in bytes */
3618 row_width *= pixel_depth;
3620 /* Regardless of pass number the Adam 7 interlace always results in a
3621 * fixed number of pixels to copy then to skip. There may be a
3622 * different number of pixels to skip at the start though.
3625 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3627 row_width -= offset;
3632 /* Work out the bytes to copy. */
3635 /* When doing the 'block' algorithm the pixel in the pass gets
3636 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3637 * passes are skipped above - the entire expanded row is copied.
3639 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3641 /* But don't allow this number to exceed the actual row width. */
3642 if (bytes_to_copy > row_width)
3643 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3646 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3647 bytes_to_copy = pixel_depth;
3649 /* In Adam7 there is a constant offset between where the pixels go. */
3650 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3652 /* And simply copy these bytes. Some optimization is possible here,
3653 * depending on the value of 'bytes_to_copy'. Special case the low
3654 * byte counts, which we know to be frequent.
3656 * Notice that these cases all 'return' rather than 'break' - this
3657 * avoids an unnecessary test on whether to restore the last byte
3660 switch (bytes_to_copy)
3667 if (row_width <= bytes_to_jump)
3670 dp += bytes_to_jump;
3671 sp += bytes_to_jump;
3672 row_width -= bytes_to_jump;
3676 /* There is a possibility of a partial copy at the end here; this
3677 * slows the code down somewhat.
3681 dp[0] = sp[0]; dp[1] = sp[1];
3683 if (row_width <= bytes_to_jump)
3686 sp += bytes_to_jump;
3687 dp += bytes_to_jump;
3688 row_width -= bytes_to_jump;
3690 while (row_width > 1);
3692 /* And there can only be one byte left at this point: */
3697 /* This can only be the RGB case, so each copy is exactly one
3698 * pixel and it is not necessary to check for a partial copy.
3702 dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2];
3704 if (row_width <= bytes_to_jump)
3707 sp += bytes_to_jump;
3708 dp += bytes_to_jump;
3709 row_width -= bytes_to_jump;
3713 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3714 /* Check for double byte alignment and, if possible, use a
3715 * 16-bit copy. Don't attempt this for narrow images - ones that
3716 * are less than an interlace panel wide. Don't attempt it for
3717 * wide bytes_to_copy either - use the memcpy there.
3719 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3720 png_isaligned(dp, png_uint_16) &&
3721 png_isaligned(sp, png_uint_16) &&
3722 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3723 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3725 /* Everything is aligned for png_uint_16 copies, but try for
3726 * png_uint_32 first.
3728 if (png_isaligned(dp, png_uint_32) &&
3729 png_isaligned(sp, png_uint_32) &&
3730 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3731 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3733 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3734 png_const_uint_32p sp32 = png_aligncastconst(
3735 png_const_uint_32p, sp);
3736 size_t skip = (bytes_to_jump-bytes_to_copy) /
3737 (sizeof (png_uint_32));
3741 size_t c = bytes_to_copy;
3745 c -= (sizeof (png_uint_32));
3749 if (row_width <= bytes_to_jump)
3754 row_width -= bytes_to_jump;
3756 while (bytes_to_copy <= row_width);
3758 /* Get to here when the row_width truncates the final copy.
3759 * There will be 1-3 bytes left to copy, so don't try the
3760 * 16-bit loop below.
3762 dp = (png_bytep)dp32;
3763 sp = (png_const_bytep)sp32;
3766 while (--row_width > 0);
3770 /* Else do it in 16-bit quantities, but only if the size is
3775 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3776 png_const_uint_16p sp16 = png_aligncastconst(
3777 png_const_uint_16p, sp);
3778 size_t skip = (bytes_to_jump-bytes_to_copy) /
3779 (sizeof (png_uint_16));
3783 size_t c = bytes_to_copy;
3787 c -= (sizeof (png_uint_16));
3791 if (row_width <= bytes_to_jump)
3796 row_width -= bytes_to_jump;
3798 while (bytes_to_copy <= row_width);
3800 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3801 dp = (png_bytep)dp16;
3802 sp = (png_const_bytep)sp16;
3805 while (--row_width > 0);
3809 #endif /* ALIGN_TYPE code */
3811 /* The true default - use a memcpy: */
3814 memcpy(dp, sp, bytes_to_copy);
3816 if (row_width <= bytes_to_jump)
3819 sp += bytes_to_jump;
3820 dp += bytes_to_jump;
3821 row_width -= bytes_to_jump;
3822 if (bytes_to_copy > row_width)
3823 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3828 } /* pixel_depth >= 8 */
3830 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3833 #endif /* READ_INTERLACING */
3835 /* If here then the switch above wasn't used so just memcpy the whole row
3836 * from the temporary row buffer (notice that this overwrites the end of the
3837 * destination row if it is a partial byte.)
3839 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3841 /* Restore the overwritten bits from the last byte if necessary. */
3842 if (end_ptr != NULL)
3843 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3846 #ifdef PNG_READ_INTERLACING_SUPPORTED
3848 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3849 png_uint_32 transformations /* Because these may affect the byte layout */)
3851 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3852 /* Offset to next interlace block */
3853 static const unsigned int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3855 png_debug(1, "in png_do_read_interlace");
3856 if (row != NULL && row_info != NULL)
3858 png_uint_32 final_width;
3860 final_width = row_info->width * png_pass_inc[pass];
3862 switch (row_info->pixel_depth)
3866 png_bytep sp = row + (size_t)((row_info->width - 1) >> 3);
3867 png_bytep dp = row + (size_t)((final_width - 1) >> 3);
3868 unsigned int sshift, dshift;
3869 unsigned int s_start, s_end;
3871 int jstop = (int)png_pass_inc[pass];
3876 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3877 if ((transformations & PNG_PACKSWAP) != 0)
3879 sshift = ((row_info->width + 7) & 0x07);
3880 dshift = ((final_width + 7) & 0x07);
3889 sshift = 7 - ((row_info->width + 7) & 0x07);
3890 dshift = 7 - ((final_width + 7) & 0x07);
3896 for (i = 0; i < row_info->width; i++)
3898 v = (png_byte)((*sp >> sshift) & 0x01);
3899 for (j = 0; j < jstop; j++)
3901 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3902 tmp |= (unsigned int)(v << dshift);
3903 *dp = (png_byte)(tmp & 0xff);
3905 if (dshift == s_end)
3912 dshift = (unsigned int)((int)dshift + s_inc);
3915 if (sshift == s_end)
3922 sshift = (unsigned int)((int)sshift + s_inc);
3929 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3930 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3931 unsigned int sshift, dshift;
3932 unsigned int s_start, s_end;
3934 int jstop = (int)png_pass_inc[pass];
3937 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3938 if ((transformations & PNG_PACKSWAP) != 0)
3940 sshift = (((row_info->width + 3) & 0x03) << 1);
3941 dshift = (((final_width + 3) & 0x03) << 1);
3950 sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1);
3951 dshift = ((3 - ((final_width + 3) & 0x03)) << 1);
3957 for (i = 0; i < row_info->width; i++)
3962 v = (png_byte)((*sp >> sshift) & 0x03);
3963 for (j = 0; j < jstop; j++)
3965 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3966 tmp |= (unsigned int)(v << dshift);
3967 *dp = (png_byte)(tmp & 0xff);
3969 if (dshift == s_end)
3976 dshift = (unsigned int)((int)dshift + s_inc);
3979 if (sshift == s_end)
3986 sshift = (unsigned int)((int)sshift + s_inc);
3993 png_bytep sp = row + (size_t)((row_info->width - 1) >> 1);
3994 png_bytep dp = row + (size_t)((final_width - 1) >> 1);
3995 unsigned int sshift, dshift;
3996 unsigned int s_start, s_end;
3999 int jstop = (int)png_pass_inc[pass];
4001 #ifdef PNG_READ_PACKSWAP_SUPPORTED
4002 if ((transformations & PNG_PACKSWAP) != 0)
4004 sshift = (((row_info->width + 1) & 0x01) << 2);
4005 dshift = (((final_width + 1) & 0x01) << 2);
4014 sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2);
4015 dshift = ((1 - ((final_width + 1) & 0x01)) << 2);
4021 for (i = 0; i < row_info->width; i++)
4023 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
4026 for (j = 0; j < jstop; j++)
4028 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
4029 tmp |= (unsigned int)(v << dshift);
4030 *dp = (png_byte)(tmp & 0xff);
4032 if (dshift == s_end)
4039 dshift = (unsigned int)((int)dshift + s_inc);
4042 if (sshift == s_end)
4049 sshift = (unsigned int)((int)sshift + s_inc);
4056 size_t pixel_bytes = (row_info->pixel_depth >> 3);
4058 png_bytep sp = row + (size_t)(row_info->width - 1)
4061 png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes;
4063 int jstop = (int)png_pass_inc[pass];
4066 for (i = 0; i < row_info->width; i++)
4068 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
4071 memcpy(v, sp, pixel_bytes);
4073 for (j = 0; j < jstop; j++)
4075 memcpy(dp, v, pixel_bytes);
4085 row_info->width = final_width;
4086 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
4088 #ifndef PNG_READ_PACKSWAP_SUPPORTED
4089 PNG_UNUSED(transformations) /* Silence compiler warning */
4092 #endif /* READ_INTERLACING */
4095 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
4096 png_const_bytep prev_row)
4099 size_t istop = row_info->rowbytes;
4100 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4101 png_bytep rp = row + bpp;
4103 PNG_UNUSED(prev_row)
4105 for (i = bpp; i < istop; i++)
4107 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
4113 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
4114 png_const_bytep prev_row)
4117 size_t istop = row_info->rowbytes;
4119 png_const_bytep pp = prev_row;
4121 for (i = 0; i < istop; i++)
4123 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
4129 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
4130 png_const_bytep prev_row)
4134 png_const_bytep pp = prev_row;
4135 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4136 size_t istop = row_info->rowbytes - bpp;
4138 for (i = 0; i < bpp; i++)
4140 *rp = (png_byte)(((int)(*rp) +
4141 ((int)(*pp++) / 2 )) & 0xff);
4146 for (i = 0; i < istop; i++)
4148 *rp = (png_byte)(((int)(*rp) +
4149 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
4156 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
4157 png_const_bytep prev_row)
4159 png_bytep rp_end = row + row_info->rowbytes;
4162 /* First pixel/byte */
4165 *row++ = (png_byte)a;
4168 while (row < rp_end)
4170 int b, pa, pb, pc, p;
4172 a &= 0xff; /* From previous iteration or start */
4183 pa = p < 0 ? -p : p;
4184 pb = pc < 0 ? -pc : pc;
4185 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4188 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
4189 * ones in the case of a tie.
4197 /* Calculate the current pixel in a, and move the previous row pixel to c
4198 * for the next time round the loop
4202 *row++ = (png_byte)a;
4207 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
4208 png_const_bytep prev_row)
4210 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4211 png_bytep rp_end = row + bpp;
4213 /* Process the first pixel in the row completely (this is the same as 'up'
4214 * because there is only one candidate predictor for the first row).
4216 while (row < rp_end)
4218 int a = *row + *prev_row++;
4219 *row++ = (png_byte)a;
4223 rp_end = rp_end + (row_info->rowbytes - bpp);
4225 while (row < rp_end)
4227 int a, b, c, pa, pb, pc, p;
4229 c = *(prev_row - bpp);
4241 pa = p < 0 ? -p : p;
4242 pb = pc < 0 ? -pc : pc;
4243 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4253 *row++ = (png_byte)a;
4258 png_init_filter_functions(png_structrp pp)
4259 /* This function is called once for every PNG image (except for PNG images
4260 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
4261 * implementations required to reverse the filtering of PNG rows. Reversing
4262 * the filter is the first transformation performed on the row data. It is
4263 * performed in place, therefore an implementation can be selected based on
4264 * the image pixel format. If the implementation depends on image width then
4265 * take care to ensure that it works correctly if the image is interlaced -
4266 * interlacing causes the actual row width to vary.
4269 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
4271 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
4272 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
4273 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
4275 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4276 png_read_filter_row_paeth_1byte_pixel;
4278 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4279 png_read_filter_row_paeth_multibyte_pixel;
4281 #ifdef PNG_FILTER_OPTIMIZATIONS
4282 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
4283 * call to install hardware optimizations for the above functions; simply
4284 * replace whatever elements of the pp->read_filter[] array with a hardware
4285 * specific (or, for that matter, generic) optimization.
4287 * To see an example of this examine what configure.ac does when
4288 * --enable-arm-neon is specified on the command line.
4290 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
4295 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
4296 png_const_bytep prev_row, int filter)
4298 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
4299 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
4300 * implementations. See png_init_filter_functions above.
4302 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
4304 if (pp->read_filter[0] == NULL)
4305 png_init_filter_functions(pp);
4307 pp->read_filter[filter-1](row_info, row, prev_row);
4311 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
4313 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
4314 png_alloc_size_t avail_out)
4316 /* Loop reading IDATs and decompressing the result into output[avail_out] */
4317 png_ptr->zstream.next_out = output;
4318 png_ptr->zstream.avail_out = 0; /* safety: set below */
4326 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
4328 if (png_ptr->zstream.avail_in == 0)
4333 while (png_ptr->idat_size == 0)
4335 png_crc_finish(png_ptr, 0);
4337 png_ptr->idat_size = png_read_chunk_header(png_ptr);
4338 /* This is an error even in the 'check' case because the code just
4339 * consumed a non-IDAT header.
4341 if (png_ptr->chunk_name != png_IDAT)
4342 png_error(png_ptr, "Not enough image data");
4345 avail_in = png_ptr->IDAT_read_size;
4347 if (avail_in > png_ptr->idat_size)
4348 avail_in = (uInt)png_ptr->idat_size;
4350 /* A PNG with a gradually increasing IDAT size will defeat this attempt
4351 * to minimize memory usage by causing lots of re-allocs, but
4352 * realistically doing IDAT_read_size re-allocs is not likely to be a
4355 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
4357 png_crc_read(png_ptr, buffer, avail_in);
4358 png_ptr->idat_size -= avail_in;
4360 png_ptr->zstream.next_in = buffer;
4361 png_ptr->zstream.avail_in = avail_in;
4364 /* And set up the output side. */
4365 if (output != NULL) /* standard read */
4367 uInt out = ZLIB_IO_MAX;
4369 if (out > avail_out)
4370 out = (uInt)avail_out;
4373 png_ptr->zstream.avail_out = out;
4376 else /* after last row, checking for end */
4378 png_ptr->zstream.next_out = tmpbuf;
4379 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4382 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4383 * process. If the LZ stream is truncated the sequential reader will
4384 * terminally damage the stream, above, by reading the chunk header of the
4385 * following chunk (it then exits with png_error).
4387 * TODO: deal more elegantly with truncated IDAT lists.
4389 ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);
4391 /* Take the unconsumed output back. */
4393 avail_out += png_ptr->zstream.avail_out;
4395 else /* avail_out counts the extra bytes */
4396 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4398 png_ptr->zstream.avail_out = 0;
4400 if (ret == Z_STREAM_END)
4402 /* Do this for safety; we won't read any more into this row. */
4403 png_ptr->zstream.next_out = NULL;
4405 png_ptr->mode |= PNG_AFTER_IDAT;
4406 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4408 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4409 png_chunk_benign_error(png_ptr, "Extra compressed data");
4415 png_zstream_error(png_ptr, ret);
4418 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4422 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4426 } while (avail_out > 0);
4430 /* The stream ended before the image; this is the same as too few IDATs so
4431 * should be handled the same way.
4434 png_error(png_ptr, "Not enough image data");
4436 else /* the deflate stream contained extra data */
4437 png_chunk_benign_error(png_ptr, "Too much image data");
4442 png_read_finish_IDAT(png_structrp png_ptr)
4444 /* We don't need any more data and the stream should have ended, however the
4445 * LZ end code may actually not have been processed. In this case we must
4446 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4447 * may still remain to be consumed.
4449 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4451 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4452 * the compressed stream, but the stream may be damaged too, so even after
4453 * this call we may need to terminate the zstream ownership.
4455 png_read_IDAT_data(png_ptr, NULL, 0);
4456 png_ptr->zstream.next_out = NULL; /* safety */
4458 /* Now clear everything out for safety; the following may not have been
4461 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4463 png_ptr->mode |= PNG_AFTER_IDAT;
4464 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4468 /* If the zstream has not been released do it now *and* terminate the reading
4469 * of the final IDAT chunk.
4471 if (png_ptr->zowner == png_IDAT)
4473 /* Always do this; the pointers otherwise point into the read buffer. */
4474 png_ptr->zstream.next_in = NULL;
4475 png_ptr->zstream.avail_in = 0;
4477 /* Now we no longer own the zstream. */
4478 png_ptr->zowner = 0;
4480 /* The slightly weird semantics of the sequential IDAT reading is that we
4481 * are always in or at the end of an IDAT chunk, so we always need to do a
4482 * crc_finish here. If idat_size is non-zero we also need to read the
4483 * spurious bytes at the end of the chunk now.
4485 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4490 png_read_finish_row(png_structrp png_ptr)
4492 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4494 /* Start of interlace block */
4495 static const png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4497 /* Offset to next interlace block */
4498 static const png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4500 /* Start of interlace block in the y direction */
4501 static const png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4503 /* Offset to next interlace block in the y direction */
4504 static const png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4506 png_debug(1, "in png_read_finish_row");
4507 png_ptr->row_number++;
4508 if (png_ptr->row_number < png_ptr->num_rows)
4511 if (png_ptr->interlaced != 0)
4513 png_ptr->row_number = 0;
4515 /* TO DO: don't do this if prev_row isn't needed (requires
4516 * read-ahead of the next row's filter byte.
4518 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4524 if (png_ptr->pass >= 7)
4527 png_ptr->iwidth = (png_ptr->width +
4528 png_pass_inc[png_ptr->pass] - 1 -
4529 png_pass_start[png_ptr->pass]) /
4530 png_pass_inc[png_ptr->pass];
4532 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4534 png_ptr->num_rows = (png_ptr->height +
4535 png_pass_yinc[png_ptr->pass] - 1 -
4536 png_pass_ystart[png_ptr->pass]) /
4537 png_pass_yinc[png_ptr->pass];
4540 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4541 break; /* libpng deinterlacing sees every row */
4543 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4545 if (png_ptr->pass < 7)
4549 /* Here after at the end of the last row of the last pass. */
4550 png_read_finish_IDAT(png_ptr);
4552 #endif /* SEQUENTIAL_READ */
4555 png_read_start_row(png_structrp png_ptr)
4557 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4559 /* Start of interlace block */
4560 static const png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4562 /* Offset to next interlace block */
4563 static const png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4565 /* Start of interlace block in the y direction */
4566 static const png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4568 /* Offset to next interlace block in the y direction */
4569 static const png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4571 unsigned int max_pixel_depth;
4574 png_debug(1, "in png_read_start_row");
4576 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4577 png_init_read_transformations(png_ptr);
4579 if (png_ptr->interlaced != 0)
4581 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4582 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4583 png_pass_ystart[0]) / png_pass_yinc[0];
4586 png_ptr->num_rows = png_ptr->height;
4588 png_ptr->iwidth = (png_ptr->width +
4589 png_pass_inc[png_ptr->pass] - 1 -
4590 png_pass_start[png_ptr->pass]) /
4591 png_pass_inc[png_ptr->pass];
4596 png_ptr->num_rows = png_ptr->height;
4597 png_ptr->iwidth = png_ptr->width;
4600 max_pixel_depth = (unsigned int)png_ptr->pixel_depth;
4602 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4603 * calculations to calculate the final pixel depth, then
4604 * png_do_read_transforms actually does the transforms. This means that the
4605 * code which effectively calculates this value is actually repeated in three
4606 * separate places. They must all match. Innocent changes to the order of
4607 * transformations can and will break libpng in a way that causes memory
4612 #ifdef PNG_READ_PACK_SUPPORTED
4613 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4614 max_pixel_depth = 8;
4617 #ifdef PNG_READ_EXPAND_SUPPORTED
4618 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4620 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4622 if (png_ptr->num_trans != 0)
4623 max_pixel_depth = 32;
4626 max_pixel_depth = 24;
4629 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4631 if (max_pixel_depth < 8)
4632 max_pixel_depth = 8;
4634 if (png_ptr->num_trans != 0)
4635 max_pixel_depth *= 2;
4638 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4640 if (png_ptr->num_trans != 0)
4642 max_pixel_depth *= 4;
4643 max_pixel_depth /= 3;
4649 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4650 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4652 # ifdef PNG_READ_EXPAND_SUPPORTED
4653 /* In fact it is an error if it isn't supported, but checking is
4656 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4658 if (png_ptr->bit_depth < 16)
4659 max_pixel_depth *= 2;
4663 png_ptr->transformations &= ~PNG_EXPAND_16;
4667 #ifdef PNG_READ_FILLER_SUPPORTED
4668 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4670 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4672 if (max_pixel_depth <= 8)
4673 max_pixel_depth = 16;
4676 max_pixel_depth = 32;
4679 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4680 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4682 if (max_pixel_depth <= 32)
4683 max_pixel_depth = 32;
4686 max_pixel_depth = 64;
4691 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4692 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4695 #ifdef PNG_READ_EXPAND_SUPPORTED
4696 (png_ptr->num_trans != 0 &&
4697 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4699 #ifdef PNG_READ_FILLER_SUPPORTED
4700 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4702 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4704 if (max_pixel_depth <= 16)
4705 max_pixel_depth = 32;
4708 max_pixel_depth = 64;
4713 if (max_pixel_depth <= 8)
4715 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4716 max_pixel_depth = 32;
4719 max_pixel_depth = 24;
4722 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4723 max_pixel_depth = 64;
4726 max_pixel_depth = 48;
4731 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4732 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4733 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4735 unsigned int user_pixel_depth = png_ptr->user_transform_depth *
4736 png_ptr->user_transform_channels;
4738 if (user_pixel_depth > max_pixel_depth)
4739 max_pixel_depth = user_pixel_depth;
4743 /* This value is stored in png_struct and double checked in the row read
4746 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4747 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4749 /* Align the width on the next larger 8 pixels. Mainly used
4752 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4753 /* Calculate the maximum bytes needed, adding a byte and a pixel
4756 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4757 1 + ((max_pixel_depth + 7) >> 3U);
4759 #ifdef PNG_MAX_MALLOC_64K
4760 if (row_bytes > (png_uint_32)65536L)
4761 png_error(png_ptr, "This image requires a row greater than 64KB");
4764 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4766 png_free(png_ptr, png_ptr->big_row_buf);
4767 png_free(png_ptr, png_ptr->big_prev_row);
4769 if (png_ptr->interlaced != 0)
4770 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4774 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4776 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4778 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4779 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4780 * of padding before and after row_buf; treat prev_row similarly.
4781 * NOTE: the alignment is to the start of the pixels, one beyond the start
4782 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4783 * was incorrect; the filter byte was aligned, which had the exact
4784 * opposite effect of that intended.
4787 png_bytep temp = png_ptr->big_row_buf + 32;
4788 int extra = (int)((temp - (png_bytep)0) & 0x0f);
4789 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4791 temp = png_ptr->big_prev_row + 32;
4792 extra = (int)((temp - (png_bytep)0) & 0x0f);
4793 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4797 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4798 png_ptr->row_buf = png_ptr->big_row_buf + 31;
4799 png_ptr->prev_row = png_ptr->big_prev_row + 31;
4801 png_ptr->old_big_row_buf_size = row_bytes + 48;
4804 #ifdef PNG_MAX_MALLOC_64K
4805 if (png_ptr->rowbytes > 65535)
4806 png_error(png_ptr, "This image requires a row greater than 64KB");
4809 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4810 png_error(png_ptr, "Row has too many bytes to allocate in memory");
4812 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4814 png_debug1(3, "width = %u,", png_ptr->width);
4815 png_debug1(3, "height = %u,", png_ptr->height);
4816 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4817 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4818 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4819 png_debug1(3, "irowbytes = %lu",
4820 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4822 /* The sequential reader needs a buffer for IDAT, but the progressive reader
4823 * does not, so free the read buffer now regardless; the sequential reader
4824 * reallocates it on demand.
4826 if (png_ptr->read_buffer != NULL)
4828 png_bytep buffer = png_ptr->read_buffer;
4830 png_ptr->read_buffer_size = 0;
4831 png_ptr->read_buffer = NULL;
4832 png_free(png_ptr, buffer);
4835 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4836 * value from the stream (note that this will result in a fatal error if the
4837 * IDAT stream has a bogus deflate header window_bits value, but this should
4838 * not be happening any longer!)
4840 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4841 png_error(png_ptr, png_ptr->zstream.msg);
4843 png_ptr->flags |= PNG_FLAG_ROW_INIT;