Merge pull request #110 from tesselode/fixes
[wdl/wdl-ol.git] / WDL / libpng / pngrutil.c
blobee584a8c406383970396d15acab052fd76fefac6
2 /* pngrutil.c - utilities to read a PNG file
4 * Last changed in libpng 1.6.19 [November 12, 2015]
5 * Copyright (c) 1998-2015 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
13 * This file contains routines that are only called from within
14 * libpng itself during the course of reading an image.
17 #include "pngpriv.h"
19 #ifdef PNG_READ_SUPPORTED
21 png_uint_32 PNGAPI
22 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
24 png_uint_32 uval = png_get_uint_32(buf);
26 if (uval > PNG_UINT_31_MAX)
27 png_error(png_ptr, "PNG unsigned integer out of range");
29 return (uval);
32 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
33 /* The following is a variation on the above for use with the fixed
34 * point values used for gAMA and cHRM. Instead of png_error it
35 * issues a warning and returns (-1) - an invalid value because both
36 * gAMA and cHRM use *unsigned* integers for fixed point values.
38 #define PNG_FIXED_ERROR (-1)
40 static png_fixed_point /* PRIVATE */
41 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
43 png_uint_32 uval = png_get_uint_32(buf);
45 if (uval <= PNG_UINT_31_MAX)
46 return (png_fixed_point)uval; /* known to be in range */
48 /* The caller can turn off the warning by passing NULL. */
49 if (png_ptr != NULL)
50 png_warning(png_ptr, "PNG fixed point integer out of range");
52 return PNG_FIXED_ERROR;
54 #endif
56 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
57 /* NOTE: the read macros will obscure these definitions, so that if
58 * PNG_USE_READ_MACROS is set the library will not use them internally,
59 * but the APIs will still be available externally.
61 * The parentheses around "PNGAPI function_name" in the following three
62 * functions are necessary because they allow the macros to co-exist with
63 * these (unused but exported) functions.
66 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
67 png_uint_32 (PNGAPI
68 png_get_uint_32)(png_const_bytep buf)
70 png_uint_32 uval =
71 ((png_uint_32)(*(buf )) << 24) +
72 ((png_uint_32)(*(buf + 1)) << 16) +
73 ((png_uint_32)(*(buf + 2)) << 8) +
74 ((png_uint_32)(*(buf + 3)) ) ;
76 return uval;
79 /* Grab a signed 32-bit integer from a buffer in big-endian format. The
80 * data is stored in the PNG file in two's complement format and there
81 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
82 * the following code does a two's complement to native conversion.
84 png_int_32 (PNGAPI
85 png_get_int_32)(png_const_bytep buf)
87 png_uint_32 uval = png_get_uint_32(buf);
88 if ((uval & 0x80000000) == 0) /* non-negative */
89 return uval;
91 uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */
92 if ((uval & 0x80000000) == 0) /* no overflow */
93 return -(png_int_32)uval;
94 /* The following has to be safe; this function only gets called on PNG data
95 * and if we get here that data is invalid. 0 is the most safe value and
96 * if not then an attacker would surely just generate a PNG with 0 instead.
98 return 0;
101 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
102 png_uint_16 (PNGAPI
103 png_get_uint_16)(png_const_bytep buf)
105 /* ANSI-C requires an int value to accomodate at least 16 bits so this
106 * works and allows the compiler not to worry about possible narrowing
107 * on 32-bit systems. (Pre-ANSI systems did not make integers smaller
108 * than 16 bits either.)
110 unsigned int val =
111 ((unsigned int)(*buf) << 8) +
112 ((unsigned int)(*(buf + 1)));
114 return (png_uint_16)val;
117 #endif /* READ_INT_FUNCTIONS */
119 /* Read and check the PNG file signature */
120 void /* PRIVATE */
121 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
123 png_size_t num_checked, num_to_check;
125 /* Exit if the user application does not expect a signature. */
126 if (png_ptr->sig_bytes >= 8)
127 return;
129 num_checked = png_ptr->sig_bytes;
130 num_to_check = 8 - num_checked;
132 #ifdef PNG_IO_STATE_SUPPORTED
133 png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
134 #endif
136 /* The signature must be serialized in a single I/O call. */
137 png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
138 png_ptr->sig_bytes = 8;
140 if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
142 if (num_checked < 4 &&
143 png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
144 png_error(png_ptr, "Not a PNG file");
145 else
146 png_error(png_ptr, "PNG file corrupted by ASCII conversion");
148 if (num_checked < 3)
149 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
152 /* Read the chunk header (length + type name).
153 * Put the type name into png_ptr->chunk_name, and return the length.
155 png_uint_32 /* PRIVATE */
156 png_read_chunk_header(png_structrp png_ptr)
158 png_byte buf[8];
159 png_uint_32 length;
161 #ifdef PNG_IO_STATE_SUPPORTED
162 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
163 #endif
165 /* Read the length and the chunk name.
166 * This must be performed in a single I/O call.
168 png_read_data(png_ptr, buf, 8);
169 length = png_get_uint_31(png_ptr, buf);
171 /* Put the chunk name into png_ptr->chunk_name. */
172 png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
174 png_debug2(0, "Reading %lx chunk, length = %lu",
175 (unsigned long)png_ptr->chunk_name, (unsigned long)length);
177 /* Reset the crc and run it over the chunk name. */
178 png_reset_crc(png_ptr);
179 png_calculate_crc(png_ptr, buf + 4, 4);
181 /* Check to see if chunk name is valid. */
182 png_check_chunk_name(png_ptr, png_ptr->chunk_name);
184 #ifdef PNG_IO_STATE_SUPPORTED
185 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
186 #endif
188 return length;
191 /* Read data, and (optionally) run it through the CRC. */
192 void /* PRIVATE */
193 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
195 if (png_ptr == NULL)
196 return;
198 png_read_data(png_ptr, buf, length);
199 png_calculate_crc(png_ptr, buf, length);
202 /* Optionally skip data and then check the CRC. Depending on whether we
203 * are reading an ancillary or critical chunk, and how the program has set
204 * things up, we may calculate the CRC on the data and print a message.
205 * Returns '1' if there was a CRC error, '0' otherwise.
207 int /* PRIVATE */
208 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
210 /* The size of the local buffer for inflate is a good guess as to a
211 * reasonable size to use for buffering reads from the application.
213 while (skip > 0)
215 png_uint_32 len;
216 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
218 len = (sizeof tmpbuf);
219 if (len > skip)
220 len = skip;
221 skip -= len;
223 png_crc_read(png_ptr, tmpbuf, len);
226 if (png_crc_error(png_ptr) != 0)
228 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
229 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
230 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
232 png_chunk_warning(png_ptr, "CRC error");
235 else
236 png_chunk_error(png_ptr, "CRC error");
238 return (1);
241 return (0);
244 /* Compare the CRC stored in the PNG file with that calculated by libpng from
245 * the data it has read thus far.
247 int /* PRIVATE */
248 png_crc_error(png_structrp png_ptr)
250 png_byte crc_bytes[4];
251 png_uint_32 crc;
252 int need_crc = 1;
254 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
256 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
257 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
258 need_crc = 0;
261 else /* critical */
263 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
264 need_crc = 0;
267 #ifdef PNG_IO_STATE_SUPPORTED
268 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
269 #endif
271 /* The chunk CRC must be serialized in a single I/O call. */
272 png_read_data(png_ptr, crc_bytes, 4);
274 if (need_crc != 0)
276 crc = png_get_uint_32(crc_bytes);
277 return ((int)(crc != png_ptr->crc));
280 else
281 return (0);
284 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
285 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
286 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
287 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
288 /* Manage the read buffer; this simply reallocates the buffer if it is not small
289 * enough (or if it is not allocated). The routine returns a pointer to the
290 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
291 * it will call png_error (via png_malloc) on failure. (warn == 2 means
292 * 'silent').
294 static png_bytep
295 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
297 png_bytep buffer = png_ptr->read_buffer;
299 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
301 png_ptr->read_buffer = NULL;
302 png_ptr->read_buffer = NULL;
303 png_ptr->read_buffer_size = 0;
304 png_free(png_ptr, buffer);
305 buffer = NULL;
308 if (buffer == NULL)
310 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
312 if (buffer != NULL)
314 png_ptr->read_buffer = buffer;
315 png_ptr->read_buffer_size = new_size;
318 else if (warn < 2) /* else silent */
320 if (warn != 0)
321 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
323 else
324 png_chunk_error(png_ptr, "insufficient memory to read chunk");
328 return buffer;
330 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
332 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
333 * decompression. Returns Z_OK on success, else a zlib error code. It checks
334 * the owner but, in final release builds, just issues a warning if some other
335 * chunk apparently owns the stream. Prior to release it does a png_error.
337 static int
338 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
340 if (png_ptr->zowner != 0)
342 char msg[64];
344 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
345 /* So the message that results is "<chunk> using zstream"; this is an
346 * internal error, but is very useful for debugging. i18n requirements
347 * are minimal.
349 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
350 #if PNG_RELEASE_BUILD
351 png_chunk_warning(png_ptr, msg);
352 png_ptr->zowner = 0;
353 #else
354 png_chunk_error(png_ptr, msg);
355 #endif
358 /* Implementation note: unlike 'png_deflate_claim' this internal function
359 * does not take the size of the data as an argument. Some efficiency could
360 * be gained by using this when it is known *if* the zlib stream itself does
361 * not record the number; however, this is an illusion: the original writer
362 * of the PNG may have selected a lower window size, and we really must
363 * follow that because, for systems with with limited capabilities, we
364 * would otherwise reject the application's attempts to use a smaller window
365 * size (zlib doesn't have an interface to say "this or lower"!).
367 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
368 * reset, therefore it is necessary to always allocate the maximum window
369 * size with earlier zlibs just in case later compressed chunks need it.
372 int ret; /* zlib return code */
373 #if PNG_ZLIB_VERNUM >= 0x1240
375 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
376 int window_bits;
378 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
379 PNG_OPTION_ON)
380 window_bits = 15;
382 else
383 window_bits = 0;
384 # else
385 # define window_bits 0
386 # endif
387 #endif
389 /* Set this for safety, just in case the previous owner left pointers to
390 * memory allocations.
392 png_ptr->zstream.next_in = NULL;
393 png_ptr->zstream.avail_in = 0;
394 png_ptr->zstream.next_out = NULL;
395 png_ptr->zstream.avail_out = 0;
397 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
399 #if PNG_ZLIB_VERNUM < 0x1240
400 ret = inflateReset(&png_ptr->zstream);
401 #else
402 ret = inflateReset2(&png_ptr->zstream, window_bits);
403 #endif
406 else
408 #if PNG_ZLIB_VERNUM < 0x1240
409 ret = inflateInit(&png_ptr->zstream);
410 #else
411 ret = inflateInit2(&png_ptr->zstream, window_bits);
412 #endif
414 if (ret == Z_OK)
415 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
418 if (ret == Z_OK)
419 png_ptr->zowner = owner;
421 else
422 png_zstream_error(png_ptr, ret);
424 return ret;
427 #ifdef window_bits
428 # undef window_bits
429 #endif
432 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
433 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
434 * allow the caller to do multiple calls if required. If the 'finish' flag is
435 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
436 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
437 * Z_OK or Z_STREAM_END will be returned on success.
439 * The input and output sizes are updated to the actual amounts of data consumed
440 * or written, not the amount available (as in a z_stream). The data pointers
441 * are not changed, so the next input is (data+input_size) and the next
442 * available output is (output+output_size).
444 static int
445 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
446 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
447 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
449 if (png_ptr->zowner == owner) /* Else not claimed */
451 int ret;
452 png_alloc_size_t avail_out = *output_size_ptr;
453 png_uint_32 avail_in = *input_size_ptr;
455 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
456 * can't even necessarily handle 65536 bytes) because the type uInt is
457 * "16 bits or more". Consequently it is necessary to chunk the input to
458 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
459 * maximum value that can be stored in a uInt.) It is possible to set
460 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
461 * a performance advantage, because it reduces the amount of data accessed
462 * at each step and that may give the OS more time to page it in.
464 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
465 /* avail_in and avail_out are set below from 'size' */
466 png_ptr->zstream.avail_in = 0;
467 png_ptr->zstream.avail_out = 0;
469 /* Read directly into the output if it is available (this is set to
470 * a local buffer below if output is NULL).
472 if (output != NULL)
473 png_ptr->zstream.next_out = output;
477 uInt avail;
478 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
480 /* zlib INPUT BUFFER */
481 /* The setting of 'avail_in' used to be outside the loop; by setting it
482 * inside it is possible to chunk the input to zlib and simply rely on
483 * zlib to advance the 'next_in' pointer. This allows arbitrary
484 * amounts of data to be passed through zlib at the unavoidable cost of
485 * requiring a window save (memcpy of up to 32768 output bytes)
486 * every ZLIB_IO_MAX input bytes.
488 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
490 avail = ZLIB_IO_MAX;
492 if (avail_in < avail)
493 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
495 avail_in -= avail;
496 png_ptr->zstream.avail_in = avail;
498 /* zlib OUTPUT BUFFER */
499 avail_out += png_ptr->zstream.avail_out; /* not written last time */
501 avail = ZLIB_IO_MAX; /* maximum zlib can process */
503 if (output == NULL)
505 /* Reset the output buffer each time round if output is NULL and
506 * make available the full buffer, up to 'remaining_space'
508 png_ptr->zstream.next_out = local_buffer;
509 if ((sizeof local_buffer) < avail)
510 avail = (sizeof local_buffer);
513 if (avail_out < avail)
514 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
516 png_ptr->zstream.avail_out = avail;
517 avail_out -= avail;
519 /* zlib inflate call */
520 /* In fact 'avail_out' may be 0 at this point, that happens at the end
521 * of the read when the final LZ end code was not passed at the end of
522 * the previous chunk of input data. Tell zlib if we have reached the
523 * end of the output buffer.
525 ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH :
526 (finish ? Z_FINISH : Z_SYNC_FLUSH));
527 } while (ret == Z_OK);
529 /* For safety kill the local buffer pointer now */
530 if (output == NULL)
531 png_ptr->zstream.next_out = NULL;
533 /* Claw back the 'size' and 'remaining_space' byte counts. */
534 avail_in += png_ptr->zstream.avail_in;
535 avail_out += png_ptr->zstream.avail_out;
537 /* Update the input and output sizes; the updated values are the amount
538 * consumed or written, effectively the inverse of what zlib uses.
540 if (avail_out > 0)
541 *output_size_ptr -= avail_out;
543 if (avail_in > 0)
544 *input_size_ptr -= avail_in;
546 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
547 png_zstream_error(png_ptr, ret);
548 return ret;
551 else
553 /* This is a bad internal error. The recovery assigns to the zstream msg
554 * pointer, which is not owned by the caller, but this is safe; it's only
555 * used on errors!
557 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
558 return Z_STREAM_ERROR;
563 * Decompress trailing data in a chunk. The assumption is that read_buffer
564 * points at an allocated area holding the contents of a chunk with a
565 * trailing compressed part. What we get back is an allocated area
566 * holding the original prefix part and an uncompressed version of the
567 * trailing part (the malloc area passed in is freed).
569 static int
570 png_decompress_chunk(png_structrp png_ptr,
571 png_uint_32 chunklength, png_uint_32 prefix_size,
572 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
573 int terminate /*add a '\0' to the end of the uncompressed data*/)
575 /* TODO: implement different limits for different types of chunk.
577 * The caller supplies *newlength set to the maximum length of the
578 * uncompressed data, but this routine allocates space for the prefix and
579 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
580 * limited only by the maximum chunk size.
582 png_alloc_size_t limit = PNG_SIZE_MAX;
584 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
585 if (png_ptr->user_chunk_malloc_max > 0 &&
586 png_ptr->user_chunk_malloc_max < limit)
587 limit = png_ptr->user_chunk_malloc_max;
588 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
589 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
590 limit = PNG_USER_CHUNK_MALLOC_MAX;
591 # endif
593 if (limit >= prefix_size + (terminate != 0))
595 int ret;
597 limit -= prefix_size + (terminate != 0);
599 if (limit < *newlength)
600 *newlength = limit;
602 /* Now try to claim the stream. */
603 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
605 if (ret == Z_OK)
607 png_uint_32 lzsize = chunklength - prefix_size;
609 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
610 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
611 /* output: */ NULL, newlength);
613 if (ret == Z_STREAM_END)
615 /* Use 'inflateReset' here, not 'inflateReset2' because this
616 * preserves the previously decided window size (otherwise it would
617 * be necessary to store the previous window size.) In practice
618 * this doesn't matter anyway, because png_inflate will call inflate
619 * with Z_FINISH in almost all cases, so the window will not be
620 * maintained.
622 if (inflateReset(&png_ptr->zstream) == Z_OK)
624 /* Because of the limit checks above we know that the new,
625 * expanded, size will fit in a size_t (let alone an
626 * png_alloc_size_t). Use png_malloc_base here to avoid an
627 * extra OOM message.
629 png_alloc_size_t new_size = *newlength;
630 png_alloc_size_t buffer_size = prefix_size + new_size +
631 (terminate != 0);
632 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
633 buffer_size));
635 if (text != NULL)
637 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
638 png_ptr->read_buffer + prefix_size, &lzsize,
639 text + prefix_size, newlength);
641 if (ret == Z_STREAM_END)
643 if (new_size == *newlength)
645 if (terminate != 0)
646 text[prefix_size + *newlength] = 0;
648 if (prefix_size > 0)
649 memcpy(text, png_ptr->read_buffer, prefix_size);
652 png_bytep old_ptr = png_ptr->read_buffer;
654 png_ptr->read_buffer = text;
655 png_ptr->read_buffer_size = buffer_size;
656 text = old_ptr; /* freed below */
660 else
662 /* The size changed on the second read, there can be no
663 * guarantee that anything is correct at this point.
664 * The 'msg' pointer has been set to "unexpected end of
665 * LZ stream", which is fine, but return an error code
666 * that the caller won't accept.
668 ret = PNG_UNEXPECTED_ZLIB_RETURN;
672 else if (ret == Z_OK)
673 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
675 /* Free the text pointer (this is the old read_buffer on
676 * success)
678 png_free(png_ptr, text);
680 /* This really is very benign, but it's still an error because
681 * the extra space may otherwise be used as a Trojan Horse.
683 if (ret == Z_STREAM_END &&
684 chunklength - prefix_size != lzsize)
685 png_chunk_benign_error(png_ptr, "extra compressed data");
688 else
690 /* Out of memory allocating the buffer */
691 ret = Z_MEM_ERROR;
692 png_zstream_error(png_ptr, Z_MEM_ERROR);
696 else
698 /* inflateReset failed, store the error message */
699 png_zstream_error(png_ptr, ret);
701 if (ret == Z_STREAM_END)
702 ret = PNG_UNEXPECTED_ZLIB_RETURN;
706 else if (ret == Z_OK)
707 ret = PNG_UNEXPECTED_ZLIB_RETURN;
709 /* Release the claimed stream */
710 png_ptr->zowner = 0;
713 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
714 ret = PNG_UNEXPECTED_ZLIB_RETURN;
716 return ret;
719 else
721 /* Application/configuration limits exceeded */
722 png_zstream_error(png_ptr, Z_MEM_ERROR);
723 return Z_MEM_ERROR;
726 #endif /* READ_COMPRESSED_TEXT */
728 #ifdef PNG_READ_iCCP_SUPPORTED
729 /* Perform a partial read and decompress, producing 'avail_out' bytes and
730 * reading from the current chunk as required.
732 static int
733 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
734 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
735 int finish)
737 if (png_ptr->zowner == png_ptr->chunk_name)
739 int ret;
741 /* next_in and avail_in must have been initialized by the caller. */
742 png_ptr->zstream.next_out = next_out;
743 png_ptr->zstream.avail_out = 0; /* set in the loop */
747 if (png_ptr->zstream.avail_in == 0)
749 if (read_size > *chunk_bytes)
750 read_size = (uInt)*chunk_bytes;
751 *chunk_bytes -= read_size;
753 if (read_size > 0)
754 png_crc_read(png_ptr, read_buffer, read_size);
756 png_ptr->zstream.next_in = read_buffer;
757 png_ptr->zstream.avail_in = read_size;
760 if (png_ptr->zstream.avail_out == 0)
762 uInt avail = ZLIB_IO_MAX;
763 if (avail > *out_size)
764 avail = (uInt)*out_size;
765 *out_size -= avail;
767 png_ptr->zstream.avail_out = avail;
770 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
771 * the available output is produced; this allows reading of truncated
772 * streams.
774 ret = inflate(&png_ptr->zstream,
775 *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
777 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
779 *out_size += png_ptr->zstream.avail_out;
780 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
782 /* Ensure the error message pointer is always set: */
783 png_zstream_error(png_ptr, ret);
784 return ret;
787 else
789 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
790 return Z_STREAM_ERROR;
793 #endif
795 /* Read and check the IDHR chunk */
797 void /* PRIVATE */
798 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
800 png_byte buf[13];
801 png_uint_32 width, height;
802 int bit_depth, color_type, compression_type, filter_type;
803 int interlace_type;
805 png_debug(1, "in png_handle_IHDR");
807 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
808 png_chunk_error(png_ptr, "out of place");
810 /* Check the length */
811 if (length != 13)
812 png_chunk_error(png_ptr, "invalid");
814 png_ptr->mode |= PNG_HAVE_IHDR;
816 png_crc_read(png_ptr, buf, 13);
817 png_crc_finish(png_ptr, 0);
819 width = png_get_uint_31(png_ptr, buf);
820 height = png_get_uint_31(png_ptr, buf + 4);
821 bit_depth = buf[8];
822 color_type = buf[9];
823 compression_type = buf[10];
824 filter_type = buf[11];
825 interlace_type = buf[12];
827 /* Set internal variables */
828 png_ptr->width = width;
829 png_ptr->height = height;
830 png_ptr->bit_depth = (png_byte)bit_depth;
831 png_ptr->interlaced = (png_byte)interlace_type;
832 png_ptr->color_type = (png_byte)color_type;
833 #ifdef PNG_MNG_FEATURES_SUPPORTED
834 png_ptr->filter_type = (png_byte)filter_type;
835 #endif
836 png_ptr->compression_type = (png_byte)compression_type;
838 /* Find number of channels */
839 switch (png_ptr->color_type)
841 default: /* invalid, png_set_IHDR calls png_error */
842 case PNG_COLOR_TYPE_GRAY:
843 case PNG_COLOR_TYPE_PALETTE:
844 png_ptr->channels = 1;
845 break;
847 case PNG_COLOR_TYPE_RGB:
848 png_ptr->channels = 3;
849 break;
851 case PNG_COLOR_TYPE_GRAY_ALPHA:
852 png_ptr->channels = 2;
853 break;
855 case PNG_COLOR_TYPE_RGB_ALPHA:
856 png_ptr->channels = 4;
857 break;
860 /* Set up other useful info */
861 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
862 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
863 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
864 png_debug1(3, "channels = %d", png_ptr->channels);
865 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
866 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
867 color_type, interlace_type, compression_type, filter_type);
870 /* Read and check the palette */
871 void /* PRIVATE */
872 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
874 png_color palette[PNG_MAX_PALETTE_LENGTH];
875 int max_palette_length, num, i;
876 #ifdef PNG_POINTER_INDEXING_SUPPORTED
877 png_colorp pal_ptr;
878 #endif
880 png_debug(1, "in png_handle_PLTE");
882 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
883 png_chunk_error(png_ptr, "missing IHDR");
885 /* Moved to before the 'after IDAT' check below because otherwise duplicate
886 * PLTE chunks are potentially ignored (the spec says there shall not be more
887 * than one PLTE, the error is not treated as benign, so this check trumps
888 * the requirement that PLTE appears before IDAT.)
890 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
891 png_chunk_error(png_ptr, "duplicate");
893 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
895 /* This is benign because the non-benign error happened before, when an
896 * IDAT was encountered in a color-mapped image with no PLTE.
898 png_crc_finish(png_ptr, length);
899 png_chunk_benign_error(png_ptr, "out of place");
900 return;
903 png_ptr->mode |= PNG_HAVE_PLTE;
905 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
907 png_crc_finish(png_ptr, length);
908 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
909 return;
912 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
913 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
915 png_crc_finish(png_ptr, length);
916 return;
918 #endif
920 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
922 png_crc_finish(png_ptr, length);
924 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
925 png_chunk_benign_error(png_ptr, "invalid");
927 else
928 png_chunk_error(png_ptr, "invalid");
930 return;
933 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
934 num = (int)length / 3;
936 /* If the palette has 256 or fewer entries but is too large for the bit
937 * depth, we don't issue an error, to preserve the behavior of previous
938 * libpng versions. We silently truncate the unused extra palette entries
939 * here.
941 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
942 max_palette_length = (1 << png_ptr->bit_depth);
943 else
944 max_palette_length = PNG_MAX_PALETTE_LENGTH;
946 if (num > max_palette_length)
947 num = max_palette_length;
949 #ifdef PNG_POINTER_INDEXING_SUPPORTED
950 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
952 png_byte buf[3];
954 png_crc_read(png_ptr, buf, 3);
955 pal_ptr->red = buf[0];
956 pal_ptr->green = buf[1];
957 pal_ptr->blue = buf[2];
959 #else
960 for (i = 0; i < num; i++)
962 png_byte buf[3];
964 png_crc_read(png_ptr, buf, 3);
965 /* Don't depend upon png_color being any order */
966 palette[i].red = buf[0];
967 palette[i].green = buf[1];
968 palette[i].blue = buf[2];
970 #endif
972 /* If we actually need the PLTE chunk (ie for a paletted image), we do
973 * whatever the normal CRC configuration tells us. However, if we
974 * have an RGB image, the PLTE can be considered ancillary, so
975 * we will act as though it is.
977 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
978 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
979 #endif
981 png_crc_finish(png_ptr, (int) length - num * 3);
984 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
985 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
987 /* If we don't want to use the data from an ancillary chunk,
988 * we have two options: an error abort, or a warning and we
989 * ignore the data in this chunk (which should be OK, since
990 * it's considered ancillary for a RGB or RGBA image).
992 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
993 * chunk type to determine whether to check the ancillary or the critical
994 * flags.
996 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
998 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
999 return;
1001 else
1002 png_chunk_error(png_ptr, "CRC error");
1005 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1006 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1007 png_chunk_warning(png_ptr, "CRC error");
1009 #endif
1011 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1012 * own copy of the palette. This has the side effect that when png_start_row
1013 * is called (this happens after any call to png_read_update_info) the
1014 * info_ptr palette gets changed. This is extremely unexpected and
1015 * confusing.
1017 * Fix this by not sharing the palette in this way.
1019 png_set_PLTE(png_ptr, info_ptr, palette, num);
1021 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1022 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1023 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1024 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1025 * therefore does a benign error if the erroneous condition is detected *and*
1026 * cancels the tRNS if the benign error returns. The alternative is to
1027 * amend the standard since it would be rather hypocritical of the standards
1028 * maintainers to ignore it.
1030 #ifdef PNG_READ_tRNS_SUPPORTED
1031 if (png_ptr->num_trans > 0 ||
1032 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1034 /* Cancel this because otherwise it would be used if the transforms
1035 * require it. Don't cancel the 'valid' flag because this would prevent
1036 * detection of duplicate chunks.
1038 png_ptr->num_trans = 0;
1040 if (info_ptr != NULL)
1041 info_ptr->num_trans = 0;
1043 png_chunk_benign_error(png_ptr, "tRNS must be after");
1045 #endif
1047 #ifdef PNG_READ_hIST_SUPPORTED
1048 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1049 png_chunk_benign_error(png_ptr, "hIST must be after");
1050 #endif
1052 #ifdef PNG_READ_bKGD_SUPPORTED
1053 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1054 png_chunk_benign_error(png_ptr, "bKGD must be after");
1055 #endif
1058 void /* PRIVATE */
1059 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1061 png_debug(1, "in png_handle_IEND");
1063 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1064 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1065 png_chunk_error(png_ptr, "out of place");
1067 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1069 png_crc_finish(png_ptr, length);
1071 if (length != 0)
1072 png_chunk_benign_error(png_ptr, "invalid");
1074 PNG_UNUSED(info_ptr)
1077 #ifdef PNG_READ_gAMA_SUPPORTED
1078 void /* PRIVATE */
1079 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1081 png_fixed_point igamma;
1082 png_byte buf[4];
1084 png_debug(1, "in png_handle_gAMA");
1086 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1087 png_chunk_error(png_ptr, "missing IHDR");
1089 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1091 png_crc_finish(png_ptr, length);
1092 png_chunk_benign_error(png_ptr, "out of place");
1093 return;
1096 if (length != 4)
1098 png_crc_finish(png_ptr, length);
1099 png_chunk_benign_error(png_ptr, "invalid");
1100 return;
1103 png_crc_read(png_ptr, buf, 4);
1105 if (png_crc_finish(png_ptr, 0) != 0)
1106 return;
1108 igamma = png_get_fixed_point(NULL, buf);
1110 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1111 png_colorspace_sync(png_ptr, info_ptr);
1113 #endif
1115 #ifdef PNG_READ_sBIT_SUPPORTED
1116 void /* PRIVATE */
1117 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1119 unsigned int truelen, i;
1120 png_byte sample_depth;
1121 png_byte buf[4];
1123 png_debug(1, "in png_handle_sBIT");
1125 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1126 png_chunk_error(png_ptr, "missing IHDR");
1128 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1130 png_crc_finish(png_ptr, length);
1131 png_chunk_benign_error(png_ptr, "out of place");
1132 return;
1135 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1137 png_crc_finish(png_ptr, length);
1138 png_chunk_benign_error(png_ptr, "duplicate");
1139 return;
1142 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1144 truelen = 3;
1145 sample_depth = 8;
1148 else
1150 truelen = png_ptr->channels;
1151 sample_depth = png_ptr->bit_depth;
1154 if (length != truelen || length > 4)
1156 png_chunk_benign_error(png_ptr, "invalid");
1157 png_crc_finish(png_ptr, length);
1158 return;
1161 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1162 png_crc_read(png_ptr, buf, truelen);
1164 if (png_crc_finish(png_ptr, 0) != 0)
1165 return;
1167 for (i=0; i<truelen; ++i)
1169 if (buf[i] == 0 || buf[i] > sample_depth)
1171 png_chunk_benign_error(png_ptr, "invalid");
1172 return;
1176 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1178 png_ptr->sig_bit.red = buf[0];
1179 png_ptr->sig_bit.green = buf[1];
1180 png_ptr->sig_bit.blue = buf[2];
1181 png_ptr->sig_bit.alpha = buf[3];
1184 else
1186 png_ptr->sig_bit.gray = buf[0];
1187 png_ptr->sig_bit.red = buf[0];
1188 png_ptr->sig_bit.green = buf[0];
1189 png_ptr->sig_bit.blue = buf[0];
1190 png_ptr->sig_bit.alpha = buf[1];
1193 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1195 #endif
1197 #ifdef PNG_READ_cHRM_SUPPORTED
1198 void /* PRIVATE */
1199 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1201 png_byte buf[32];
1202 png_xy xy;
1204 png_debug(1, "in png_handle_cHRM");
1206 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1207 png_chunk_error(png_ptr, "missing IHDR");
1209 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1211 png_crc_finish(png_ptr, length);
1212 png_chunk_benign_error(png_ptr, "out of place");
1213 return;
1216 if (length != 32)
1218 png_crc_finish(png_ptr, length);
1219 png_chunk_benign_error(png_ptr, "invalid");
1220 return;
1223 png_crc_read(png_ptr, buf, 32);
1225 if (png_crc_finish(png_ptr, 0) != 0)
1226 return;
1228 xy.whitex = png_get_fixed_point(NULL, buf);
1229 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1230 xy.redx = png_get_fixed_point(NULL, buf + 8);
1231 xy.redy = png_get_fixed_point(NULL, buf + 12);
1232 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1233 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1234 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1235 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1237 if (xy.whitex == PNG_FIXED_ERROR ||
1238 xy.whitey == PNG_FIXED_ERROR ||
1239 xy.redx == PNG_FIXED_ERROR ||
1240 xy.redy == PNG_FIXED_ERROR ||
1241 xy.greenx == PNG_FIXED_ERROR ||
1242 xy.greeny == PNG_FIXED_ERROR ||
1243 xy.bluex == PNG_FIXED_ERROR ||
1244 xy.bluey == PNG_FIXED_ERROR)
1246 png_chunk_benign_error(png_ptr, "invalid values");
1247 return;
1250 /* If a colorspace error has already been output skip this chunk */
1251 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1252 return;
1254 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1256 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1257 png_colorspace_sync(png_ptr, info_ptr);
1258 png_chunk_benign_error(png_ptr, "duplicate");
1259 return;
1262 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1263 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1264 1/*prefer cHRM values*/);
1265 png_colorspace_sync(png_ptr, info_ptr);
1267 #endif
1269 #ifdef PNG_READ_sRGB_SUPPORTED
1270 void /* PRIVATE */
1271 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1273 png_byte intent;
1275 png_debug(1, "in png_handle_sRGB");
1277 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1278 png_chunk_error(png_ptr, "missing IHDR");
1280 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1282 png_crc_finish(png_ptr, length);
1283 png_chunk_benign_error(png_ptr, "out of place");
1284 return;
1287 if (length != 1)
1289 png_crc_finish(png_ptr, length);
1290 png_chunk_benign_error(png_ptr, "invalid");
1291 return;
1294 png_crc_read(png_ptr, &intent, 1);
1296 if (png_crc_finish(png_ptr, 0) != 0)
1297 return;
1299 /* If a colorspace error has already been output skip this chunk */
1300 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1301 return;
1303 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1304 * this.
1306 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1308 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1309 png_colorspace_sync(png_ptr, info_ptr);
1310 png_chunk_benign_error(png_ptr, "too many profiles");
1311 return;
1314 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1315 png_colorspace_sync(png_ptr, info_ptr);
1317 #endif /* READ_sRGB */
1319 #ifdef PNG_READ_iCCP_SUPPORTED
1320 void /* PRIVATE */
1321 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1322 /* Note: this does not properly handle profiles that are > 64K under DOS */
1324 png_const_charp errmsg = NULL; /* error message output, or no error */
1325 int finished = 0; /* crc checked */
1327 png_debug(1, "in png_handle_iCCP");
1329 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1330 png_chunk_error(png_ptr, "missing IHDR");
1332 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1334 png_crc_finish(png_ptr, length);
1335 png_chunk_benign_error(png_ptr, "out of place");
1336 return;
1339 /* Consistent with all the above colorspace handling an obviously *invalid*
1340 * chunk is just ignored, so does not invalidate the color space. An
1341 * alternative is to set the 'invalid' flags at the start of this routine
1342 * and only clear them in they were not set before and all the tests pass.
1343 * The minimum 'deflate' stream is assumed to be just the 2 byte header and
1344 * 4 byte checksum. The keyword must be at least one character and there is
1345 * a terminator (0) byte and the compression method.
1347 if (length < 9)
1349 png_crc_finish(png_ptr, length);
1350 png_chunk_benign_error(png_ptr, "too short");
1351 return;
1354 /* If a colorspace error has already been output skip this chunk */
1355 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1357 png_crc_finish(png_ptr, length);
1358 return;
1361 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1362 * this.
1364 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1366 uInt read_length, keyword_length;
1367 char keyword[81];
1369 /* Find the keyword; the keyword plus separator and compression method
1370 * bytes can be at most 81 characters long.
1372 read_length = 81; /* maximum */
1373 if (read_length > length)
1374 read_length = (uInt)length;
1376 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1377 length -= read_length;
1379 keyword_length = 0;
1380 while (keyword_length < 80 && keyword_length < read_length &&
1381 keyword[keyword_length] != 0)
1382 ++keyword_length;
1384 /* TODO: make the keyword checking common */
1385 if (keyword_length >= 1 && keyword_length <= 79)
1387 /* We only understand '0' compression - deflate - so if we get a
1388 * different value we can't safely decode the chunk.
1390 if (keyword_length+1 < read_length &&
1391 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1393 read_length -= keyword_length+2;
1395 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1397 Byte profile_header[132];
1398 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1399 png_alloc_size_t size = (sizeof profile_header);
1401 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1402 png_ptr->zstream.avail_in = read_length;
1403 (void)png_inflate_read(png_ptr, local_buffer,
1404 (sizeof local_buffer), &length, profile_header, &size,
1405 0/*finish: don't, because the output is too small*/);
1407 if (size == 0)
1409 /* We have the ICC profile header; do the basic header checks.
1411 const png_uint_32 profile_length =
1412 png_get_uint_32(profile_header);
1414 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1415 keyword, profile_length) != 0)
1417 /* The length is apparently ok, so we can check the 132
1418 * byte header.
1420 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1421 keyword, profile_length, profile_header,
1422 png_ptr->color_type) != 0)
1424 /* Now read the tag table; a variable size buffer is
1425 * needed at this point, allocate one for the whole
1426 * profile. The header check has already validated
1427 * that none of these stuff will overflow.
1429 const png_uint_32 tag_count = png_get_uint_32(
1430 profile_header+128);
1431 png_bytep profile = png_read_buffer(png_ptr,
1432 profile_length, 2/*silent*/);
1434 if (profile != NULL)
1436 memcpy(profile, profile_header,
1437 (sizeof profile_header));
1439 size = 12 * tag_count;
1441 (void)png_inflate_read(png_ptr, local_buffer,
1442 (sizeof local_buffer), &length,
1443 profile + (sizeof profile_header), &size, 0);
1445 /* Still expect a buffer error because we expect
1446 * there to be some tag data!
1448 if (size == 0)
1450 if (png_icc_check_tag_table(png_ptr,
1451 &png_ptr->colorspace, keyword, profile_length,
1452 profile) != 0)
1454 /* The profile has been validated for basic
1455 * security issues, so read the whole thing in.
1457 size = profile_length - (sizeof profile_header)
1458 - 12 * tag_count;
1460 (void)png_inflate_read(png_ptr, local_buffer,
1461 (sizeof local_buffer), &length,
1462 profile + (sizeof profile_header) +
1463 12 * tag_count, &size, 1/*finish*/);
1465 if (length > 0 && !(png_ptr->flags &
1466 PNG_FLAG_BENIGN_ERRORS_WARN))
1467 errmsg = "extra compressed data";
1469 /* But otherwise allow extra data: */
1470 else if (size == 0)
1472 if (length > 0)
1474 /* This can be handled completely, so
1475 * keep going.
1477 png_chunk_warning(png_ptr,
1478 "extra compressed data");
1481 png_crc_finish(png_ptr, length);
1482 finished = 1;
1484 # ifdef PNG_sRGB_SUPPORTED
1485 /* Check for a match against sRGB */
1486 png_icc_set_sRGB(png_ptr,
1487 &png_ptr->colorspace, profile,
1488 png_ptr->zstream.adler);
1489 # endif
1491 /* Steal the profile for info_ptr. */
1492 if (info_ptr != NULL)
1494 png_free_data(png_ptr, info_ptr,
1495 PNG_FREE_ICCP, 0);
1497 info_ptr->iccp_name = png_voidcast(char*,
1498 png_malloc_base(png_ptr,
1499 keyword_length+1));
1500 if (info_ptr->iccp_name != NULL)
1502 memcpy(info_ptr->iccp_name, keyword,
1503 keyword_length+1);
1504 info_ptr->iccp_proflen =
1505 profile_length;
1506 info_ptr->iccp_profile = profile;
1507 png_ptr->read_buffer = NULL; /*steal*/
1508 info_ptr->free_me |= PNG_FREE_ICCP;
1509 info_ptr->valid |= PNG_INFO_iCCP;
1512 else
1514 png_ptr->colorspace.flags |=
1515 PNG_COLORSPACE_INVALID;
1516 errmsg = "out of memory";
1520 /* else the profile remains in the read
1521 * buffer which gets reused for subsequent
1522 * chunks.
1525 if (info_ptr != NULL)
1526 png_colorspace_sync(png_ptr, info_ptr);
1528 if (errmsg == NULL)
1530 png_ptr->zowner = 0;
1531 return;
1535 else if (size > 0)
1536 errmsg = "truncated";
1538 #ifndef __COVERITY__
1539 else
1540 errmsg = png_ptr->zstream.msg;
1541 #endif
1544 /* else png_icc_check_tag_table output an error */
1547 else /* profile truncated */
1548 errmsg = png_ptr->zstream.msg;
1551 else
1552 errmsg = "out of memory";
1555 /* else png_icc_check_header output an error */
1558 /* else png_icc_check_length output an error */
1561 else /* profile truncated */
1562 errmsg = png_ptr->zstream.msg;
1564 /* Release the stream */
1565 png_ptr->zowner = 0;
1568 else /* png_inflate_claim failed */
1569 errmsg = png_ptr->zstream.msg;
1572 else
1573 errmsg = "bad compression method"; /* or missing */
1576 else
1577 errmsg = "bad keyword";
1580 else
1581 errmsg = "too many profiles";
1583 /* Failure: the reason is in 'errmsg' */
1584 if (finished == 0)
1585 png_crc_finish(png_ptr, length);
1587 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1588 png_colorspace_sync(png_ptr, info_ptr);
1589 if (errmsg != NULL) /* else already output */
1590 png_chunk_benign_error(png_ptr, errmsg);
1592 #endif /* READ_iCCP */
1594 #ifdef PNG_READ_sPLT_SUPPORTED
1595 void /* PRIVATE */
1596 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1597 /* Note: this does not properly handle chunks that are > 64K under DOS */
1599 png_bytep entry_start, buffer;
1600 png_sPLT_t new_palette;
1601 png_sPLT_entryp pp;
1602 png_uint_32 data_length;
1603 int entry_size, i;
1604 png_uint_32 skip = 0;
1605 png_uint_32 dl;
1606 png_size_t max_dl;
1608 png_debug(1, "in png_handle_sPLT");
1610 #ifdef PNG_USER_LIMITS_SUPPORTED
1611 if (png_ptr->user_chunk_cache_max != 0)
1613 if (png_ptr->user_chunk_cache_max == 1)
1615 png_crc_finish(png_ptr, length);
1616 return;
1619 if (--png_ptr->user_chunk_cache_max == 1)
1621 png_warning(png_ptr, "No space in chunk cache for sPLT");
1622 png_crc_finish(png_ptr, length);
1623 return;
1626 #endif
1628 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1629 png_chunk_error(png_ptr, "missing IHDR");
1631 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1633 png_crc_finish(png_ptr, length);
1634 png_chunk_benign_error(png_ptr, "out of place");
1635 return;
1638 #ifdef PNG_MAX_MALLOC_64K
1639 if (length > 65535U)
1641 png_crc_finish(png_ptr, length);
1642 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1643 return;
1645 #endif
1647 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1648 if (buffer == NULL)
1650 png_crc_finish(png_ptr, length);
1651 png_chunk_benign_error(png_ptr, "out of memory");
1652 return;
1656 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1657 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1658 * potential breakage point if the types in pngconf.h aren't exactly right.
1660 png_crc_read(png_ptr, buffer, length);
1662 if (png_crc_finish(png_ptr, skip) != 0)
1663 return;
1665 buffer[length] = 0;
1667 for (entry_start = buffer; *entry_start; entry_start++)
1668 /* Empty loop to find end of name */ ;
1670 ++entry_start;
1672 /* A sample depth should follow the separator, and we should be on it */
1673 if (entry_start > buffer + length - 2)
1675 png_warning(png_ptr, "malformed sPLT chunk");
1676 return;
1679 new_palette.depth = *entry_start++;
1680 entry_size = (new_palette.depth == 8 ? 6 : 10);
1681 /* This must fit in a png_uint_32 because it is derived from the original
1682 * chunk data length.
1684 data_length = length - (png_uint_32)(entry_start - buffer);
1686 /* Integrity-check the data length */
1687 if ((data_length % entry_size) != 0)
1689 png_warning(png_ptr, "sPLT chunk has bad length");
1690 return;
1693 dl = (png_int_32)(data_length / entry_size);
1694 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1696 if (dl > max_dl)
1698 png_warning(png_ptr, "sPLT chunk too long");
1699 return;
1702 new_palette.nentries = (png_int_32)(data_length / entry_size);
1704 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
1705 png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
1707 if (new_palette.entries == NULL)
1709 png_warning(png_ptr, "sPLT chunk requires too much memory");
1710 return;
1713 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1714 for (i = 0; i < new_palette.nentries; i++)
1716 pp = new_palette.entries + i;
1718 if (new_palette.depth == 8)
1720 pp->red = *entry_start++;
1721 pp->green = *entry_start++;
1722 pp->blue = *entry_start++;
1723 pp->alpha = *entry_start++;
1726 else
1728 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1729 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1730 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1731 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1734 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1736 #else
1737 pp = new_palette.entries;
1739 for (i = 0; i < new_palette.nentries; i++)
1742 if (new_palette.depth == 8)
1744 pp[i].red = *entry_start++;
1745 pp[i].green = *entry_start++;
1746 pp[i].blue = *entry_start++;
1747 pp[i].alpha = *entry_start++;
1750 else
1752 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1753 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1754 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1755 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1758 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1760 #endif
1762 /* Discard all chunk data except the name and stash that */
1763 new_palette.name = (png_charp)buffer;
1765 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1767 png_free(png_ptr, new_palette.entries);
1769 #endif /* READ_sPLT */
1771 #ifdef PNG_READ_tRNS_SUPPORTED
1772 void /* PRIVATE */
1773 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1775 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1777 png_debug(1, "in png_handle_tRNS");
1779 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1780 png_chunk_error(png_ptr, "missing IHDR");
1782 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1784 png_crc_finish(png_ptr, length);
1785 png_chunk_benign_error(png_ptr, "out of place");
1786 return;
1789 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1791 png_crc_finish(png_ptr, length);
1792 png_chunk_benign_error(png_ptr, "duplicate");
1793 return;
1796 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1798 png_byte buf[2];
1800 if (length != 2)
1802 png_crc_finish(png_ptr, length);
1803 png_chunk_benign_error(png_ptr, "invalid");
1804 return;
1807 png_crc_read(png_ptr, buf, 2);
1808 png_ptr->num_trans = 1;
1809 png_ptr->trans_color.gray = png_get_uint_16(buf);
1812 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1814 png_byte buf[6];
1816 if (length != 6)
1818 png_crc_finish(png_ptr, length);
1819 png_chunk_benign_error(png_ptr, "invalid");
1820 return;
1823 png_crc_read(png_ptr, buf, length);
1824 png_ptr->num_trans = 1;
1825 png_ptr->trans_color.red = png_get_uint_16(buf);
1826 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1827 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1830 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1832 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1834 /* TODO: is this actually an error in the ISO spec? */
1835 png_crc_finish(png_ptr, length);
1836 png_chunk_benign_error(png_ptr, "out of place");
1837 return;
1840 if (length > (unsigned int) png_ptr->num_palette ||
1841 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1842 length == 0)
1844 png_crc_finish(png_ptr, length);
1845 png_chunk_benign_error(png_ptr, "invalid");
1846 return;
1849 png_crc_read(png_ptr, readbuf, length);
1850 png_ptr->num_trans = (png_uint_16)length;
1853 else
1855 png_crc_finish(png_ptr, length);
1856 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1857 return;
1860 if (png_crc_finish(png_ptr, 0) != 0)
1862 png_ptr->num_trans = 0;
1863 return;
1866 /* TODO: this is a horrible side effect in the palette case because the
1867 * png_struct ends up with a pointer to the tRNS buffer owned by the
1868 * png_info. Fix this.
1870 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1871 &(png_ptr->trans_color));
1873 #endif
1875 #ifdef PNG_READ_bKGD_SUPPORTED
1876 void /* PRIVATE */
1877 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1879 unsigned int truelen;
1880 png_byte buf[6];
1881 png_color_16 background;
1883 png_debug(1, "in png_handle_bKGD");
1885 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1886 png_chunk_error(png_ptr, "missing IHDR");
1888 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1889 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1890 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1892 png_crc_finish(png_ptr, length);
1893 png_chunk_benign_error(png_ptr, "out of place");
1894 return;
1897 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1899 png_crc_finish(png_ptr, length);
1900 png_chunk_benign_error(png_ptr, "duplicate");
1901 return;
1904 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1905 truelen = 1;
1907 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1908 truelen = 6;
1910 else
1911 truelen = 2;
1913 if (length != truelen)
1915 png_crc_finish(png_ptr, length);
1916 png_chunk_benign_error(png_ptr, "invalid");
1917 return;
1920 png_crc_read(png_ptr, buf, truelen);
1922 if (png_crc_finish(png_ptr, 0) != 0)
1923 return;
1925 /* We convert the index value into RGB components so that we can allow
1926 * arbitrary RGB values for background when we have transparency, and
1927 * so it is easy to determine the RGB values of the background color
1928 * from the info_ptr struct.
1930 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1932 background.index = buf[0];
1934 if (info_ptr != NULL && info_ptr->num_palette != 0)
1936 if (buf[0] >= info_ptr->num_palette)
1938 png_chunk_benign_error(png_ptr, "invalid index");
1939 return;
1942 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1943 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1944 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1947 else
1948 background.red = background.green = background.blue = 0;
1950 background.gray = 0;
1953 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1955 background.index = 0;
1956 background.red =
1957 background.green =
1958 background.blue =
1959 background.gray = png_get_uint_16(buf);
1962 else
1964 background.index = 0;
1965 background.red = png_get_uint_16(buf);
1966 background.green = png_get_uint_16(buf + 2);
1967 background.blue = png_get_uint_16(buf + 4);
1968 background.gray = 0;
1971 png_set_bKGD(png_ptr, info_ptr, &background);
1973 #endif
1975 #ifdef PNG_READ_hIST_SUPPORTED
1976 void /* PRIVATE */
1977 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1979 unsigned int num, i;
1980 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
1982 png_debug(1, "in png_handle_hIST");
1984 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1985 png_chunk_error(png_ptr, "missing IHDR");
1987 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1988 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
1990 png_crc_finish(png_ptr, length);
1991 png_chunk_benign_error(png_ptr, "out of place");
1992 return;
1995 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1997 png_crc_finish(png_ptr, length);
1998 png_chunk_benign_error(png_ptr, "duplicate");
1999 return;
2002 num = length / 2 ;
2004 if (num != (unsigned int) png_ptr->num_palette ||
2005 num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
2007 png_crc_finish(png_ptr, length);
2008 png_chunk_benign_error(png_ptr, "invalid");
2009 return;
2012 for (i = 0; i < num; i++)
2014 png_byte buf[2];
2016 png_crc_read(png_ptr, buf, 2);
2017 readbuf[i] = png_get_uint_16(buf);
2020 if (png_crc_finish(png_ptr, 0) != 0)
2021 return;
2023 png_set_hIST(png_ptr, info_ptr, readbuf);
2025 #endif
2027 #ifdef PNG_READ_pHYs_SUPPORTED
2028 void /* PRIVATE */
2029 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2031 png_byte buf[9];
2032 png_uint_32 res_x, res_y;
2033 int unit_type;
2035 png_debug(1, "in png_handle_pHYs");
2037 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2038 png_chunk_error(png_ptr, "missing IHDR");
2040 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2042 png_crc_finish(png_ptr, length);
2043 png_chunk_benign_error(png_ptr, "out of place");
2044 return;
2047 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2049 png_crc_finish(png_ptr, length);
2050 png_chunk_benign_error(png_ptr, "duplicate");
2051 return;
2054 if (length != 9)
2056 png_crc_finish(png_ptr, length);
2057 png_chunk_benign_error(png_ptr, "invalid");
2058 return;
2061 png_crc_read(png_ptr, buf, 9);
2063 if (png_crc_finish(png_ptr, 0) != 0)
2064 return;
2066 res_x = png_get_uint_32(buf);
2067 res_y = png_get_uint_32(buf + 4);
2068 unit_type = buf[8];
2069 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2071 #endif
2073 #ifdef PNG_READ_oFFs_SUPPORTED
2074 void /* PRIVATE */
2075 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2077 png_byte buf[9];
2078 png_int_32 offset_x, offset_y;
2079 int unit_type;
2081 png_debug(1, "in png_handle_oFFs");
2083 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2084 png_chunk_error(png_ptr, "missing IHDR");
2086 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2088 png_crc_finish(png_ptr, length);
2089 png_chunk_benign_error(png_ptr, "out of place");
2090 return;
2093 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2095 png_crc_finish(png_ptr, length);
2096 png_chunk_benign_error(png_ptr, "duplicate");
2097 return;
2100 if (length != 9)
2102 png_crc_finish(png_ptr, length);
2103 png_chunk_benign_error(png_ptr, "invalid");
2104 return;
2107 png_crc_read(png_ptr, buf, 9);
2109 if (png_crc_finish(png_ptr, 0) != 0)
2110 return;
2112 offset_x = png_get_int_32(buf);
2113 offset_y = png_get_int_32(buf + 4);
2114 unit_type = buf[8];
2115 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2117 #endif
2119 #ifdef PNG_READ_pCAL_SUPPORTED
2120 /* Read the pCAL chunk (described in the PNG Extensions document) */
2121 void /* PRIVATE */
2122 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2124 png_int_32 X0, X1;
2125 png_byte type, nparams;
2126 png_bytep buffer, buf, units, endptr;
2127 png_charpp params;
2128 int i;
2130 png_debug(1, "in png_handle_pCAL");
2132 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2133 png_chunk_error(png_ptr, "missing IHDR");
2135 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2137 png_crc_finish(png_ptr, length);
2138 png_chunk_benign_error(png_ptr, "out of place");
2139 return;
2142 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2144 png_crc_finish(png_ptr, length);
2145 png_chunk_benign_error(png_ptr, "duplicate");
2146 return;
2149 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2150 length + 1);
2152 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2154 if (buffer == NULL)
2156 png_crc_finish(png_ptr, length);
2157 png_chunk_benign_error(png_ptr, "out of memory");
2158 return;
2161 png_crc_read(png_ptr, buffer, length);
2163 if (png_crc_finish(png_ptr, 0) != 0)
2164 return;
2166 buffer[length] = 0; /* Null terminate the last string */
2168 png_debug(3, "Finding end of pCAL purpose string");
2169 for (buf = buffer; *buf; buf++)
2170 /* Empty loop */ ;
2172 endptr = buffer + length;
2174 /* We need to have at least 12 bytes after the purpose string
2175 * in order to get the parameter information.
2177 if (endptr <= buf + 12)
2179 png_chunk_benign_error(png_ptr, "invalid");
2180 return;
2183 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2184 X0 = png_get_int_32((png_bytep)buf+1);
2185 X1 = png_get_int_32((png_bytep)buf+5);
2186 type = buf[9];
2187 nparams = buf[10];
2188 units = buf + 11;
2190 png_debug(3, "Checking pCAL equation type and number of parameters");
2191 /* Check that we have the right number of parameters for known
2192 * equation types.
2194 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2195 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2196 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2197 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2199 png_chunk_benign_error(png_ptr, "invalid parameter count");
2200 return;
2203 else if (type >= PNG_EQUATION_LAST)
2205 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2208 for (buf = units; *buf; buf++)
2209 /* Empty loop to move past the units string. */ ;
2211 png_debug(3, "Allocating pCAL parameters array");
2213 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2214 nparams * (sizeof (png_charp))));
2216 if (params == NULL)
2218 png_chunk_benign_error(png_ptr, "out of memory");
2219 return;
2222 /* Get pointers to the start of each parameter string. */
2223 for (i = 0; i < nparams; i++)
2225 buf++; /* Skip the null string terminator from previous parameter. */
2227 png_debug1(3, "Reading pCAL parameter %d", i);
2229 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2230 /* Empty loop to move past each parameter string */ ;
2232 /* Make sure we haven't run out of data yet */
2233 if (buf > endptr)
2235 png_free(png_ptr, params);
2236 png_chunk_benign_error(png_ptr, "invalid data");
2237 return;
2241 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2242 (png_charp)units, params);
2244 png_free(png_ptr, params);
2246 #endif
2248 #ifdef PNG_READ_sCAL_SUPPORTED
2249 /* Read the sCAL chunk */
2250 void /* PRIVATE */
2251 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2253 png_bytep buffer;
2254 png_size_t i;
2255 int state;
2257 png_debug(1, "in png_handle_sCAL");
2259 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2260 png_chunk_error(png_ptr, "missing IHDR");
2262 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2264 png_crc_finish(png_ptr, length);
2265 png_chunk_benign_error(png_ptr, "out of place");
2266 return;
2269 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2271 png_crc_finish(png_ptr, length);
2272 png_chunk_benign_error(png_ptr, "duplicate");
2273 return;
2276 /* Need unit type, width, \0, height: minimum 4 bytes */
2277 else if (length < 4)
2279 png_crc_finish(png_ptr, length);
2280 png_chunk_benign_error(png_ptr, "invalid");
2281 return;
2284 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2285 length + 1);
2287 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2289 if (buffer == NULL)
2291 png_chunk_benign_error(png_ptr, "out of memory");
2292 png_crc_finish(png_ptr, length);
2293 return;
2296 png_crc_read(png_ptr, buffer, length);
2297 buffer[length] = 0; /* Null terminate the last string */
2299 if (png_crc_finish(png_ptr, 0) != 0)
2300 return;
2302 /* Validate the unit. */
2303 if (buffer[0] != 1 && buffer[0] != 2)
2305 png_chunk_benign_error(png_ptr, "invalid unit");
2306 return;
2309 /* Validate the ASCII numbers, need two ASCII numbers separated by
2310 * a '\0' and they need to fit exactly in the chunk data.
2312 i = 1;
2313 state = 0;
2315 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2316 i >= length || buffer[i++] != 0)
2317 png_chunk_benign_error(png_ptr, "bad width format");
2319 else if (PNG_FP_IS_POSITIVE(state) == 0)
2320 png_chunk_benign_error(png_ptr, "non-positive width");
2322 else
2324 png_size_t heighti = i;
2326 state = 0;
2327 if (png_check_fp_number((png_const_charp)buffer, length,
2328 &state, &i) == 0 || i != length)
2329 png_chunk_benign_error(png_ptr, "bad height format");
2331 else if (PNG_FP_IS_POSITIVE(state) == 0)
2332 png_chunk_benign_error(png_ptr, "non-positive height");
2334 else
2335 /* This is the (only) success case. */
2336 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2337 (png_charp)buffer+1, (png_charp)buffer+heighti);
2340 #endif
2342 #ifdef PNG_READ_tIME_SUPPORTED
2343 void /* PRIVATE */
2344 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2346 png_byte buf[7];
2347 png_time mod_time;
2349 png_debug(1, "in png_handle_tIME");
2351 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2352 png_chunk_error(png_ptr, "missing IHDR");
2354 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2356 png_crc_finish(png_ptr, length);
2357 png_chunk_benign_error(png_ptr, "duplicate");
2358 return;
2361 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2362 png_ptr->mode |= PNG_AFTER_IDAT;
2364 if (length != 7)
2366 png_crc_finish(png_ptr, length);
2367 png_chunk_benign_error(png_ptr, "invalid");
2368 return;
2371 png_crc_read(png_ptr, buf, 7);
2373 if (png_crc_finish(png_ptr, 0) != 0)
2374 return;
2376 mod_time.second = buf[6];
2377 mod_time.minute = buf[5];
2378 mod_time.hour = buf[4];
2379 mod_time.day = buf[3];
2380 mod_time.month = buf[2];
2381 mod_time.year = png_get_uint_16(buf);
2383 png_set_tIME(png_ptr, info_ptr, &mod_time);
2385 #endif
2387 #ifdef PNG_READ_tEXt_SUPPORTED
2388 /* Note: this does not properly handle chunks that are > 64K under DOS */
2389 void /* PRIVATE */
2390 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2392 png_text text_info;
2393 png_bytep buffer;
2394 png_charp key;
2395 png_charp text;
2396 png_uint_32 skip = 0;
2398 png_debug(1, "in png_handle_tEXt");
2400 #ifdef PNG_USER_LIMITS_SUPPORTED
2401 if (png_ptr->user_chunk_cache_max != 0)
2403 if (png_ptr->user_chunk_cache_max == 1)
2405 png_crc_finish(png_ptr, length);
2406 return;
2409 if (--png_ptr->user_chunk_cache_max == 1)
2411 png_crc_finish(png_ptr, length);
2412 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2413 return;
2416 #endif
2418 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2419 png_chunk_error(png_ptr, "missing IHDR");
2421 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2422 png_ptr->mode |= PNG_AFTER_IDAT;
2424 #ifdef PNG_MAX_MALLOC_64K
2425 if (length > 65535U)
2427 png_crc_finish(png_ptr, length);
2428 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2429 return;
2431 #endif
2433 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2435 if (buffer == NULL)
2437 png_chunk_benign_error(png_ptr, "out of memory");
2438 return;
2441 png_crc_read(png_ptr, buffer, length);
2443 if (png_crc_finish(png_ptr, skip) != 0)
2444 return;
2446 key = (png_charp)buffer;
2447 key[length] = 0;
2449 for (text = key; *text; text++)
2450 /* Empty loop to find end of key */ ;
2452 if (text != key + length)
2453 text++;
2455 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2456 text_info.key = key;
2457 text_info.lang = NULL;
2458 text_info.lang_key = NULL;
2459 text_info.itxt_length = 0;
2460 text_info.text = text;
2461 text_info.text_length = strlen(text);
2463 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2464 png_warning(png_ptr, "Insufficient memory to process text chunk");
2466 #endif
2468 #ifdef PNG_READ_zTXt_SUPPORTED
2469 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2470 void /* PRIVATE */
2471 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2473 png_const_charp errmsg = NULL;
2474 png_bytep buffer;
2475 png_uint_32 keyword_length;
2477 png_debug(1, "in png_handle_zTXt");
2479 #ifdef PNG_USER_LIMITS_SUPPORTED
2480 if (png_ptr->user_chunk_cache_max != 0)
2482 if (png_ptr->user_chunk_cache_max == 1)
2484 png_crc_finish(png_ptr, length);
2485 return;
2488 if (--png_ptr->user_chunk_cache_max == 1)
2490 png_crc_finish(png_ptr, length);
2491 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2492 return;
2495 #endif
2497 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2498 png_chunk_error(png_ptr, "missing IHDR");
2500 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2501 png_ptr->mode |= PNG_AFTER_IDAT;
2503 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2505 if (buffer == NULL)
2507 png_crc_finish(png_ptr, length);
2508 png_chunk_benign_error(png_ptr, "out of memory");
2509 return;
2512 png_crc_read(png_ptr, buffer, length);
2514 if (png_crc_finish(png_ptr, 0) != 0)
2515 return;
2517 /* TODO: also check that the keyword contents match the spec! */
2518 for (keyword_length = 0;
2519 keyword_length < length && buffer[keyword_length] != 0;
2520 ++keyword_length)
2521 /* Empty loop to find end of name */ ;
2523 if (keyword_length > 79 || keyword_length < 1)
2524 errmsg = "bad keyword";
2526 /* zTXt must have some LZ data after the keyword, although it may expand to
2527 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2528 * then the LZ data:
2530 else if (keyword_length + 3 > length)
2531 errmsg = "truncated";
2533 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2534 errmsg = "unknown compression type";
2536 else
2538 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2540 /* TODO: at present png_decompress_chunk imposes a single application
2541 * level memory limit, this should be split to different values for iCCP
2542 * and text chunks.
2544 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2545 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2547 png_text text;
2549 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
2550 * for the extra compression type byte and the fact that it isn't
2551 * necessarily '\0' terminated.
2553 buffer = png_ptr->read_buffer;
2554 buffer[uncompressed_length+(keyword_length+2)] = 0;
2556 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2557 text.key = (png_charp)buffer;
2558 text.text = (png_charp)(buffer + keyword_length+2);
2559 text.text_length = uncompressed_length;
2560 text.itxt_length = 0;
2561 text.lang = NULL;
2562 text.lang_key = NULL;
2564 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2565 errmsg = "insufficient memory";
2568 else
2569 errmsg = png_ptr->zstream.msg;
2572 if (errmsg != NULL)
2573 png_chunk_benign_error(png_ptr, errmsg);
2575 #endif
2577 #ifdef PNG_READ_iTXt_SUPPORTED
2578 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2579 void /* PRIVATE */
2580 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2582 png_const_charp errmsg = NULL;
2583 png_bytep buffer;
2584 png_uint_32 prefix_length;
2586 png_debug(1, "in png_handle_iTXt");
2588 #ifdef PNG_USER_LIMITS_SUPPORTED
2589 if (png_ptr->user_chunk_cache_max != 0)
2591 if (png_ptr->user_chunk_cache_max == 1)
2593 png_crc_finish(png_ptr, length);
2594 return;
2597 if (--png_ptr->user_chunk_cache_max == 1)
2599 png_crc_finish(png_ptr, length);
2600 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2601 return;
2604 #endif
2606 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2607 png_chunk_error(png_ptr, "missing IHDR");
2609 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2610 png_ptr->mode |= PNG_AFTER_IDAT;
2612 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2614 if (buffer == NULL)
2616 png_crc_finish(png_ptr, length);
2617 png_chunk_benign_error(png_ptr, "out of memory");
2618 return;
2621 png_crc_read(png_ptr, buffer, length);
2623 if (png_crc_finish(png_ptr, 0) != 0)
2624 return;
2626 /* First the keyword. */
2627 for (prefix_length=0;
2628 prefix_length < length && buffer[prefix_length] != 0;
2629 ++prefix_length)
2630 /* Empty loop */ ;
2632 /* Perform a basic check on the keyword length here. */
2633 if (prefix_length > 79 || prefix_length < 1)
2634 errmsg = "bad keyword";
2636 /* Expect keyword, compression flag, compression type, language, translated
2637 * keyword (both may be empty but are 0 terminated) then the text, which may
2638 * be empty.
2640 else if (prefix_length + 5 > length)
2641 errmsg = "truncated";
2643 else if (buffer[prefix_length+1] == 0 ||
2644 (buffer[prefix_length+1] == 1 &&
2645 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2647 int compressed = buffer[prefix_length+1] != 0;
2648 png_uint_32 language_offset, translated_keyword_offset;
2649 png_alloc_size_t uncompressed_length = 0;
2651 /* Now the language tag */
2652 prefix_length += 3;
2653 language_offset = prefix_length;
2655 for (; prefix_length < length && buffer[prefix_length] != 0;
2656 ++prefix_length)
2657 /* Empty loop */ ;
2659 /* WARNING: the length may be invalid here, this is checked below. */
2660 translated_keyword_offset = ++prefix_length;
2662 for (; prefix_length < length && buffer[prefix_length] != 0;
2663 ++prefix_length)
2664 /* Empty loop */ ;
2666 /* prefix_length should now be at the trailing '\0' of the translated
2667 * keyword, but it may already be over the end. None of this arithmetic
2668 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2669 * systems the available allocation may overflow.
2671 ++prefix_length;
2673 if (compressed == 0 && prefix_length <= length)
2674 uncompressed_length = length - prefix_length;
2676 else if (compressed != 0 && prefix_length < length)
2678 uncompressed_length = PNG_SIZE_MAX;
2680 /* TODO: at present png_decompress_chunk imposes a single application
2681 * level memory limit, this should be split to different values for
2682 * iCCP and text chunks.
2684 if (png_decompress_chunk(png_ptr, length, prefix_length,
2685 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2686 buffer = png_ptr->read_buffer;
2688 else
2689 errmsg = png_ptr->zstream.msg;
2692 else
2693 errmsg = "truncated";
2695 if (errmsg == NULL)
2697 png_text text;
2699 buffer[uncompressed_length+prefix_length] = 0;
2701 if (compressed == 0)
2702 text.compression = PNG_ITXT_COMPRESSION_NONE;
2704 else
2705 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2707 text.key = (png_charp)buffer;
2708 text.lang = (png_charp)buffer + language_offset;
2709 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2710 text.text = (png_charp)buffer + prefix_length;
2711 text.text_length = 0;
2712 text.itxt_length = uncompressed_length;
2714 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2715 errmsg = "insufficient memory";
2719 else
2720 errmsg = "bad compression info";
2722 if (errmsg != NULL)
2723 png_chunk_benign_error(png_ptr, errmsg);
2725 #endif
2727 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2728 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2729 static int
2730 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2732 png_alloc_size_t limit = PNG_SIZE_MAX;
2734 if (png_ptr->unknown_chunk.data != NULL)
2736 png_free(png_ptr, png_ptr->unknown_chunk.data);
2737 png_ptr->unknown_chunk.data = NULL;
2740 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
2741 if (png_ptr->user_chunk_malloc_max > 0 &&
2742 png_ptr->user_chunk_malloc_max < limit)
2743 limit = png_ptr->user_chunk_malloc_max;
2745 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2746 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2747 limit = PNG_USER_CHUNK_MALLOC_MAX;
2748 # endif
2750 if (length <= limit)
2752 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2753 /* The following is safe because of the PNG_SIZE_MAX init above */
2754 png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
2755 /* 'mode' is a flag array, only the bottom four bits matter here */
2756 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2758 if (length == 0)
2759 png_ptr->unknown_chunk.data = NULL;
2761 else
2763 /* Do a 'warn' here - it is handled below. */
2764 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2765 png_malloc_warn(png_ptr, length));
2769 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2771 /* This is benign because we clean up correctly */
2772 png_crc_finish(png_ptr, length);
2773 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2774 return 0;
2777 else
2779 if (length > 0)
2780 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2781 png_crc_finish(png_ptr, 0);
2782 return 1;
2785 #endif /* READ_UNKNOWN_CHUNKS */
2787 /* Handle an unknown, or known but disabled, chunk */
2788 void /* PRIVATE */
2789 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2790 png_uint_32 length, int keep)
2792 int handled = 0; /* the chunk was handled */
2794 png_debug(1, "in png_handle_unknown");
2796 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2797 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2798 * the bug which meant that setting a non-default behavior for a specific
2799 * chunk would be ignored (the default was always used unless a user
2800 * callback was installed).
2802 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2803 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2804 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2805 * This is just an optimization to avoid multiple calls to the lookup
2806 * function.
2808 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2809 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2810 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2811 # endif
2812 # endif
2814 /* One of the following methods will read the chunk or skip it (at least one
2815 * of these is always defined because this is the only way to switch on
2816 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2818 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2819 /* The user callback takes precedence over the chunk keep value, but the
2820 * keep value is still required to validate a save of a critical chunk.
2822 if (png_ptr->read_user_chunk_fn != NULL)
2824 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2826 /* Callback to user unknown chunk handler */
2827 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2828 &png_ptr->unknown_chunk);
2830 /* ret is:
2831 * negative: An error occurred; png_chunk_error will be called.
2832 * zero: The chunk was not handled, the chunk will be discarded
2833 * unless png_set_keep_unknown_chunks has been used to set
2834 * a 'keep' behavior for this particular chunk, in which
2835 * case that will be used. A critical chunk will cause an
2836 * error at this point unless it is to be saved.
2837 * positive: The chunk was handled, libpng will ignore/discard it.
2839 if (ret < 0)
2840 png_chunk_error(png_ptr, "error in user chunk");
2842 else if (ret == 0)
2844 /* If the keep value is 'default' or 'never' override it, but
2845 * still error out on critical chunks unless the keep value is
2846 * 'always' While this is weird it is the behavior in 1.4.12.
2847 * A possible improvement would be to obey the value set for the
2848 * chunk, but this would be an API change that would probably
2849 * damage some applications.
2851 * The png_app_warning below catches the case that matters, where
2852 * the application has not set specific save or ignore for this
2853 * chunk or global save or ignore.
2855 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2857 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2858 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2860 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2861 png_app_warning(png_ptr,
2862 "forcing save of an unhandled chunk;"
2863 " please call png_set_keep_unknown_chunks");
2864 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
2866 # endif
2867 keep = PNG_HANDLE_CHUNK_IF_SAFE;
2871 else /* chunk was handled */
2873 handled = 1;
2874 /* Critical chunks can be safely discarded at this point. */
2875 keep = PNG_HANDLE_CHUNK_NEVER;
2879 else
2880 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
2883 else
2884 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
2885 # endif /* READ_USER_CHUNKS */
2887 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
2889 /* keep is currently just the per-chunk setting, if there was no
2890 * setting change it to the global default now (not that this may
2891 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
2892 * if not simply skip the chunk.
2894 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
2895 keep = png_ptr->unknown_default;
2897 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2898 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2899 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2901 if (png_cache_unknown_chunk(png_ptr, length) == 0)
2902 keep = PNG_HANDLE_CHUNK_NEVER;
2905 else
2906 png_crc_finish(png_ptr, length);
2908 # else
2909 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
2910 # error no method to support READ_UNKNOWN_CHUNKS
2911 # endif
2914 /* If here there is no read callback pointer set and no support is
2915 * compiled in to just save the unknown chunks, so simply skip this
2916 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
2917 * the app has erroneously asked for unknown chunk saving when there
2918 * is no support.
2920 if (keep > PNG_HANDLE_CHUNK_NEVER)
2921 png_app_error(png_ptr, "no unknown chunk support available");
2923 png_crc_finish(png_ptr, length);
2925 # endif
2927 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
2928 /* Now store the chunk in the chunk list if appropriate, and if the limits
2929 * permit it.
2931 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2932 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2933 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2935 # ifdef PNG_USER_LIMITS_SUPPORTED
2936 switch (png_ptr->user_chunk_cache_max)
2938 case 2:
2939 png_ptr->user_chunk_cache_max = 1;
2940 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2941 /* FALL THROUGH */
2942 case 1:
2943 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
2944 * chunk being skipped, now there will be a hard error below.
2946 break;
2948 default: /* not at limit */
2949 --(png_ptr->user_chunk_cache_max);
2950 /* FALL THROUGH */
2951 case 0: /* no limit */
2952 # endif /* USER_LIMITS */
2953 /* Here when the limit isn't reached or when limits are compiled
2954 * out; store the chunk.
2956 png_set_unknown_chunks(png_ptr, info_ptr,
2957 &png_ptr->unknown_chunk, 1);
2958 handled = 1;
2959 # ifdef PNG_USER_LIMITS_SUPPORTED
2960 break;
2962 # endif
2964 # else /* no store support: the chunk must be handled by the user callback */
2965 PNG_UNUSED(info_ptr)
2966 # endif
2968 /* Regardless of the error handling below the cached data (if any) can be
2969 * freed now. Notice that the data is not freed if there is a png_error, but
2970 * it will be freed by destroy_read_struct.
2972 if (png_ptr->unknown_chunk.data != NULL)
2973 png_free(png_ptr, png_ptr->unknown_chunk.data);
2974 png_ptr->unknown_chunk.data = NULL;
2976 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
2977 /* There is no support to read an unknown chunk, so just skip it. */
2978 png_crc_finish(png_ptr, length);
2979 PNG_UNUSED(info_ptr)
2980 PNG_UNUSED(keep)
2981 #endif /* !READ_UNKNOWN_CHUNKS */
2983 /* Check for unhandled critical chunks */
2984 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
2985 png_chunk_error(png_ptr, "unhandled critical chunk");
2988 /* This function is called to verify that a chunk name is valid.
2989 * This function can't have the "critical chunk check" incorporated
2990 * into it, since in the future we will need to be able to call user
2991 * functions to handle unknown critical chunks after we check that
2992 * the chunk name itself is valid.
2995 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
2997 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
3000 void /* PRIVATE */
3001 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
3003 int i;
3005 png_debug(1, "in png_check_chunk_name");
3007 for (i=1; i<=4; ++i)
3009 int c = chunk_name & 0xff;
3011 if (c < 65 || c > 122 || (c > 90 && c < 97))
3012 png_chunk_error(png_ptr, "invalid chunk type");
3014 chunk_name >>= 8;
3018 /* Combines the row recently read in with the existing pixels in the row. This
3019 * routine takes care of alpha and transparency if requested. This routine also
3020 * handles the two methods of progressive display of interlaced images,
3021 * depending on the 'display' value; if 'display' is true then the whole row
3022 * (dp) is filled from the start by replicating the available pixels. If
3023 * 'display' is false only those pixels present in the pass are filled in.
3025 void /* PRIVATE */
3026 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3028 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3029 png_const_bytep sp = png_ptr->row_buf + 1;
3030 png_alloc_size_t row_width = png_ptr->width;
3031 unsigned int pass = png_ptr->pass;
3032 png_bytep end_ptr = 0;
3033 png_byte end_byte = 0;
3034 unsigned int end_mask;
3036 png_debug(1, "in png_combine_row");
3038 /* Added in 1.5.6: it should not be possible to enter this routine until at
3039 * least one row has been read from the PNG data and transformed.
3041 if (pixel_depth == 0)
3042 png_error(png_ptr, "internal row logic error");
3044 /* Added in 1.5.4: the pixel depth should match the information returned by
3045 * any call to png_read_update_info at this point. Do not continue if we got
3046 * this wrong.
3048 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3049 PNG_ROWBYTES(pixel_depth, row_width))
3050 png_error(png_ptr, "internal row size calculation error");
3052 /* Don't expect this to ever happen: */
3053 if (row_width == 0)
3054 png_error(png_ptr, "internal row width error");
3056 /* Preserve the last byte in cases where only part of it will be overwritten,
3057 * the multiply below may overflow, we don't care because ANSI-C guarantees
3058 * we get the low bits.
3060 end_mask = (pixel_depth * row_width) & 7;
3061 if (end_mask != 0)
3063 /* end_ptr == NULL is a flag to say do nothing */
3064 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3065 end_byte = *end_ptr;
3066 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3067 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3068 /* little-endian byte */
3069 end_mask = 0xff << end_mask;
3071 else /* big-endian byte */
3072 # endif
3073 end_mask = 0xff >> end_mask;
3074 /* end_mask is now the bits to *keep* from the destination row */
3077 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3078 * will also happen if interlacing isn't supported or if the application
3079 * does not call png_set_interlace_handling(). In the latter cases the
3080 * caller just gets a sequence of the unexpanded rows from each interlace
3081 * pass.
3083 #ifdef PNG_READ_INTERLACING_SUPPORTED
3084 if (png_ptr->interlaced != 0 &&
3085 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3086 pass < 6 && (display == 0 ||
3087 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3088 (display == 1 && (pass & 1) != 0)))
3090 /* Narrow images may have no bits in a pass; the caller should handle
3091 * this, but this test is cheap:
3093 if (row_width <= PNG_PASS_START_COL(pass))
3094 return;
3096 if (pixel_depth < 8)
3098 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3099 * into 32 bits, then a single loop over the bytes using the four byte
3100 * values in the 32-bit mask can be used. For the 'display' option the
3101 * expanded mask may also not require any masking within a byte. To
3102 * make this work the PACKSWAP option must be taken into account - it
3103 * simply requires the pixels to be reversed in each byte.
3105 * The 'regular' case requires a mask for each of the first 6 passes,
3106 * the 'display' case does a copy for the even passes in the range
3107 * 0..6. This has already been handled in the test above.
3109 * The masks are arranged as four bytes with the first byte to use in
3110 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3111 * not) of the pixels in each byte.
3113 * NOTE: the whole of this logic depends on the caller of this function
3114 * only calling it on rows appropriate to the pass. This function only
3115 * understands the 'x' logic; the 'y' logic is handled by the caller.
3117 * The following defines allow generation of compile time constant bit
3118 * masks for each pixel depth and each possibility of swapped or not
3119 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3120 * is in the range 0..7; and the result is 1 if the pixel is to be
3121 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3122 * for the block method.
3124 * With some compilers a compile time expression of the general form:
3126 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3128 * Produces warnings with values of 'shift' in the range 33 to 63
3129 * because the right hand side of the ?: expression is evaluated by
3130 * the compiler even though it isn't used. Microsoft Visual C (various
3131 * versions) and the Intel C compiler are known to do this. To avoid
3132 * this the following macros are used in 1.5.6. This is a temporary
3133 * solution to avoid destabilizing the code during the release process.
3135 # if PNG_USE_COMPILE_TIME_MASKS
3136 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3137 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3138 # else
3139 # define PNG_LSR(x,s) ((x)>>(s))
3140 # define PNG_LSL(x,s) ((x)<<(s))
3141 # endif
3142 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3143 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3144 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3145 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3147 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3148 * little endian - the first pixel is at bit 0 - however the extra
3149 * parameter 's' can be set to cause the mask position to be swapped
3150 * within each byte, to match the PNG format. This is done by XOR of
3151 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3153 # define PIXEL_MASK(p,x,d,s) \
3154 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3156 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3158 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3159 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3161 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3162 * cases the result needs replicating, for the 4-bpp case the above
3163 * generates a full 32 bits.
3165 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3167 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3168 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3169 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3171 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3172 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3173 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3175 #if PNG_USE_COMPILE_TIME_MASKS
3176 /* Utility macros to construct all the masks for a depth/swap
3177 * combination. The 's' parameter says whether the format is PNG
3178 * (big endian bytes) or not. Only the three odd-numbered passes are
3179 * required for the display/block algorithm.
3181 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3182 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3184 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3186 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3188 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3189 * then pass:
3191 static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3193 /* Little-endian byte masks for PACKSWAP */
3194 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3195 /* Normal (big-endian byte) masks - PNG format */
3196 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3199 /* display_mask has only three entries for the odd passes, so index by
3200 * pass>>1.
3202 static PNG_CONST png_uint_32 display_mask[2][3][3] =
3204 /* Little-endian byte masks for PACKSWAP */
3205 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3206 /* Normal (big-endian byte) masks - PNG format */
3207 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3210 # define MASK(pass,depth,display,png)\
3211 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3212 row_mask[png][DEPTH_INDEX(depth)][pass])
3214 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3215 /* This is the runtime alternative: it seems unlikely that this will
3216 * ever be either smaller or faster than the compile time approach.
3218 # define MASK(pass,depth,display,png)\
3219 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3220 #endif /* !USE_COMPILE_TIME_MASKS */
3222 /* Use the appropriate mask to copy the required bits. In some cases
3223 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3224 * the number of pixels, but the code copies bytes, so it is necessary
3225 * to special case the end.
3227 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3228 png_uint_32 mask;
3230 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3231 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3232 mask = MASK(pass, pixel_depth, display, 0);
3234 else
3235 # endif
3236 mask = MASK(pass, pixel_depth, display, 1);
3238 for (;;)
3240 png_uint_32 m;
3242 /* It doesn't matter in the following if png_uint_32 has more than
3243 * 32 bits because the high bits always match those in m<<24; it is,
3244 * however, essential to use OR here, not +, because of this.
3246 m = mask;
3247 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3248 m &= 0xff;
3250 if (m != 0) /* something to copy */
3252 if (m != 0xff)
3253 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3254 else
3255 *dp = *sp;
3258 /* NOTE: this may overwrite the last byte with garbage if the image
3259 * is not an exact number of bytes wide; libpng has always done
3260 * this.
3262 if (row_width <= pixels_per_byte)
3263 break; /* May need to restore part of the last byte */
3265 row_width -= pixels_per_byte;
3266 ++dp;
3267 ++sp;
3271 else /* pixel_depth >= 8 */
3273 unsigned int bytes_to_copy, bytes_to_jump;
3275 /* Validate the depth - it must be a multiple of 8 */
3276 if (pixel_depth & 7)
3277 png_error(png_ptr, "invalid user transform pixel depth");
3279 pixel_depth >>= 3; /* now in bytes */
3280 row_width *= pixel_depth;
3282 /* Regardless of pass number the Adam 7 interlace always results in a
3283 * fixed number of pixels to copy then to skip. There may be a
3284 * different number of pixels to skip at the start though.
3287 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3289 row_width -= offset;
3290 dp += offset;
3291 sp += offset;
3294 /* Work out the bytes to copy. */
3295 if (display != 0)
3297 /* When doing the 'block' algorithm the pixel in the pass gets
3298 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3299 * passes are skipped above - the entire expanded row is copied.
3301 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3303 /* But don't allow this number to exceed the actual row width. */
3304 if (bytes_to_copy > row_width)
3305 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3308 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3309 bytes_to_copy = pixel_depth;
3311 /* In Adam7 there is a constant offset between where the pixels go. */
3312 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3314 /* And simply copy these bytes. Some optimization is possible here,
3315 * depending on the value of 'bytes_to_copy'. Special case the low
3316 * byte counts, which we know to be frequent.
3318 * Notice that these cases all 'return' rather than 'break' - this
3319 * avoids an unnecessary test on whether to restore the last byte
3320 * below.
3322 switch (bytes_to_copy)
3324 case 1:
3325 for (;;)
3327 *dp = *sp;
3329 if (row_width <= bytes_to_jump)
3330 return;
3332 dp += bytes_to_jump;
3333 sp += bytes_to_jump;
3334 row_width -= bytes_to_jump;
3337 case 2:
3338 /* There is a possibility of a partial copy at the end here; this
3339 * slows the code down somewhat.
3343 dp[0] = sp[0], dp[1] = sp[1];
3345 if (row_width <= bytes_to_jump)
3346 return;
3348 sp += bytes_to_jump;
3349 dp += bytes_to_jump;
3350 row_width -= bytes_to_jump;
3352 while (row_width > 1);
3354 /* And there can only be one byte left at this point: */
3355 *dp = *sp;
3356 return;
3358 case 3:
3359 /* This can only be the RGB case, so each copy is exactly one
3360 * pixel and it is not necessary to check for a partial copy.
3362 for (;;)
3364 dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
3366 if (row_width <= bytes_to_jump)
3367 return;
3369 sp += bytes_to_jump;
3370 dp += bytes_to_jump;
3371 row_width -= bytes_to_jump;
3374 default:
3375 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3376 /* Check for double byte alignment and, if possible, use a
3377 * 16-bit copy. Don't attempt this for narrow images - ones that
3378 * are less than an interlace panel wide. Don't attempt it for
3379 * wide bytes_to_copy either - use the memcpy there.
3381 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3382 png_isaligned(dp, png_uint_16) &&
3383 png_isaligned(sp, png_uint_16) &&
3384 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3385 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3387 /* Everything is aligned for png_uint_16 copies, but try for
3388 * png_uint_32 first.
3390 if (png_isaligned(dp, png_uint_32) != 0 &&
3391 png_isaligned(sp, png_uint_32) != 0 &&
3392 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3393 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3395 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3396 png_const_uint_32p sp32 = png_aligncastconst(
3397 png_const_uint_32p, sp);
3398 size_t skip = (bytes_to_jump-bytes_to_copy) /
3399 (sizeof (png_uint_32));
3403 size_t c = bytes_to_copy;
3406 *dp32++ = *sp32++;
3407 c -= (sizeof (png_uint_32));
3409 while (c > 0);
3411 if (row_width <= bytes_to_jump)
3412 return;
3414 dp32 += skip;
3415 sp32 += skip;
3416 row_width -= bytes_to_jump;
3418 while (bytes_to_copy <= row_width);
3420 /* Get to here when the row_width truncates the final copy.
3421 * There will be 1-3 bytes left to copy, so don't try the
3422 * 16-bit loop below.
3424 dp = (png_bytep)dp32;
3425 sp = (png_const_bytep)sp32;
3427 *dp++ = *sp++;
3428 while (--row_width > 0);
3429 return;
3432 /* Else do it in 16-bit quantities, but only if the size is
3433 * not too large.
3435 else
3437 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3438 png_const_uint_16p sp16 = png_aligncastconst(
3439 png_const_uint_16p, sp);
3440 size_t skip = (bytes_to_jump-bytes_to_copy) /
3441 (sizeof (png_uint_16));
3445 size_t c = bytes_to_copy;
3448 *dp16++ = *sp16++;
3449 c -= (sizeof (png_uint_16));
3451 while (c > 0);
3453 if (row_width <= bytes_to_jump)
3454 return;
3456 dp16 += skip;
3457 sp16 += skip;
3458 row_width -= bytes_to_jump;
3460 while (bytes_to_copy <= row_width);
3462 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3463 dp = (png_bytep)dp16;
3464 sp = (png_const_bytep)sp16;
3466 *dp++ = *sp++;
3467 while (--row_width > 0);
3468 return;
3471 #endif /* ALIGN_TYPE code */
3473 /* The true default - use a memcpy: */
3474 for (;;)
3476 memcpy(dp, sp, bytes_to_copy);
3478 if (row_width <= bytes_to_jump)
3479 return;
3481 sp += bytes_to_jump;
3482 dp += bytes_to_jump;
3483 row_width -= bytes_to_jump;
3484 if (bytes_to_copy > row_width)
3485 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3489 /* NOT REACHED*/
3490 } /* pixel_depth >= 8 */
3492 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3494 else
3495 #endif /* READ_INTERLACING */
3497 /* If here then the switch above wasn't used so just memcpy the whole row
3498 * from the temporary row buffer (notice that this overwrites the end of the
3499 * destination row if it is a partial byte.)
3501 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3503 /* Restore the overwritten bits from the last byte if necessary. */
3504 if (end_ptr != NULL)
3505 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3508 #ifdef PNG_READ_INTERLACING_SUPPORTED
3509 void /* PRIVATE */
3510 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3511 png_uint_32 transformations /* Because these may affect the byte layout */)
3513 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3514 /* Offset to next interlace block */
3515 static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3517 png_debug(1, "in png_do_read_interlace");
3518 if (row != NULL && row_info != NULL)
3520 png_uint_32 final_width;
3522 final_width = row_info->width * png_pass_inc[pass];
3524 switch (row_info->pixel_depth)
3526 case 1:
3528 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
3529 png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
3530 int sshift, dshift;
3531 int s_start, s_end, s_inc;
3532 int jstop = png_pass_inc[pass];
3533 png_byte v;
3534 png_uint_32 i;
3535 int j;
3537 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3538 if ((transformations & PNG_PACKSWAP) != 0)
3540 sshift = (int)((row_info->width + 7) & 0x07);
3541 dshift = (int)((final_width + 7) & 0x07);
3542 s_start = 7;
3543 s_end = 0;
3544 s_inc = -1;
3547 else
3548 #endif
3550 sshift = 7 - (int)((row_info->width + 7) & 0x07);
3551 dshift = 7 - (int)((final_width + 7) & 0x07);
3552 s_start = 0;
3553 s_end = 7;
3554 s_inc = 1;
3557 for (i = 0; i < row_info->width; i++)
3559 v = (png_byte)((*sp >> sshift) & 0x01);
3560 for (j = 0; j < jstop; j++)
3562 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3563 tmp |= v << dshift;
3564 *dp = (png_byte)(tmp & 0xff);
3566 if (dshift == s_end)
3568 dshift = s_start;
3569 dp--;
3572 else
3573 dshift += s_inc;
3576 if (sshift == s_end)
3578 sshift = s_start;
3579 sp--;
3582 else
3583 sshift += s_inc;
3585 break;
3588 case 2:
3590 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3591 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3592 int sshift, dshift;
3593 int s_start, s_end, s_inc;
3594 int jstop = png_pass_inc[pass];
3595 png_uint_32 i;
3597 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3598 if ((transformations & PNG_PACKSWAP) != 0)
3600 sshift = (int)(((row_info->width + 3) & 0x03) << 1);
3601 dshift = (int)(((final_width + 3) & 0x03) << 1);
3602 s_start = 6;
3603 s_end = 0;
3604 s_inc = -2;
3607 else
3608 #endif
3610 sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
3611 dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
3612 s_start = 0;
3613 s_end = 6;
3614 s_inc = 2;
3617 for (i = 0; i < row_info->width; i++)
3619 png_byte v;
3620 int j;
3622 v = (png_byte)((*sp >> sshift) & 0x03);
3623 for (j = 0; j < jstop; j++)
3625 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3626 tmp |= v << dshift;
3627 *dp = (png_byte)(tmp & 0xff);
3629 if (dshift == s_end)
3631 dshift = s_start;
3632 dp--;
3635 else
3636 dshift += s_inc;
3639 if (sshift == s_end)
3641 sshift = s_start;
3642 sp--;
3645 else
3646 sshift += s_inc;
3648 break;
3651 case 4:
3653 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
3654 png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
3655 int sshift, dshift;
3656 int s_start, s_end, s_inc;
3657 png_uint_32 i;
3658 int jstop = png_pass_inc[pass];
3660 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3661 if ((transformations & PNG_PACKSWAP) != 0)
3663 sshift = (int)(((row_info->width + 1) & 0x01) << 2);
3664 dshift = (int)(((final_width + 1) & 0x01) << 2);
3665 s_start = 4;
3666 s_end = 0;
3667 s_inc = -4;
3670 else
3671 #endif
3673 sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
3674 dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
3675 s_start = 0;
3676 s_end = 4;
3677 s_inc = 4;
3680 for (i = 0; i < row_info->width; i++)
3682 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
3683 int j;
3685 for (j = 0; j < jstop; j++)
3687 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
3688 tmp |= v << dshift;
3689 *dp = (png_byte)(tmp & 0xff);
3691 if (dshift == s_end)
3693 dshift = s_start;
3694 dp--;
3697 else
3698 dshift += s_inc;
3701 if (sshift == s_end)
3703 sshift = s_start;
3704 sp--;
3707 else
3708 sshift += s_inc;
3710 break;
3713 default:
3715 png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
3717 png_bytep sp = row + (png_size_t)(row_info->width - 1)
3718 * pixel_bytes;
3720 png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
3722 int jstop = png_pass_inc[pass];
3723 png_uint_32 i;
3725 for (i = 0; i < row_info->width; i++)
3727 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
3728 int j;
3730 memcpy(v, sp, pixel_bytes);
3732 for (j = 0; j < jstop; j++)
3734 memcpy(dp, v, pixel_bytes);
3735 dp -= pixel_bytes;
3738 sp -= pixel_bytes;
3740 break;
3744 row_info->width = final_width;
3745 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
3747 #ifndef PNG_READ_PACKSWAP_SUPPORTED
3748 PNG_UNUSED(transformations) /* Silence compiler warning */
3749 #endif
3751 #endif /* READ_INTERLACING */
3753 static void
3754 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
3755 png_const_bytep prev_row)
3757 png_size_t i;
3758 png_size_t istop = row_info->rowbytes;
3759 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3760 png_bytep rp = row + bpp;
3762 PNG_UNUSED(prev_row)
3764 for (i = bpp; i < istop; i++)
3766 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
3767 rp++;
3771 static void
3772 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
3773 png_const_bytep prev_row)
3775 png_size_t i;
3776 png_size_t istop = row_info->rowbytes;
3777 png_bytep rp = row;
3778 png_const_bytep pp = prev_row;
3780 for (i = 0; i < istop; i++)
3782 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
3783 rp++;
3787 static void
3788 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
3789 png_const_bytep prev_row)
3791 png_size_t i;
3792 png_bytep rp = row;
3793 png_const_bytep pp = prev_row;
3794 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3795 png_size_t istop = row_info->rowbytes - bpp;
3797 for (i = 0; i < bpp; i++)
3799 *rp = (png_byte)(((int)(*rp) +
3800 ((int)(*pp++) / 2 )) & 0xff);
3802 rp++;
3805 for (i = 0; i < istop; i++)
3807 *rp = (png_byte)(((int)(*rp) +
3808 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
3810 rp++;
3814 static void
3815 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
3816 png_const_bytep prev_row)
3818 png_bytep rp_end = row + row_info->rowbytes;
3819 int a, c;
3821 /* First pixel/byte */
3822 c = *prev_row++;
3823 a = *row + c;
3824 *row++ = (png_byte)a;
3826 /* Remainder */
3827 while (row < rp_end)
3829 int b, pa, pb, pc, p;
3831 a &= 0xff; /* From previous iteration or start */
3832 b = *prev_row++;
3834 p = b - c;
3835 pc = a - c;
3837 #ifdef PNG_USE_ABS
3838 pa = abs(p);
3839 pb = abs(pc);
3840 pc = abs(p + pc);
3841 #else
3842 pa = p < 0 ? -p : p;
3843 pb = pc < 0 ? -pc : pc;
3844 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3845 #endif
3847 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
3848 * ones in the case of a tie.
3850 if (pb < pa) pa = pb, a = b;
3851 if (pc < pa) a = c;
3853 /* Calculate the current pixel in a, and move the previous row pixel to c
3854 * for the next time round the loop
3856 c = b;
3857 a += *row;
3858 *row++ = (png_byte)a;
3862 static void
3863 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
3864 png_const_bytep prev_row)
3866 int bpp = (row_info->pixel_depth + 7) >> 3;
3867 png_bytep rp_end = row + bpp;
3869 /* Process the first pixel in the row completely (this is the same as 'up'
3870 * because there is only one candidate predictor for the first row).
3872 while (row < rp_end)
3874 int a = *row + *prev_row++;
3875 *row++ = (png_byte)a;
3878 /* Remainder */
3879 rp_end += row_info->rowbytes - bpp;
3881 while (row < rp_end)
3883 int a, b, c, pa, pb, pc, p;
3885 c = *(prev_row - bpp);
3886 a = *(row - bpp);
3887 b = *prev_row++;
3889 p = b - c;
3890 pc = a - c;
3892 #ifdef PNG_USE_ABS
3893 pa = abs(p);
3894 pb = abs(pc);
3895 pc = abs(p + pc);
3896 #else
3897 pa = p < 0 ? -p : p;
3898 pb = pc < 0 ? -pc : pc;
3899 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3900 #endif
3902 if (pb < pa) pa = pb, a = b;
3903 if (pc < pa) a = c;
3905 a += *row;
3906 *row++ = (png_byte)a;
3910 static void
3911 png_init_filter_functions(png_structrp pp)
3912 /* This function is called once for every PNG image (except for PNG images
3913 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
3914 * implementations required to reverse the filtering of PNG rows. Reversing
3915 * the filter is the first transformation performed on the row data. It is
3916 * performed in place, therefore an implementation can be selected based on
3917 * the image pixel format. If the implementation depends on image width then
3918 * take care to ensure that it works correctly if the image is interlaced -
3919 * interlacing causes the actual row width to vary.
3922 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
3924 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
3925 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
3926 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
3927 if (bpp == 1)
3928 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3929 png_read_filter_row_paeth_1byte_pixel;
3930 else
3931 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3932 png_read_filter_row_paeth_multibyte_pixel;
3934 #ifdef PNG_FILTER_OPTIMIZATIONS
3935 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
3936 * call to install hardware optimizations for the above functions; simply
3937 * replace whatever elements of the pp->read_filter[] array with a hardware
3938 * specific (or, for that matter, generic) optimization.
3940 * To see an example of this examine what configure.ac does when
3941 * --enable-arm-neon is specified on the command line.
3943 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
3944 #endif
3947 void /* PRIVATE */
3948 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
3949 png_const_bytep prev_row, int filter)
3951 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
3952 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
3953 * implementations. See png_init_filter_functions above.
3955 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
3957 if (pp->read_filter[0] == NULL)
3958 png_init_filter_functions(pp);
3960 pp->read_filter[filter-1](row_info, row, prev_row);
3964 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
3965 void /* PRIVATE */
3966 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
3967 png_alloc_size_t avail_out)
3969 /* Loop reading IDATs and decompressing the result into output[avail_out] */
3970 png_ptr->zstream.next_out = output;
3971 png_ptr->zstream.avail_out = 0; /* safety: set below */
3973 if (output == NULL)
3974 avail_out = 0;
3978 int ret;
3979 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
3981 if (png_ptr->zstream.avail_in == 0)
3983 uInt avail_in;
3984 png_bytep buffer;
3986 while (png_ptr->idat_size == 0)
3988 png_crc_finish(png_ptr, 0);
3990 png_ptr->idat_size = png_read_chunk_header(png_ptr);
3991 /* This is an error even in the 'check' case because the code just
3992 * consumed a non-IDAT header.
3994 if (png_ptr->chunk_name != png_IDAT)
3995 png_error(png_ptr, "Not enough image data");
3998 avail_in = png_ptr->IDAT_read_size;
4000 if (avail_in > png_ptr->idat_size)
4001 avail_in = (uInt)png_ptr->idat_size;
4003 /* A PNG with a gradually increasing IDAT size will defeat this attempt
4004 * to minimize memory usage by causing lots of re-allocs, but
4005 * realistically doing IDAT_read_size re-allocs is not likely to be a
4006 * big problem.
4008 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
4010 png_crc_read(png_ptr, buffer, avail_in);
4011 png_ptr->idat_size -= avail_in;
4013 png_ptr->zstream.next_in = buffer;
4014 png_ptr->zstream.avail_in = avail_in;
4017 /* And set up the output side. */
4018 if (output != NULL) /* standard read */
4020 uInt out = ZLIB_IO_MAX;
4022 if (out > avail_out)
4023 out = (uInt)avail_out;
4025 avail_out -= out;
4026 png_ptr->zstream.avail_out = out;
4029 else /* after last row, checking for end */
4031 png_ptr->zstream.next_out = tmpbuf;
4032 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4035 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4036 * process. If the LZ stream is truncated the sequential reader will
4037 * terminally damage the stream, above, by reading the chunk header of the
4038 * following chunk (it then exits with png_error).
4040 * TODO: deal more elegantly with truncated IDAT lists.
4042 ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
4044 /* Take the unconsumed output back. */
4045 if (output != NULL)
4046 avail_out += png_ptr->zstream.avail_out;
4048 else /* avail_out counts the extra bytes */
4049 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4051 png_ptr->zstream.avail_out = 0;
4053 if (ret == Z_STREAM_END)
4055 /* Do this for safety; we won't read any more into this row. */
4056 png_ptr->zstream.next_out = NULL;
4058 png_ptr->mode |= PNG_AFTER_IDAT;
4059 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4061 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4062 png_chunk_benign_error(png_ptr, "Extra compressed data");
4063 break;
4066 if (ret != Z_OK)
4068 png_zstream_error(png_ptr, ret);
4070 if (output != NULL)
4071 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4073 else /* checking */
4075 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4076 return;
4079 } while (avail_out > 0);
4081 if (avail_out > 0)
4083 /* The stream ended before the image; this is the same as too few IDATs so
4084 * should be handled the same way.
4086 if (output != NULL)
4087 png_error(png_ptr, "Not enough image data");
4089 else /* the deflate stream contained extra data */
4090 png_chunk_benign_error(png_ptr, "Too much image data");
4094 void /* PRIVATE */
4095 png_read_finish_IDAT(png_structrp png_ptr)
4097 /* We don't need any more data and the stream should have ended, however the
4098 * LZ end code may actually not have been processed. In this case we must
4099 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4100 * may still remain to be consumed.
4102 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4104 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4105 * the compressed stream, but the stream may be damaged too, so even after
4106 * this call we may need to terminate the zstream ownership.
4108 png_read_IDAT_data(png_ptr, NULL, 0);
4109 png_ptr->zstream.next_out = NULL; /* safety */
4111 /* Now clear everything out for safety; the following may not have been
4112 * done.
4114 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4116 png_ptr->mode |= PNG_AFTER_IDAT;
4117 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4121 /* If the zstream has not been released do it now *and* terminate the reading
4122 * of the final IDAT chunk.
4124 if (png_ptr->zowner == png_IDAT)
4126 /* Always do this; the pointers otherwise point into the read buffer. */
4127 png_ptr->zstream.next_in = NULL;
4128 png_ptr->zstream.avail_in = 0;
4130 /* Now we no longer own the zstream. */
4131 png_ptr->zowner = 0;
4133 /* The slightly weird semantics of the sequential IDAT reading is that we
4134 * are always in or at the end of an IDAT chunk, so we always need to do a
4135 * crc_finish here. If idat_size is non-zero we also need to read the
4136 * spurious bytes at the end of the chunk now.
4138 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4142 void /* PRIVATE */
4143 png_read_finish_row(png_structrp png_ptr)
4145 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4147 /* Start of interlace block */
4148 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4150 /* Offset to next interlace block */
4151 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4153 /* Start of interlace block in the y direction */
4154 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4156 /* Offset to next interlace block in the y direction */
4157 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4159 png_debug(1, "in png_read_finish_row");
4160 png_ptr->row_number++;
4161 if (png_ptr->row_number < png_ptr->num_rows)
4162 return;
4164 if (png_ptr->interlaced != 0)
4166 png_ptr->row_number = 0;
4168 /* TO DO: don't do this if prev_row isn't needed (requires
4169 * read-ahead of the next row's filter byte.
4171 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4175 png_ptr->pass++;
4177 if (png_ptr->pass >= 7)
4178 break;
4180 png_ptr->iwidth = (png_ptr->width +
4181 png_pass_inc[png_ptr->pass] - 1 -
4182 png_pass_start[png_ptr->pass]) /
4183 png_pass_inc[png_ptr->pass];
4185 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4187 png_ptr->num_rows = (png_ptr->height +
4188 png_pass_yinc[png_ptr->pass] - 1 -
4189 png_pass_ystart[png_ptr->pass]) /
4190 png_pass_yinc[png_ptr->pass];
4193 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4194 break; /* libpng deinterlacing sees every row */
4196 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4198 if (png_ptr->pass < 7)
4199 return;
4202 /* Here after at the end of the last row of the last pass. */
4203 png_read_finish_IDAT(png_ptr);
4205 #endif /* SEQUENTIAL_READ */
4207 void /* PRIVATE */
4208 png_read_start_row(png_structrp png_ptr)
4210 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4212 /* Start of interlace block */
4213 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4215 /* Offset to next interlace block */
4216 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4218 /* Start of interlace block in the y direction */
4219 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4221 /* Offset to next interlace block in the y direction */
4222 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4224 int max_pixel_depth;
4225 png_size_t row_bytes;
4227 png_debug(1, "in png_read_start_row");
4229 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4230 png_init_read_transformations(png_ptr);
4231 #endif
4232 if (png_ptr->interlaced != 0)
4234 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4235 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4236 png_pass_ystart[0]) / png_pass_yinc[0];
4238 else
4239 png_ptr->num_rows = png_ptr->height;
4241 png_ptr->iwidth = (png_ptr->width +
4242 png_pass_inc[png_ptr->pass] - 1 -
4243 png_pass_start[png_ptr->pass]) /
4244 png_pass_inc[png_ptr->pass];
4247 else
4249 png_ptr->num_rows = png_ptr->height;
4250 png_ptr->iwidth = png_ptr->width;
4253 max_pixel_depth = png_ptr->pixel_depth;
4255 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4256 * calculations to calculate the final pixel depth, then
4257 * png_do_read_transforms actually does the transforms. This means that the
4258 * code which effectively calculates this value is actually repeated in three
4259 * separate places. They must all match. Innocent changes to the order of
4260 * transformations can and will break libpng in a way that causes memory
4261 * overwrites.
4263 * TODO: fix this.
4265 #ifdef PNG_READ_PACK_SUPPORTED
4266 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4267 max_pixel_depth = 8;
4268 #endif
4270 #ifdef PNG_READ_EXPAND_SUPPORTED
4271 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4273 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4275 if (png_ptr->num_trans != 0)
4276 max_pixel_depth = 32;
4278 else
4279 max_pixel_depth = 24;
4282 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4284 if (max_pixel_depth < 8)
4285 max_pixel_depth = 8;
4287 if (png_ptr->num_trans != 0)
4288 max_pixel_depth *= 2;
4291 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4293 if (png_ptr->num_trans != 0)
4295 max_pixel_depth *= 4;
4296 max_pixel_depth /= 3;
4300 #endif
4302 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4303 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4305 # ifdef PNG_READ_EXPAND_SUPPORTED
4306 /* In fact it is an error if it isn't supported, but checking is
4307 * the safe way.
4309 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4311 if (png_ptr->bit_depth < 16)
4312 max_pixel_depth *= 2;
4314 else
4315 # endif
4316 png_ptr->transformations &= ~PNG_EXPAND_16;
4318 #endif
4320 #ifdef PNG_READ_FILLER_SUPPORTED
4321 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4323 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4325 if (max_pixel_depth <= 8)
4326 max_pixel_depth = 16;
4328 else
4329 max_pixel_depth = 32;
4332 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4333 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4335 if (max_pixel_depth <= 32)
4336 max_pixel_depth = 32;
4338 else
4339 max_pixel_depth = 64;
4342 #endif
4344 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4345 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4347 if (
4348 #ifdef PNG_READ_EXPAND_SUPPORTED
4349 (png_ptr->num_trans != 0 &&
4350 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4351 #endif
4352 #ifdef PNG_READ_FILLER_SUPPORTED
4353 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4354 #endif
4355 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4357 if (max_pixel_depth <= 16)
4358 max_pixel_depth = 32;
4360 else
4361 max_pixel_depth = 64;
4364 else
4366 if (max_pixel_depth <= 8)
4368 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4369 max_pixel_depth = 32;
4371 else
4372 max_pixel_depth = 24;
4375 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4376 max_pixel_depth = 64;
4378 else
4379 max_pixel_depth = 48;
4382 #endif
4384 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4385 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4386 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4388 int user_pixel_depth = png_ptr->user_transform_depth *
4389 png_ptr->user_transform_channels;
4391 if (user_pixel_depth > max_pixel_depth)
4392 max_pixel_depth = user_pixel_depth;
4394 #endif
4396 /* This value is stored in png_struct and double checked in the row read
4397 * code.
4399 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4400 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4402 /* Align the width on the next larger 8 pixels. Mainly used
4403 * for interlacing
4405 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4406 /* Calculate the maximum bytes needed, adding a byte and a pixel
4407 * for safety's sake
4409 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4410 1 + ((max_pixel_depth + 7) >> 3);
4412 #ifdef PNG_MAX_MALLOC_64K
4413 if (row_bytes > (png_uint_32)65536L)
4414 png_error(png_ptr, "This image requires a row greater than 64KB");
4415 #endif
4417 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4419 png_free(png_ptr, png_ptr->big_row_buf);
4420 png_free(png_ptr, png_ptr->big_prev_row);
4422 if (png_ptr->interlaced != 0)
4423 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4424 row_bytes + 48);
4426 else
4427 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4429 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4431 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4432 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4433 * of padding before and after row_buf; treat prev_row similarly.
4434 * NOTE: the alignment is to the start of the pixels, one beyond the start
4435 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4436 * was incorrect; the filter byte was aligned, which had the exact
4437 * opposite effect of that intended.
4440 png_bytep temp = png_ptr->big_row_buf + 32;
4441 int extra = (int)((temp - (png_bytep)0) & 0x0f);
4442 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4444 temp = png_ptr->big_prev_row + 32;
4445 extra = (int)((temp - (png_bytep)0) & 0x0f);
4446 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4449 #else
4450 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4451 png_ptr->row_buf = png_ptr->big_row_buf + 31;
4452 png_ptr->prev_row = png_ptr->big_prev_row + 31;
4453 #endif
4454 png_ptr->old_big_row_buf_size = row_bytes + 48;
4457 #ifdef PNG_MAX_MALLOC_64K
4458 if (png_ptr->rowbytes > 65535)
4459 png_error(png_ptr, "This image requires a row greater than 64KB");
4461 #endif
4462 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4463 png_error(png_ptr, "Row has too many bytes to allocate in memory");
4465 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4467 png_debug1(3, "width = %u,", png_ptr->width);
4468 png_debug1(3, "height = %u,", png_ptr->height);
4469 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4470 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4471 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4472 png_debug1(3, "irowbytes = %lu",
4473 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4475 /* The sequential reader needs a buffer for IDAT, but the progressive reader
4476 * does not, so free the read buffer now regardless; the sequential reader
4477 * reallocates it on demand.
4479 if (png_ptr->read_buffer != 0)
4481 png_bytep buffer = png_ptr->read_buffer;
4483 png_ptr->read_buffer_size = 0;
4484 png_ptr->read_buffer = NULL;
4485 png_free(png_ptr, buffer);
4488 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4489 * value from the stream (note that this will result in a fatal error if the
4490 * IDAT stream has a bogus deflate header window_bits value, but this should
4491 * not be happening any longer!)
4493 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4494 png_error(png_ptr, png_ptr->zstream.msg);
4496 png_ptr->flags |= PNG_FLAG_ROW_INIT;
4498 #endif /* READ */