sync with TL rev. 36644 (trunk)
[luatex.git] / source / libs / libpng / libpng-1.6.17 / pngrutil.c
blob6c5c37526bc5bc8608fdd62c44922189e4be1298
2 /* pngrutil.c - utilities to read a PNG file
4 * Last changed in libpng 1.6.17 [March 26, 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 return -(png_int_32)uval;
95 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
96 png_uint_16 (PNGAPI
97 png_get_uint_16)(png_const_bytep buf)
99 /* ANSI-C requires an int value to accomodate at least 16 bits so this
100 * works and allows the compiler not to worry about possible narrowing
101 * on 32 bit systems. (Pre-ANSI systems did not make integers smaller
102 * than 16 bits either.)
104 unsigned int val =
105 ((unsigned int)(*buf) << 8) +
106 ((unsigned int)(*(buf + 1)));
108 return (png_uint_16)val;
111 #endif /* READ_INT_FUNCTIONS */
113 /* Read and check the PNG file signature */
114 void /* PRIVATE */
115 png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
117 png_size_t num_checked, num_to_check;
119 /* Exit if the user application does not expect a signature. */
120 if (png_ptr->sig_bytes >= 8)
121 return;
123 num_checked = png_ptr->sig_bytes;
124 num_to_check = 8 - num_checked;
126 #ifdef PNG_IO_STATE_SUPPORTED
127 png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
128 #endif
130 /* The signature must be serialized in a single I/O call. */
131 png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
132 png_ptr->sig_bytes = 8;
134 if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
136 if (num_checked < 4 &&
137 png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
138 png_error(png_ptr, "Not a PNG file");
139 else
140 png_error(png_ptr, "PNG file corrupted by ASCII conversion");
142 if (num_checked < 3)
143 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
146 /* Read the chunk header (length + type name).
147 * Put the type name into png_ptr->chunk_name, and return the length.
149 png_uint_32 /* PRIVATE */
150 png_read_chunk_header(png_structrp png_ptr)
152 png_byte buf[8];
153 png_uint_32 length;
155 #ifdef PNG_IO_STATE_SUPPORTED
156 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
157 #endif
159 /* Read the length and the chunk name.
160 * This must be performed in a single I/O call.
162 png_read_data(png_ptr, buf, 8);
163 length = png_get_uint_31(png_ptr, buf);
165 /* Put the chunk name into png_ptr->chunk_name. */
166 png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
168 png_debug2(0, "Reading %lx chunk, length = %lu",
169 (unsigned long)png_ptr->chunk_name, (unsigned long)length);
171 /* Reset the crc and run it over the chunk name. */
172 png_reset_crc(png_ptr);
173 png_calculate_crc(png_ptr, buf + 4, 4);
175 /* Check to see if chunk name is valid. */
176 png_check_chunk_name(png_ptr, png_ptr->chunk_name);
178 #ifdef PNG_IO_STATE_SUPPORTED
179 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
180 #endif
182 return length;
185 /* Read data, and (optionally) run it through the CRC. */
186 void /* PRIVATE */
187 png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
189 if (png_ptr == NULL)
190 return;
192 png_read_data(png_ptr, buf, length);
193 png_calculate_crc(png_ptr, buf, length);
196 /* Optionally skip data and then check the CRC. Depending on whether we
197 * are reading an ancillary or critical chunk, and how the program has set
198 * things up, we may calculate the CRC on the data and print a message.
199 * Returns '1' if there was a CRC error, '0' otherwise.
201 int /* PRIVATE */
202 png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
204 /* The size of the local buffer for inflate is a good guess as to a
205 * reasonable size to use for buffering reads from the application.
207 while (skip > 0)
209 png_uint_32 len;
210 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
212 len = (sizeof tmpbuf);
213 if (len > skip)
214 len = skip;
215 skip -= len;
217 png_crc_read(png_ptr, tmpbuf, len);
220 if (png_crc_error(png_ptr) != 0)
222 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
223 (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
224 (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
226 png_chunk_warning(png_ptr, "CRC error");
229 else
230 png_chunk_error(png_ptr, "CRC error");
232 return (1);
235 return (0);
238 /* Compare the CRC stored in the PNG file with that calculated by libpng from
239 * the data it has read thus far.
241 int /* PRIVATE */
242 png_crc_error(png_structrp png_ptr)
244 png_byte crc_bytes[4];
245 png_uint_32 crc;
246 int need_crc = 1;
248 if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
250 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
251 (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
252 need_crc = 0;
255 else /* critical */
257 if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
258 need_crc = 0;
261 #ifdef PNG_IO_STATE_SUPPORTED
262 png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
263 #endif
265 /* The chunk CRC must be serialized in a single I/O call. */
266 png_read_data(png_ptr, crc_bytes, 4);
268 if (need_crc != 0)
270 crc = png_get_uint_32(crc_bytes);
271 return ((int)(crc != png_ptr->crc));
274 else
275 return (0);
278 #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
279 defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
280 defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
281 defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED)
282 /* Manage the read buffer; this simply reallocates the buffer if it is not small
283 * enough (or if it is not allocated). The routine returns a pointer to the
284 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
285 * it will call png_error (via png_malloc) on failure. (warn == 2 means
286 * 'silent').
288 static png_bytep
289 png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn)
291 png_bytep buffer = png_ptr->read_buffer;
293 if (buffer != NULL && new_size > png_ptr->read_buffer_size)
295 png_ptr->read_buffer = NULL;
296 png_ptr->read_buffer = NULL;
297 png_ptr->read_buffer_size = 0;
298 png_free(png_ptr, buffer);
299 buffer = NULL;
302 if (buffer == NULL)
304 buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
306 if (buffer != NULL)
308 png_ptr->read_buffer = buffer;
309 png_ptr->read_buffer_size = new_size;
312 else if (warn < 2) /* else silent */
314 if (warn != 0)
315 png_chunk_warning(png_ptr, "insufficient memory to read chunk");
317 else
318 png_chunk_error(png_ptr, "insufficient memory to read chunk");
322 return buffer;
324 #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */
326 /* png_inflate_claim: claim the zstream for some nefarious purpose that involves
327 * decompression. Returns Z_OK on success, else a zlib error code. It checks
328 * the owner but, in final release builds, just issues a warning if some other
329 * chunk apparently owns the stream. Prior to release it does a png_error.
331 static int
332 png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
334 if (png_ptr->zowner != 0)
336 char msg[64];
338 PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
339 /* So the message that results is "<chunk> using zstream"; this is an
340 * internal error, but is very useful for debugging. i18n requirements
341 * are minimal.
343 (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
344 #if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
345 png_chunk_warning(png_ptr, msg);
346 png_ptr->zowner = 0;
347 #else
348 png_chunk_error(png_ptr, msg);
349 #endif
352 /* Implementation note: unlike 'png_deflate_claim' this internal function
353 * does not take the size of the data as an argument. Some efficiency could
354 * be gained by using this when it is known *if* the zlib stream itself does
355 * not record the number; however, this is an illusion: the original writer
356 * of the PNG may have selected a lower window size, and we really must
357 * follow that because, for systems with with limited capabilities, we
358 * would otherwise reject the application's attempts to use a smaller window
359 * size (zlib doesn't have an interface to say "this or lower"!).
361 * inflateReset2 was added to zlib 1.2.4; before this the window could not be
362 * reset, therefore it is necessary to always allocate the maximum window
363 * size with earlier zlibs just in case later compressed chunks need it.
366 int ret; /* zlib return code */
367 #if PNG_ZLIB_VERNUM >= 0x1240
369 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
370 int window_bits;
372 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
373 PNG_OPTION_ON)
374 window_bits = 15;
376 else
377 window_bits = 0;
378 # else
379 # define window_bits 0
380 # endif
381 #endif
383 /* Set this for safety, just in case the previous owner left pointers to
384 * memory allocations.
386 png_ptr->zstream.next_in = NULL;
387 png_ptr->zstream.avail_in = 0;
388 png_ptr->zstream.next_out = NULL;
389 png_ptr->zstream.avail_out = 0;
391 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
393 #if PNG_ZLIB_VERNUM < 0x1240
394 ret = inflateReset(&png_ptr->zstream);
395 #else
396 ret = inflateReset2(&png_ptr->zstream, window_bits);
397 #endif
400 else
402 #if PNG_ZLIB_VERNUM < 0x1240
403 ret = inflateInit(&png_ptr->zstream);
404 #else
405 ret = inflateInit2(&png_ptr->zstream, window_bits);
406 #endif
408 if (ret == Z_OK)
409 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
412 if (ret == Z_OK)
413 png_ptr->zowner = owner;
415 else
416 png_zstream_error(png_ptr, ret);
418 return ret;
421 #ifdef window_bits
422 # undef window_bits
423 #endif
426 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
427 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
428 * allow the caller to do multiple calls if required. If the 'finish' flag is
429 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
430 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
431 * Z_OK or Z_STREAM_END will be returned on success.
433 * The input and output sizes are updated to the actual amounts of data consumed
434 * or written, not the amount available (as in a z_stream). The data pointers
435 * are not changed, so the next input is (data+input_size) and the next
436 * available output is (output+output_size).
438 static int
439 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
440 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
441 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
443 if (png_ptr->zowner == owner) /* Else not claimed */
445 int ret;
446 png_alloc_size_t avail_out = *output_size_ptr;
447 png_uint_32 avail_in = *input_size_ptr;
449 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
450 * can't even necessarily handle 65536 bytes) because the type uInt is
451 * "16 bits or more". Consequently it is necessary to chunk the input to
452 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
453 * maximum value that can be stored in a uInt.) It is possible to set
454 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
455 * a performance advantage, because it reduces the amount of data accessed
456 * at each step and that may give the OS more time to page it in.
458 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
459 /* avail_in and avail_out are set below from 'size' */
460 png_ptr->zstream.avail_in = 0;
461 png_ptr->zstream.avail_out = 0;
463 /* Read directly into the output if it is available (this is set to
464 * a local buffer below if output is NULL).
466 if (output != NULL)
467 png_ptr->zstream.next_out = output;
471 uInt avail;
472 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
474 /* zlib INPUT BUFFER */
475 /* The setting of 'avail_in' used to be outside the loop; by setting it
476 * inside it is possible to chunk the input to zlib and simply rely on
477 * zlib to advance the 'next_in' pointer. This allows arbitrary
478 * amounts of data to be passed through zlib at the unavoidable cost of
479 * requiring a window save (memcpy of up to 32768 output bytes)
480 * every ZLIB_IO_MAX input bytes.
482 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
484 avail = ZLIB_IO_MAX;
486 if (avail_in < avail)
487 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
489 avail_in -= avail;
490 png_ptr->zstream.avail_in = avail;
492 /* zlib OUTPUT BUFFER */
493 avail_out += png_ptr->zstream.avail_out; /* not written last time */
495 avail = ZLIB_IO_MAX; /* maximum zlib can process */
497 if (output == NULL)
499 /* Reset the output buffer each time round if output is NULL and
500 * make available the full buffer, up to 'remaining_space'
502 png_ptr->zstream.next_out = local_buffer;
503 if ((sizeof local_buffer) < avail)
504 avail = (sizeof local_buffer);
507 if (avail_out < avail)
508 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
510 png_ptr->zstream.avail_out = avail;
511 avail_out -= avail;
513 /* zlib inflate call */
514 /* In fact 'avail_out' may be 0 at this point, that happens at the end
515 * of the read when the final LZ end code was not passed at the end of
516 * the previous chunk of input data. Tell zlib if we have reached the
517 * end of the output buffer.
519 ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH :
520 (finish ? Z_FINISH : Z_SYNC_FLUSH));
521 } while (ret == Z_OK);
523 /* For safety kill the local buffer pointer now */
524 if (output == NULL)
525 png_ptr->zstream.next_out = NULL;
527 /* Claw back the 'size' and 'remaining_space' byte counts. */
528 avail_in += png_ptr->zstream.avail_in;
529 avail_out += png_ptr->zstream.avail_out;
531 /* Update the input and output sizes; the updated values are the amount
532 * consumed or written, effectively the inverse of what zlib uses.
534 if (avail_out > 0)
535 *output_size_ptr -= avail_out;
537 if (avail_in > 0)
538 *input_size_ptr -= avail_in;
540 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
541 png_zstream_error(png_ptr, ret);
542 return ret;
545 else
547 /* This is a bad internal error. The recovery assigns to the zstream msg
548 * pointer, which is not owned by the caller, but this is safe; it's only
549 * used on errors!
551 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
552 return Z_STREAM_ERROR;
557 * Decompress trailing data in a chunk. The assumption is that read_buffer
558 * points at an allocated area holding the contents of a chunk with a
559 * trailing compressed part. What we get back is an allocated area
560 * holding the original prefix part and an uncompressed version of the
561 * trailing part (the malloc area passed in is freed).
563 static int
564 png_decompress_chunk(png_structrp png_ptr,
565 png_uint_32 chunklength, png_uint_32 prefix_size,
566 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
567 int terminate /*add a '\0' to the end of the uncompressed data*/)
569 /* TODO: implement different limits for different types of chunk.
571 * The caller supplies *newlength set to the maximum length of the
572 * uncompressed data, but this routine allocates space for the prefix and
573 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
574 * limited only by the maximum chunk size.
576 png_alloc_size_t limit = PNG_SIZE_MAX;
578 # ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
579 if (png_ptr->user_chunk_malloc_max > 0 &&
580 png_ptr->user_chunk_malloc_max < limit)
581 limit = png_ptr->user_chunk_malloc_max;
582 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
583 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
584 limit = PNG_USER_CHUNK_MALLOC_MAX;
585 # endif
587 if (limit >= prefix_size + (terminate != 0))
589 int ret;
591 limit -= prefix_size + (terminate != 0);
593 if (limit < *newlength)
594 *newlength = limit;
596 /* Now try to claim the stream. */
597 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
599 if (ret == Z_OK)
601 png_uint_32 lzsize = chunklength - prefix_size;
603 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
604 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
605 /* output: */ NULL, newlength);
607 if (ret == Z_STREAM_END)
609 /* Use 'inflateReset' here, not 'inflateReset2' because this
610 * preserves the previously decided window size (otherwise it would
611 * be necessary to store the previous window size.) In practice
612 * this doesn't matter anyway, because png_inflate will call inflate
613 * with Z_FINISH in almost all cases, so the window will not be
614 * maintained.
616 if (inflateReset(&png_ptr->zstream) == Z_OK)
618 /* Because of the limit checks above we know that the new,
619 * expanded, size will fit in a size_t (let alone an
620 * png_alloc_size_t). Use png_malloc_base here to avoid an
621 * extra OOM message.
623 png_alloc_size_t new_size = *newlength;
624 png_alloc_size_t buffer_size = prefix_size + new_size +
625 (terminate != 0);
626 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
627 buffer_size));
629 if (text != NULL)
631 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
632 png_ptr->read_buffer + prefix_size, &lzsize,
633 text + prefix_size, newlength);
635 if (ret == Z_STREAM_END)
637 if (new_size == *newlength)
639 if (terminate != 0)
640 text[prefix_size + *newlength] = 0;
642 if (prefix_size > 0)
643 memcpy(text, png_ptr->read_buffer, prefix_size);
646 png_bytep old_ptr = png_ptr->read_buffer;
648 png_ptr->read_buffer = text;
649 png_ptr->read_buffer_size = buffer_size;
650 text = old_ptr; /* freed below */
654 else
656 /* The size changed on the second read, there can be no
657 * guarantee that anything is correct at this point.
658 * The 'msg' pointer has been set to "unexpected end of
659 * LZ stream", which is fine, but return an error code
660 * that the caller won't accept.
662 ret = PNG_UNEXPECTED_ZLIB_RETURN;
666 else if (ret == Z_OK)
667 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
669 /* Free the text pointer (this is the old read_buffer on
670 * success)
672 png_free(png_ptr, text);
673 text = NULL;
675 /* This really is very benign, but it's still an error because
676 * the extra space may otherwise be used as a Trojan Horse.
678 if (ret == Z_STREAM_END &&
679 chunklength - prefix_size != lzsize)
680 png_chunk_benign_error(png_ptr, "extra compressed data");
683 else
685 /* Out of memory allocating the buffer */
686 ret = Z_MEM_ERROR;
687 png_zstream_error(png_ptr, Z_MEM_ERROR);
691 else
693 /* inflateReset failed, store the error message */
694 png_zstream_error(png_ptr, ret);
696 if (ret == Z_STREAM_END)
697 ret = PNG_UNEXPECTED_ZLIB_RETURN;
701 else if (ret == Z_OK)
702 ret = PNG_UNEXPECTED_ZLIB_RETURN;
704 /* Release the claimed stream */
705 png_ptr->zowner = 0;
708 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
709 ret = PNG_UNEXPECTED_ZLIB_RETURN;
711 return ret;
714 else
716 /* Application/configuration limits exceeded */
717 png_zstream_error(png_ptr, Z_MEM_ERROR);
718 return Z_MEM_ERROR;
721 #endif /* READ_COMPRESSED_TEXT */
723 #ifdef PNG_READ_iCCP_SUPPORTED
724 /* Perform a partial read and decompress, producing 'avail_out' bytes and
725 * reading from the current chunk as required.
727 static int
728 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
729 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
730 int finish)
732 if (png_ptr->zowner == png_ptr->chunk_name)
734 int ret;
736 /* next_in and avail_in must have been initialized by the caller. */
737 png_ptr->zstream.next_out = next_out;
738 png_ptr->zstream.avail_out = 0; /* set in the loop */
742 if (png_ptr->zstream.avail_in == 0)
744 if (read_size > *chunk_bytes)
745 read_size = (uInt)*chunk_bytes;
746 *chunk_bytes -= read_size;
748 if (read_size > 0)
749 png_crc_read(png_ptr, read_buffer, read_size);
751 png_ptr->zstream.next_in = read_buffer;
752 png_ptr->zstream.avail_in = read_size;
755 if (png_ptr->zstream.avail_out == 0)
757 uInt avail = ZLIB_IO_MAX;
758 if (avail > *out_size)
759 avail = (uInt)*out_size;
760 *out_size -= avail;
762 png_ptr->zstream.avail_out = avail;
765 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
766 * the available output is produced; this allows reading of truncated
767 * streams.
769 ret = inflate(&png_ptr->zstream,
770 *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
772 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
774 *out_size += png_ptr->zstream.avail_out;
775 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
777 /* Ensure the error message pointer is always set: */
778 png_zstream_error(png_ptr, ret);
779 return ret;
782 else
784 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
785 return Z_STREAM_ERROR;
788 #endif
790 /* Read and check the IDHR chunk */
792 void /* PRIVATE */
793 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
795 png_byte buf[13];
796 png_uint_32 width, height;
797 int bit_depth, color_type, compression_type, filter_type;
798 int interlace_type;
800 png_debug(1, "in png_handle_IHDR");
802 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
803 png_chunk_error(png_ptr, "out of place");
805 /* Check the length */
806 if (length != 13)
807 png_chunk_error(png_ptr, "invalid");
809 png_ptr->mode |= PNG_HAVE_IHDR;
811 png_crc_read(png_ptr, buf, 13);
812 png_crc_finish(png_ptr, 0);
814 width = png_get_uint_31(png_ptr, buf);
815 height = png_get_uint_31(png_ptr, buf + 4);
816 bit_depth = buf[8];
817 color_type = buf[9];
818 compression_type = buf[10];
819 filter_type = buf[11];
820 interlace_type = buf[12];
822 /* Set internal variables */
823 png_ptr->width = width;
824 png_ptr->height = height;
825 png_ptr->bit_depth = (png_byte)bit_depth;
826 png_ptr->interlaced = (png_byte)interlace_type;
827 png_ptr->color_type = (png_byte)color_type;
828 #ifdef PNG_MNG_FEATURES_SUPPORTED
829 png_ptr->filter_type = (png_byte)filter_type;
830 #endif
831 png_ptr->compression_type = (png_byte)compression_type;
833 /* Find number of channels */
834 switch (png_ptr->color_type)
836 default: /* invalid, png_set_IHDR calls png_error */
837 case PNG_COLOR_TYPE_GRAY:
838 case PNG_COLOR_TYPE_PALETTE:
839 png_ptr->channels = 1;
840 break;
842 case PNG_COLOR_TYPE_RGB:
843 png_ptr->channels = 3;
844 break;
846 case PNG_COLOR_TYPE_GRAY_ALPHA:
847 png_ptr->channels = 2;
848 break;
850 case PNG_COLOR_TYPE_RGB_ALPHA:
851 png_ptr->channels = 4;
852 break;
855 /* Set up other useful info */
856 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
857 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
858 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
859 png_debug1(3, "channels = %d", png_ptr->channels);
860 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
861 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
862 color_type, interlace_type, compression_type, filter_type);
865 /* Read and check the palette */
866 void /* PRIVATE */
867 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
869 png_color palette[PNG_MAX_PALETTE_LENGTH];
870 int num, i;
871 #ifdef PNG_POINTER_INDEXING_SUPPORTED
872 png_colorp pal_ptr;
873 #endif
875 png_debug(1, "in png_handle_PLTE");
877 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
878 png_chunk_error(png_ptr, "missing IHDR");
880 /* Moved to before the 'after IDAT' check below because otherwise duplicate
881 * PLTE chunks are potentially ignored (the spec says there shall not be more
882 * than one PLTE, the error is not treated as benign, so this check trumps
883 * the requirement that PLTE appears before IDAT.)
885 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
886 png_chunk_error(png_ptr, "duplicate");
888 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
890 /* This is benign because the non-benign error happened before, when an
891 * IDAT was encountered in a color-mapped image with no PLTE.
893 png_crc_finish(png_ptr, length);
894 png_chunk_benign_error(png_ptr, "out of place");
895 return;
898 png_ptr->mode |= PNG_HAVE_PLTE;
900 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
902 png_crc_finish(png_ptr, length);
903 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
904 return;
907 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
908 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
910 png_crc_finish(png_ptr, length);
911 return;
913 #endif
915 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
917 png_crc_finish(png_ptr, length);
919 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
920 png_chunk_benign_error(png_ptr, "invalid");
922 else
923 png_chunk_error(png_ptr, "invalid");
925 return;
928 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
929 num = (int)length / 3;
931 #ifdef PNG_POINTER_INDEXING_SUPPORTED
932 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
934 png_byte buf[3];
936 png_crc_read(png_ptr, buf, 3);
937 pal_ptr->red = buf[0];
938 pal_ptr->green = buf[1];
939 pal_ptr->blue = buf[2];
941 #else
942 for (i = 0; i < num; i++)
944 png_byte buf[3];
946 png_crc_read(png_ptr, buf, 3);
947 /* Don't depend upon png_color being any order */
948 palette[i].red = buf[0];
949 palette[i].green = buf[1];
950 palette[i].blue = buf[2];
952 #endif
954 /* If we actually need the PLTE chunk (ie for a paletted image), we do
955 * whatever the normal CRC configuration tells us. However, if we
956 * have an RGB image, the PLTE can be considered ancillary, so
957 * we will act as though it is.
959 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
960 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
961 #endif
963 png_crc_finish(png_ptr, 0);
966 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
967 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
969 /* If we don't want to use the data from an ancillary chunk,
970 * we have two options: an error abort, or a warning and we
971 * ignore the data in this chunk (which should be OK, since
972 * it's considered ancillary for a RGB or RGBA image).
974 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
975 * chunk type to determine whether to check the ancillary or the critical
976 * flags.
978 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
980 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
981 return;
983 else
984 png_chunk_error(png_ptr, "CRC error");
987 /* Otherwise, we (optionally) emit a warning and use the chunk. */
988 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
989 png_chunk_warning(png_ptr, "CRC error");
991 #endif
993 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
994 * own copy of the palette. This has the side effect that when png_start_row
995 * is called (this happens after any call to png_read_update_info) the
996 * info_ptr palette gets changed. This is extremely unexpected and
997 * confusing.
999 * Fix this by not sharing the palette in this way.
1001 png_set_PLTE(png_ptr, info_ptr, palette, num);
1003 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1004 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1005 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1006 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1007 * therefore does a benign error if the erroneous condition is detected *and*
1008 * cancels the tRNS if the benign error returns. The alternative is to
1009 * amend the standard since it would be rather hypocritical of the standards
1010 * maintainers to ignore it.
1012 #ifdef PNG_READ_tRNS_SUPPORTED
1013 if (png_ptr->num_trans > 0 ||
1014 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1016 /* Cancel this because otherwise it would be used if the transforms
1017 * require it. Don't cancel the 'valid' flag because this would prevent
1018 * detection of duplicate chunks.
1020 png_ptr->num_trans = 0;
1022 if (info_ptr != NULL)
1023 info_ptr->num_trans = 0;
1025 png_chunk_benign_error(png_ptr, "tRNS must be after");
1027 #endif
1029 #ifdef PNG_READ_hIST_SUPPORTED
1030 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1031 png_chunk_benign_error(png_ptr, "hIST must be after");
1032 #endif
1034 #ifdef PNG_READ_bKGD_SUPPORTED
1035 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1036 png_chunk_benign_error(png_ptr, "bKGD must be after");
1037 #endif
1040 void /* PRIVATE */
1041 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1043 png_debug(1, "in png_handle_IEND");
1045 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1046 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1047 png_chunk_error(png_ptr, "out of place");
1049 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1051 png_crc_finish(png_ptr, length);
1053 if (length != 0)
1054 png_chunk_benign_error(png_ptr, "invalid");
1056 PNG_UNUSED(info_ptr)
1059 #ifdef PNG_READ_gAMA_SUPPORTED
1060 void /* PRIVATE */
1061 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1063 png_fixed_point igamma;
1064 png_byte buf[4];
1066 png_debug(1, "in png_handle_gAMA");
1068 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1069 png_chunk_error(png_ptr, "missing IHDR");
1071 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1073 png_crc_finish(png_ptr, length);
1074 png_chunk_benign_error(png_ptr, "out of place");
1075 return;
1078 if (length != 4)
1080 png_crc_finish(png_ptr, length);
1081 png_chunk_benign_error(png_ptr, "invalid");
1082 return;
1085 png_crc_read(png_ptr, buf, 4);
1087 if (png_crc_finish(png_ptr, 0) != 0)
1088 return;
1090 igamma = png_get_fixed_point(NULL, buf);
1092 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1093 png_colorspace_sync(png_ptr, info_ptr);
1095 #endif
1097 #ifdef PNG_READ_sBIT_SUPPORTED
1098 void /* PRIVATE */
1099 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1101 unsigned int truelen, i;
1102 png_byte sample_depth;
1103 png_byte buf[4];
1105 png_debug(1, "in png_handle_sBIT");
1107 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1108 png_chunk_error(png_ptr, "missing IHDR");
1110 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1112 png_crc_finish(png_ptr, length);
1113 png_chunk_benign_error(png_ptr, "out of place");
1114 return;
1117 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1119 png_crc_finish(png_ptr, length);
1120 png_chunk_benign_error(png_ptr, "duplicate");
1121 return;
1124 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1126 truelen = 3;
1127 sample_depth = 8;
1130 else
1132 truelen = png_ptr->channels;
1133 sample_depth = png_ptr->bit_depth;
1136 if (length != truelen || length > 4)
1138 png_chunk_benign_error(png_ptr, "invalid");
1139 png_crc_finish(png_ptr, length);
1140 return;
1143 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1144 png_crc_read(png_ptr, buf, truelen);
1146 if (png_crc_finish(png_ptr, 0) != 0)
1147 return;
1149 for (i=0; i<truelen; ++i)
1150 if (buf[i] == 0 || buf[i] > sample_depth)
1152 png_chunk_benign_error(png_ptr, "invalid");
1153 return;
1156 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1158 png_ptr->sig_bit.red = buf[0];
1159 png_ptr->sig_bit.green = buf[1];
1160 png_ptr->sig_bit.blue = buf[2];
1161 png_ptr->sig_bit.alpha = buf[3];
1164 else
1166 png_ptr->sig_bit.gray = buf[0];
1167 png_ptr->sig_bit.red = buf[0];
1168 png_ptr->sig_bit.green = buf[0];
1169 png_ptr->sig_bit.blue = buf[0];
1170 png_ptr->sig_bit.alpha = buf[1];
1173 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1175 #endif
1177 #ifdef PNG_READ_cHRM_SUPPORTED
1178 void /* PRIVATE */
1179 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1181 png_byte buf[32];
1182 png_xy xy;
1184 png_debug(1, "in png_handle_cHRM");
1186 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1187 png_chunk_error(png_ptr, "missing IHDR");
1189 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1191 png_crc_finish(png_ptr, length);
1192 png_chunk_benign_error(png_ptr, "out of place");
1193 return;
1196 if (length != 32)
1198 png_crc_finish(png_ptr, length);
1199 png_chunk_benign_error(png_ptr, "invalid");
1200 return;
1203 png_crc_read(png_ptr, buf, 32);
1205 if (png_crc_finish(png_ptr, 0) != 0)
1206 return;
1208 xy.whitex = png_get_fixed_point(NULL, buf);
1209 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1210 xy.redx = png_get_fixed_point(NULL, buf + 8);
1211 xy.redy = png_get_fixed_point(NULL, buf + 12);
1212 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1213 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1214 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1215 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1217 if (xy.whitex == PNG_FIXED_ERROR ||
1218 xy.whitey == PNG_FIXED_ERROR ||
1219 xy.redx == PNG_FIXED_ERROR ||
1220 xy.redy == PNG_FIXED_ERROR ||
1221 xy.greenx == PNG_FIXED_ERROR ||
1222 xy.greeny == PNG_FIXED_ERROR ||
1223 xy.bluex == PNG_FIXED_ERROR ||
1224 xy.bluey == PNG_FIXED_ERROR)
1226 png_chunk_benign_error(png_ptr, "invalid values");
1227 return;
1230 /* If a colorspace error has already been output skip this chunk */
1231 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1232 return;
1234 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1236 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1237 png_colorspace_sync(png_ptr, info_ptr);
1238 png_chunk_benign_error(png_ptr, "duplicate");
1239 return;
1242 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1243 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1244 1/*prefer cHRM values*/);
1245 png_colorspace_sync(png_ptr, info_ptr);
1247 #endif
1249 #ifdef PNG_READ_sRGB_SUPPORTED
1250 void /* PRIVATE */
1251 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1253 png_byte intent;
1255 png_debug(1, "in png_handle_sRGB");
1257 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1258 png_chunk_error(png_ptr, "missing IHDR");
1260 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1262 png_crc_finish(png_ptr, length);
1263 png_chunk_benign_error(png_ptr, "out of place");
1264 return;
1267 if (length != 1)
1269 png_crc_finish(png_ptr, length);
1270 png_chunk_benign_error(png_ptr, "invalid");
1271 return;
1274 png_crc_read(png_ptr, &intent, 1);
1276 if (png_crc_finish(png_ptr, 0) != 0)
1277 return;
1279 /* If a colorspace error has already been output skip this chunk */
1280 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1281 return;
1283 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1284 * this.
1286 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1288 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1289 png_colorspace_sync(png_ptr, info_ptr);
1290 png_chunk_benign_error(png_ptr, "too many profiles");
1291 return;
1294 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1295 png_colorspace_sync(png_ptr, info_ptr);
1297 #endif /* READ_sRGB */
1299 #ifdef PNG_READ_iCCP_SUPPORTED
1300 void /* PRIVATE */
1301 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1302 /* Note: this does not properly handle profiles that are > 64K under DOS */
1304 png_const_charp errmsg = NULL; /* error message output, or no error */
1305 int finished = 0; /* crc checked */
1307 png_debug(1, "in png_handle_iCCP");
1309 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1310 png_chunk_error(png_ptr, "missing IHDR");
1312 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1314 png_crc_finish(png_ptr, length);
1315 png_chunk_benign_error(png_ptr, "out of place");
1316 return;
1319 /* Consistent with all the above colorspace handling an obviously *invalid*
1320 * chunk is just ignored, so does not invalidate the color space. An
1321 * alternative is to set the 'invalid' flags at the start of this routine
1322 * and only clear them in they were not set before and all the tests pass.
1323 * The minimum 'deflate' stream is assumed to be just the 2 byte header and
1324 * 4 byte checksum. The keyword must be at least one character and there is
1325 * a terminator (0) byte and the compression method.
1327 if (length < 9)
1329 png_crc_finish(png_ptr, length);
1330 png_chunk_benign_error(png_ptr, "too short");
1331 return;
1334 /* If a colorspace error has already been output skip this chunk */
1335 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1337 png_crc_finish(png_ptr, length);
1338 return;
1341 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1342 * this.
1344 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1346 uInt read_length, keyword_length;
1347 char keyword[81];
1349 /* Find the keyword; the keyword plus separator and compression method
1350 * bytes can be at most 81 characters long.
1352 read_length = 81; /* maximum */
1353 if (read_length > length)
1354 read_length = (uInt)length;
1356 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1357 length -= read_length;
1359 keyword_length = 0;
1360 while (keyword_length < 80 && keyword_length < read_length &&
1361 keyword[keyword_length] != 0)
1362 ++keyword_length;
1364 /* TODO: make the keyword checking common */
1365 if (keyword_length >= 1 && keyword_length <= 79)
1367 /* We only understand '0' compression - deflate - so if we get a
1368 * different value we can't safely decode the chunk.
1370 if (keyword_length+1 < read_length &&
1371 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1373 read_length -= keyword_length+2;
1375 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1377 Byte profile_header[132];
1378 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1379 png_alloc_size_t size = (sizeof profile_header);
1381 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1382 png_ptr->zstream.avail_in = read_length;
1383 (void)png_inflate_read(png_ptr, local_buffer,
1384 (sizeof local_buffer), &length, profile_header, &size,
1385 0/*finish: don't, because the output is too small*/);
1387 if (size == 0)
1389 /* We have the ICC profile header; do the basic header checks.
1391 const png_uint_32 profile_length =
1392 png_get_uint_32(profile_header);
1394 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1395 keyword, profile_length) != 0)
1397 /* The length is apparently ok, so we can check the 132
1398 * byte header.
1400 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1401 keyword, profile_length, profile_header,
1402 png_ptr->color_type) != 0)
1404 /* Now read the tag table; a variable size buffer is
1405 * needed at this point, allocate one for the whole
1406 * profile. The header check has already validated
1407 * that none of these stuff will overflow.
1409 const png_uint_32 tag_count = png_get_uint_32(
1410 profile_header+128);
1411 png_bytep profile = png_read_buffer(png_ptr,
1412 profile_length, 2/*silent*/);
1414 if (profile != NULL)
1416 memcpy(profile, profile_header,
1417 (sizeof profile_header));
1419 size = 12 * tag_count;
1421 (void)png_inflate_read(png_ptr, local_buffer,
1422 (sizeof local_buffer), &length,
1423 profile + (sizeof profile_header), &size, 0);
1425 /* Still expect a buffer error because we expect
1426 * there to be some tag data!
1428 if (size == 0)
1430 if (png_icc_check_tag_table(png_ptr,
1431 &png_ptr->colorspace, keyword, profile_length,
1432 profile) != 0)
1434 /* The profile has been validated for basic
1435 * security issues, so read the whole thing in.
1437 size = profile_length - (sizeof profile_header)
1438 - 12 * tag_count;
1440 (void)png_inflate_read(png_ptr, local_buffer,
1441 (sizeof local_buffer), &length,
1442 profile + (sizeof profile_header) +
1443 12 * tag_count, &size, 1/*finish*/);
1445 if (length > 0 && !(png_ptr->flags &
1446 PNG_FLAG_BENIGN_ERRORS_WARN))
1447 errmsg = "extra compressed data";
1449 /* But otherwise allow extra data: */
1450 else if (size == 0)
1452 if (length > 0)
1454 /* This can be handled completely, so
1455 * keep going.
1457 png_chunk_warning(png_ptr,
1458 "extra compressed data");
1461 png_crc_finish(png_ptr, length);
1462 finished = 1;
1464 # ifdef PNG_sRGB_SUPPORTED
1465 /* Check for a match against sRGB */
1466 png_icc_set_sRGB(png_ptr,
1467 &png_ptr->colorspace, profile,
1468 png_ptr->zstream.adler);
1469 # endif
1471 /* Steal the profile for info_ptr. */
1472 if (info_ptr != NULL)
1474 png_free_data(png_ptr, info_ptr,
1475 PNG_FREE_ICCP, 0);
1477 info_ptr->iccp_name = png_voidcast(char*,
1478 png_malloc_base(png_ptr,
1479 keyword_length+1));
1480 if (info_ptr->iccp_name != NULL)
1482 memcpy(info_ptr->iccp_name, keyword,
1483 keyword_length+1);
1484 info_ptr->iccp_proflen =
1485 profile_length;
1486 info_ptr->iccp_profile = profile;
1487 png_ptr->read_buffer = NULL; /*steal*/
1488 info_ptr->free_me |= PNG_FREE_ICCP;
1489 info_ptr->valid |= PNG_INFO_iCCP;
1492 else
1494 png_ptr->colorspace.flags |=
1495 PNG_COLORSPACE_INVALID;
1496 errmsg = "out of memory";
1500 /* else the profile remains in the read
1501 * buffer which gets reused for subsequent
1502 * chunks.
1505 if (info_ptr != NULL)
1506 png_colorspace_sync(png_ptr, info_ptr);
1508 if (errmsg == NULL)
1510 png_ptr->zowner = 0;
1511 return;
1515 else if (size > 0)
1516 errmsg = "truncated";
1518 #ifndef __COVERITY__
1519 else
1520 errmsg = png_ptr->zstream.msg;
1521 #endif
1524 /* else png_icc_check_tag_table output an error */
1527 else /* profile truncated */
1528 errmsg = png_ptr->zstream.msg;
1531 else
1532 errmsg = "out of memory";
1535 /* else png_icc_check_header output an error */
1538 /* else png_icc_check_length output an error */
1541 else /* profile truncated */
1542 errmsg = png_ptr->zstream.msg;
1544 /* Release the stream */
1545 png_ptr->zowner = 0;
1548 else /* png_inflate_claim failed */
1549 errmsg = png_ptr->zstream.msg;
1552 else
1553 errmsg = "bad compression method"; /* or missing */
1556 else
1557 errmsg = "bad keyword";
1560 else
1561 errmsg = "too many profiles";
1563 /* Failure: the reason is in 'errmsg' */
1564 if (finished == 0)
1565 png_crc_finish(png_ptr, length);
1567 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1568 png_colorspace_sync(png_ptr, info_ptr);
1569 if (errmsg != NULL) /* else already output */
1570 png_chunk_benign_error(png_ptr, errmsg);
1572 #endif /* READ_iCCP */
1574 #ifdef PNG_READ_sPLT_SUPPORTED
1575 void /* PRIVATE */
1576 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1577 /* Note: this does not properly handle chunks that are > 64K under DOS */
1579 png_bytep entry_start, buffer;
1580 png_sPLT_t new_palette;
1581 png_sPLT_entryp pp;
1582 png_uint_32 data_length;
1583 int entry_size, i;
1584 png_uint_32 skip = 0;
1585 png_uint_32 dl;
1586 png_size_t max_dl;
1588 png_debug(1, "in png_handle_sPLT");
1590 #ifdef PNG_USER_LIMITS_SUPPORTED
1591 if (png_ptr->user_chunk_cache_max != 0)
1593 if (png_ptr->user_chunk_cache_max == 1)
1595 png_crc_finish(png_ptr, length);
1596 return;
1599 if (--png_ptr->user_chunk_cache_max == 1)
1601 png_warning(png_ptr, "No space in chunk cache for sPLT");
1602 png_crc_finish(png_ptr, length);
1603 return;
1606 #endif
1608 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1609 png_chunk_error(png_ptr, "missing IHDR");
1611 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1613 png_crc_finish(png_ptr, length);
1614 png_chunk_benign_error(png_ptr, "out of place");
1615 return;
1618 #ifdef PNG_MAX_MALLOC_64K
1619 if (length > 65535U)
1621 png_crc_finish(png_ptr, length);
1622 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1623 return;
1625 #endif
1627 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1628 if (buffer == NULL)
1630 png_crc_finish(png_ptr, length);
1631 png_chunk_benign_error(png_ptr, "out of memory");
1632 return;
1636 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1637 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1638 * potential breakage point if the types in pngconf.h aren't exactly right.
1640 png_crc_read(png_ptr, buffer, length);
1642 if (png_crc_finish(png_ptr, skip) != 0)
1643 return;
1645 buffer[length] = 0;
1647 for (entry_start = buffer; *entry_start; entry_start++)
1648 /* Empty loop to find end of name */ ;
1650 ++entry_start;
1652 /* A sample depth should follow the separator, and we should be on it */
1653 if (entry_start > buffer + length - 2)
1655 png_warning(png_ptr, "malformed sPLT chunk");
1656 return;
1659 new_palette.depth = *entry_start++;
1660 entry_size = (new_palette.depth == 8 ? 6 : 10);
1661 /* This must fit in a png_uint_32 because it is derived from the original
1662 * chunk data length.
1664 data_length = length - (png_uint_32)(entry_start - buffer);
1666 /* Integrity-check the data length */
1667 if ((data_length % entry_size) != 0)
1669 png_warning(png_ptr, "sPLT chunk has bad length");
1670 return;
1673 dl = (png_int_32)(data_length / entry_size);
1674 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1676 if (dl > max_dl)
1678 png_warning(png_ptr, "sPLT chunk too long");
1679 return;
1682 new_palette.nentries = (png_int_32)(data_length / entry_size);
1684 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
1685 png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
1687 if (new_palette.entries == NULL)
1689 png_warning(png_ptr, "sPLT chunk requires too much memory");
1690 return;
1693 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1694 for (i = 0; i < new_palette.nentries; i++)
1696 pp = new_palette.entries + i;
1698 if (new_palette.depth == 8)
1700 pp->red = *entry_start++;
1701 pp->green = *entry_start++;
1702 pp->blue = *entry_start++;
1703 pp->alpha = *entry_start++;
1706 else
1708 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1709 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1710 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1711 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1714 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1716 #else
1717 pp = new_palette.entries;
1719 for (i = 0; i < new_palette.nentries; i++)
1722 if (new_palette.depth == 8)
1724 pp[i].red = *entry_start++;
1725 pp[i].green = *entry_start++;
1726 pp[i].blue = *entry_start++;
1727 pp[i].alpha = *entry_start++;
1730 else
1732 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1733 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1734 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1735 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1738 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1740 #endif
1742 /* Discard all chunk data except the name and stash that */
1743 new_palette.name = (png_charp)buffer;
1745 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1747 png_free(png_ptr, new_palette.entries);
1749 #endif /* READ_sPLT */
1751 #ifdef PNG_READ_tRNS_SUPPORTED
1752 void /* PRIVATE */
1753 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1755 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1757 png_debug(1, "in png_handle_tRNS");
1759 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1760 png_chunk_error(png_ptr, "missing IHDR");
1762 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1764 png_crc_finish(png_ptr, length);
1765 png_chunk_benign_error(png_ptr, "out of place");
1766 return;
1769 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1771 png_crc_finish(png_ptr, length);
1772 png_chunk_benign_error(png_ptr, "duplicate");
1773 return;
1776 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1778 png_byte buf[2];
1780 if (length != 2)
1782 png_crc_finish(png_ptr, length);
1783 png_chunk_benign_error(png_ptr, "invalid");
1784 return;
1787 png_crc_read(png_ptr, buf, 2);
1788 png_ptr->num_trans = 1;
1789 png_ptr->trans_color.gray = png_get_uint_16(buf);
1792 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1794 png_byte buf[6];
1796 if (length != 6)
1798 png_crc_finish(png_ptr, length);
1799 png_chunk_benign_error(png_ptr, "invalid");
1800 return;
1803 png_crc_read(png_ptr, buf, length);
1804 png_ptr->num_trans = 1;
1805 png_ptr->trans_color.red = png_get_uint_16(buf);
1806 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1807 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1810 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1812 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1814 /* TODO: is this actually an error in the ISO spec? */
1815 png_crc_finish(png_ptr, length);
1816 png_chunk_benign_error(png_ptr, "out of place");
1817 return;
1820 if (length > png_ptr->num_palette || length > PNG_MAX_PALETTE_LENGTH ||
1821 length == 0)
1823 png_crc_finish(png_ptr, length);
1824 png_chunk_benign_error(png_ptr, "invalid");
1825 return;
1828 png_crc_read(png_ptr, readbuf, length);
1829 png_ptr->num_trans = (png_uint_16)length;
1832 else
1834 png_crc_finish(png_ptr, length);
1835 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1836 return;
1839 if (png_crc_finish(png_ptr, 0) != 0)
1841 png_ptr->num_trans = 0;
1842 return;
1845 /* TODO: this is a horrible side effect in the palette case because the
1846 * png_struct ends up with a pointer to the tRNS buffer owned by the
1847 * png_info. Fix this.
1849 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1850 &(png_ptr->trans_color));
1852 #endif
1854 #ifdef PNG_READ_bKGD_SUPPORTED
1855 void /* PRIVATE */
1856 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1858 unsigned int truelen;
1859 png_byte buf[6];
1860 png_color_16 background;
1862 png_debug(1, "in png_handle_bKGD");
1864 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1865 png_chunk_error(png_ptr, "missing IHDR");
1867 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1868 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1869 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1871 png_crc_finish(png_ptr, length);
1872 png_chunk_benign_error(png_ptr, "out of place");
1873 return;
1876 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1878 png_crc_finish(png_ptr, length);
1879 png_chunk_benign_error(png_ptr, "duplicate");
1880 return;
1883 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1884 truelen = 1;
1886 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1887 truelen = 6;
1889 else
1890 truelen = 2;
1892 if (length != truelen)
1894 png_crc_finish(png_ptr, length);
1895 png_chunk_benign_error(png_ptr, "invalid");
1896 return;
1899 png_crc_read(png_ptr, buf, truelen);
1901 if (png_crc_finish(png_ptr, 0) != 0)
1902 return;
1904 /* We convert the index value into RGB components so that we can allow
1905 * arbitrary RGB values for background when we have transparency, and
1906 * so it is easy to determine the RGB values of the background color
1907 * from the info_ptr struct.
1909 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1911 background.index = buf[0];
1913 if (info_ptr != NULL && info_ptr->num_palette != 0)
1915 if (buf[0] >= info_ptr->num_palette)
1917 png_chunk_benign_error(png_ptr, "invalid index");
1918 return;
1921 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1922 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1923 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1926 else
1927 background.red = background.green = background.blue = 0;
1929 background.gray = 0;
1932 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1934 background.index = 0;
1935 background.red =
1936 background.green =
1937 background.blue =
1938 background.gray = png_get_uint_16(buf);
1941 else
1943 background.index = 0;
1944 background.red = png_get_uint_16(buf);
1945 background.green = png_get_uint_16(buf + 2);
1946 background.blue = png_get_uint_16(buf + 4);
1947 background.gray = 0;
1950 png_set_bKGD(png_ptr, info_ptr, &background);
1952 #endif
1954 #ifdef PNG_READ_hIST_SUPPORTED
1955 void /* PRIVATE */
1956 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1958 unsigned int num, i;
1959 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
1961 png_debug(1, "in png_handle_hIST");
1963 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1964 png_chunk_error(png_ptr, "missing IHDR");
1966 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1967 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
1969 png_crc_finish(png_ptr, length);
1970 png_chunk_benign_error(png_ptr, "out of place");
1971 return;
1974 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1976 png_crc_finish(png_ptr, length);
1977 png_chunk_benign_error(png_ptr, "duplicate");
1978 return;
1981 num = length / 2 ;
1983 if (num != png_ptr->num_palette || num > PNG_MAX_PALETTE_LENGTH)
1985 png_crc_finish(png_ptr, length);
1986 png_chunk_benign_error(png_ptr, "invalid");
1987 return;
1990 for (i = 0; i < num; i++)
1992 png_byte buf[2];
1994 png_crc_read(png_ptr, buf, 2);
1995 readbuf[i] = png_get_uint_16(buf);
1998 if (png_crc_finish(png_ptr, 0) != 0)
1999 return;
2001 png_set_hIST(png_ptr, info_ptr, readbuf);
2003 #endif
2005 #ifdef PNG_READ_pHYs_SUPPORTED
2006 void /* PRIVATE */
2007 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2009 png_byte buf[9];
2010 png_uint_32 res_x, res_y;
2011 int unit_type;
2013 png_debug(1, "in png_handle_pHYs");
2015 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2016 png_chunk_error(png_ptr, "missing IHDR");
2018 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2020 png_crc_finish(png_ptr, length);
2021 png_chunk_benign_error(png_ptr, "out of place");
2022 return;
2025 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2027 png_crc_finish(png_ptr, length);
2028 png_chunk_benign_error(png_ptr, "duplicate");
2029 return;
2032 if (length != 9)
2034 png_crc_finish(png_ptr, length);
2035 png_chunk_benign_error(png_ptr, "invalid");
2036 return;
2039 png_crc_read(png_ptr, buf, 9);
2041 if (png_crc_finish(png_ptr, 0) != 0)
2042 return;
2044 res_x = png_get_uint_32(buf);
2045 res_y = png_get_uint_32(buf + 4);
2046 unit_type = buf[8];
2047 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2049 #endif
2051 #ifdef PNG_READ_oFFs_SUPPORTED
2052 void /* PRIVATE */
2053 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2055 png_byte buf[9];
2056 png_int_32 offset_x, offset_y;
2057 int unit_type;
2059 png_debug(1, "in png_handle_oFFs");
2061 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2062 png_chunk_error(png_ptr, "missing IHDR");
2064 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2066 png_crc_finish(png_ptr, length);
2067 png_chunk_benign_error(png_ptr, "out of place");
2068 return;
2071 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2073 png_crc_finish(png_ptr, length);
2074 png_chunk_benign_error(png_ptr, "duplicate");
2075 return;
2078 if (length != 9)
2080 png_crc_finish(png_ptr, length);
2081 png_chunk_benign_error(png_ptr, "invalid");
2082 return;
2085 png_crc_read(png_ptr, buf, 9);
2087 if (png_crc_finish(png_ptr, 0) != 0)
2088 return;
2090 offset_x = png_get_int_32(buf);
2091 offset_y = png_get_int_32(buf + 4);
2092 unit_type = buf[8];
2093 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2095 #endif
2097 #ifdef PNG_READ_pCAL_SUPPORTED
2098 /* Read the pCAL chunk (described in the PNG Extensions document) */
2099 void /* PRIVATE */
2100 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2102 png_int_32 X0, X1;
2103 png_byte type, nparams;
2104 png_bytep buffer, buf, units, endptr;
2105 png_charpp params;
2106 int i;
2108 png_debug(1, "in png_handle_pCAL");
2110 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2111 png_chunk_error(png_ptr, "missing IHDR");
2113 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2115 png_crc_finish(png_ptr, length);
2116 png_chunk_benign_error(png_ptr, "out of place");
2117 return;
2120 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2122 png_crc_finish(png_ptr, length);
2123 png_chunk_benign_error(png_ptr, "duplicate");
2124 return;
2127 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2128 length + 1);
2130 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2132 if (buffer == NULL)
2134 png_crc_finish(png_ptr, length);
2135 png_chunk_benign_error(png_ptr, "out of memory");
2136 return;
2139 png_crc_read(png_ptr, buffer, length);
2141 if (png_crc_finish(png_ptr, 0) != 0)
2142 return;
2144 buffer[length] = 0; /* Null terminate the last string */
2146 png_debug(3, "Finding end of pCAL purpose string");
2147 for (buf = buffer; *buf; buf++)
2148 /* Empty loop */ ;
2150 endptr = buffer + length;
2152 /* We need to have at least 12 bytes after the purpose string
2153 * in order to get the parameter information.
2155 if (endptr <= buf + 12)
2157 png_chunk_benign_error(png_ptr, "invalid");
2158 return;
2161 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2162 X0 = png_get_int_32((png_bytep)buf+1);
2163 X1 = png_get_int_32((png_bytep)buf+5);
2164 type = buf[9];
2165 nparams = buf[10];
2166 units = buf + 11;
2168 png_debug(3, "Checking pCAL equation type and number of parameters");
2169 /* Check that we have the right number of parameters for known
2170 * equation types.
2172 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2173 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2174 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2175 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2177 png_chunk_benign_error(png_ptr, "invalid parameter count");
2178 return;
2181 else if (type >= PNG_EQUATION_LAST)
2183 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2186 for (buf = units; *buf; buf++)
2187 /* Empty loop to move past the units string. */ ;
2189 png_debug(3, "Allocating pCAL parameters array");
2191 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2192 nparams * (sizeof (png_charp))));
2194 if (params == NULL)
2196 png_chunk_benign_error(png_ptr, "out of memory");
2197 return;
2200 /* Get pointers to the start of each parameter string. */
2201 for (i = 0; i < nparams; i++)
2203 buf++; /* Skip the null string terminator from previous parameter. */
2205 png_debug1(3, "Reading pCAL parameter %d", i);
2207 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2208 /* Empty loop to move past each parameter string */ ;
2210 /* Make sure we haven't run out of data yet */
2211 if (buf > endptr)
2213 png_free(png_ptr, params);
2214 png_chunk_benign_error(png_ptr, "invalid data");
2215 return;
2219 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2220 (png_charp)units, params);
2222 png_free(png_ptr, params);
2224 #endif
2226 #ifdef PNG_READ_sCAL_SUPPORTED
2227 /* Read the sCAL chunk */
2228 void /* PRIVATE */
2229 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2231 png_bytep buffer;
2232 png_size_t i;
2233 int state;
2235 png_debug(1, "in png_handle_sCAL");
2237 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2238 png_chunk_error(png_ptr, "missing IHDR");
2240 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2242 png_crc_finish(png_ptr, length);
2243 png_chunk_benign_error(png_ptr, "out of place");
2244 return;
2247 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2249 png_crc_finish(png_ptr, length);
2250 png_chunk_benign_error(png_ptr, "duplicate");
2251 return;
2254 /* Need unit type, width, \0, height: minimum 4 bytes */
2255 else if (length < 4)
2257 png_crc_finish(png_ptr, length);
2258 png_chunk_benign_error(png_ptr, "invalid");
2259 return;
2262 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2263 length + 1);
2265 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2267 if (buffer == NULL)
2269 png_chunk_benign_error(png_ptr, "out of memory");
2270 png_crc_finish(png_ptr, length);
2271 return;
2274 png_crc_read(png_ptr, buffer, length);
2275 buffer[length] = 0; /* Null terminate the last string */
2277 if (png_crc_finish(png_ptr, 0) != 0)
2278 return;
2280 /* Validate the unit. */
2281 if (buffer[0] != 1 && buffer[0] != 2)
2283 png_chunk_benign_error(png_ptr, "invalid unit");
2284 return;
2287 /* Validate the ASCII numbers, need two ASCII numbers separated by
2288 * a '\0' and they need to fit exactly in the chunk data.
2290 i = 1;
2291 state = 0;
2293 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2294 i >= length || buffer[i++] != 0)
2295 png_chunk_benign_error(png_ptr, "bad width format");
2297 else if (PNG_FP_IS_POSITIVE(state) == 0)
2298 png_chunk_benign_error(png_ptr, "non-positive width");
2300 else
2302 png_size_t heighti = i;
2304 state = 0;
2305 if (png_check_fp_number((png_const_charp)buffer, length,
2306 &state, &i) == 0 || i != length)
2307 png_chunk_benign_error(png_ptr, "bad height format");
2309 else if (PNG_FP_IS_POSITIVE(state) == 0)
2310 png_chunk_benign_error(png_ptr, "non-positive height");
2312 else
2313 /* This is the (only) success case. */
2314 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2315 (png_charp)buffer+1, (png_charp)buffer+heighti);
2318 #endif
2320 #ifdef PNG_READ_tIME_SUPPORTED
2321 void /* PRIVATE */
2322 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2324 png_byte buf[7];
2325 png_time mod_time;
2327 png_debug(1, "in png_handle_tIME");
2329 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2330 png_chunk_error(png_ptr, "missing IHDR");
2332 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2334 png_crc_finish(png_ptr, length);
2335 png_chunk_benign_error(png_ptr, "duplicate");
2336 return;
2339 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2340 png_ptr->mode |= PNG_AFTER_IDAT;
2342 if (length != 7)
2344 png_crc_finish(png_ptr, length);
2345 png_chunk_benign_error(png_ptr, "invalid");
2346 return;
2349 png_crc_read(png_ptr, buf, 7);
2351 if (png_crc_finish(png_ptr, 0) != 0)
2352 return;
2354 mod_time.second = buf[6];
2355 mod_time.minute = buf[5];
2356 mod_time.hour = buf[4];
2357 mod_time.day = buf[3];
2358 mod_time.month = buf[2];
2359 mod_time.year = png_get_uint_16(buf);
2361 png_set_tIME(png_ptr, info_ptr, &mod_time);
2363 #endif
2365 #ifdef PNG_READ_tEXt_SUPPORTED
2366 /* Note: this does not properly handle chunks that are > 64K under DOS */
2367 void /* PRIVATE */
2368 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2370 png_text text_info;
2371 png_bytep buffer;
2372 png_charp key;
2373 png_charp text;
2374 png_uint_32 skip = 0;
2376 png_debug(1, "in png_handle_tEXt");
2378 #ifdef PNG_USER_LIMITS_SUPPORTED
2379 if (png_ptr->user_chunk_cache_max != 0)
2381 if (png_ptr->user_chunk_cache_max == 1)
2383 png_crc_finish(png_ptr, length);
2384 return;
2387 if (--png_ptr->user_chunk_cache_max == 1)
2389 png_crc_finish(png_ptr, length);
2390 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2391 return;
2394 #endif
2396 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2397 png_chunk_error(png_ptr, "missing IHDR");
2399 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2400 png_ptr->mode |= PNG_AFTER_IDAT;
2402 #ifdef PNG_MAX_MALLOC_64K
2403 if (length > 65535U)
2405 png_crc_finish(png_ptr, length);
2406 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2407 return;
2409 #endif
2411 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2413 if (buffer == NULL)
2415 png_chunk_benign_error(png_ptr, "out of memory");
2416 return;
2419 png_crc_read(png_ptr, buffer, length);
2421 if (png_crc_finish(png_ptr, skip) != 0)
2422 return;
2424 key = (png_charp)buffer;
2425 key[length] = 0;
2427 for (text = key; *text; text++)
2428 /* Empty loop to find end of key */ ;
2430 if (text != key + length)
2431 text++;
2433 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2434 text_info.key = key;
2435 text_info.lang = NULL;
2436 text_info.lang_key = NULL;
2437 text_info.itxt_length = 0;
2438 text_info.text = text;
2439 text_info.text_length = strlen(text);
2441 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2442 png_warning(png_ptr, "Insufficient memory to process text chunk");
2444 #endif
2446 #ifdef PNG_READ_zTXt_SUPPORTED
2447 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2448 void /* PRIVATE */
2449 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2451 png_const_charp errmsg = NULL;
2452 png_bytep buffer;
2453 png_uint_32 keyword_length;
2455 png_debug(1, "in png_handle_zTXt");
2457 #ifdef PNG_USER_LIMITS_SUPPORTED
2458 if (png_ptr->user_chunk_cache_max != 0)
2460 if (png_ptr->user_chunk_cache_max == 1)
2462 png_crc_finish(png_ptr, length);
2463 return;
2466 if (--png_ptr->user_chunk_cache_max == 1)
2468 png_crc_finish(png_ptr, length);
2469 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2470 return;
2473 #endif
2475 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2476 png_chunk_error(png_ptr, "missing IHDR");
2478 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2479 png_ptr->mode |= PNG_AFTER_IDAT;
2481 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2483 if (buffer == NULL)
2485 png_crc_finish(png_ptr, length);
2486 png_chunk_benign_error(png_ptr, "out of memory");
2487 return;
2490 png_crc_read(png_ptr, buffer, length);
2492 if (png_crc_finish(png_ptr, 0) != 0)
2493 return;
2495 /* TODO: also check that the keyword contents match the spec! */
2496 for (keyword_length = 0;
2497 keyword_length < length && buffer[keyword_length] != 0;
2498 ++keyword_length)
2499 /* Empty loop to find end of name */ ;
2501 if (keyword_length > 79 || keyword_length < 1)
2502 errmsg = "bad keyword";
2504 /* zTXt must have some LZ data after the keyword, although it may expand to
2505 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2506 * then the LZ data:
2508 else if (keyword_length + 3 > length)
2509 errmsg = "truncated";
2511 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2512 errmsg = "unknown compression type";
2514 else
2516 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2518 /* TODO: at present png_decompress_chunk imposes a single application
2519 * level memory limit, this should be split to different values for iCCP
2520 * and text chunks.
2522 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2523 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2525 png_text text;
2527 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
2528 * for the extra compression type byte and the fact that it isn't
2529 * necessarily '\0' terminated.
2531 buffer = png_ptr->read_buffer;
2532 buffer[uncompressed_length+(keyword_length+2)] = 0;
2534 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2535 text.key = (png_charp)buffer;
2536 text.text = (png_charp)(buffer + keyword_length+2);
2537 text.text_length = uncompressed_length;
2538 text.itxt_length = 0;
2539 text.lang = NULL;
2540 text.lang_key = NULL;
2542 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2543 errmsg = "insufficient memory";
2546 else
2547 errmsg = png_ptr->zstream.msg;
2550 if (errmsg != NULL)
2551 png_chunk_benign_error(png_ptr, errmsg);
2553 #endif
2555 #ifdef PNG_READ_iTXt_SUPPORTED
2556 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2557 void /* PRIVATE */
2558 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2560 png_const_charp errmsg = NULL;
2561 png_bytep buffer;
2562 png_uint_32 prefix_length;
2564 png_debug(1, "in png_handle_iTXt");
2566 #ifdef PNG_USER_LIMITS_SUPPORTED
2567 if (png_ptr->user_chunk_cache_max != 0)
2569 if (png_ptr->user_chunk_cache_max == 1)
2571 png_crc_finish(png_ptr, length);
2572 return;
2575 if (--png_ptr->user_chunk_cache_max == 1)
2577 png_crc_finish(png_ptr, length);
2578 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2579 return;
2582 #endif
2584 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2585 png_chunk_error(png_ptr, "missing IHDR");
2587 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2588 png_ptr->mode |= PNG_AFTER_IDAT;
2590 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2592 if (buffer == NULL)
2594 png_crc_finish(png_ptr, length);
2595 png_chunk_benign_error(png_ptr, "out of memory");
2596 return;
2599 png_crc_read(png_ptr, buffer, length);
2601 if (png_crc_finish(png_ptr, 0) != 0)
2602 return;
2604 /* First the keyword. */
2605 for (prefix_length=0;
2606 prefix_length < length && buffer[prefix_length] != 0;
2607 ++prefix_length)
2608 /* Empty loop */ ;
2610 /* Perform a basic check on the keyword length here. */
2611 if (prefix_length > 79 || prefix_length < 1)
2612 errmsg = "bad keyword";
2614 /* Expect keyword, compression flag, compression type, language, translated
2615 * keyword (both may be empty but are 0 terminated) then the text, which may
2616 * be empty.
2618 else if (prefix_length + 5 > length)
2619 errmsg = "truncated";
2621 else if (buffer[prefix_length+1] == 0 ||
2622 (buffer[prefix_length+1] == 1 &&
2623 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2625 int compressed = buffer[prefix_length+1] != 0;
2626 png_uint_32 language_offset, translated_keyword_offset;
2627 png_alloc_size_t uncompressed_length = 0;
2629 /* Now the language tag */
2630 prefix_length += 3;
2631 language_offset = prefix_length;
2633 for (; prefix_length < length && buffer[prefix_length] != 0;
2634 ++prefix_length)
2635 /* Empty loop */ ;
2637 /* WARNING: the length may be invalid here, this is checked below. */
2638 translated_keyword_offset = ++prefix_length;
2640 for (; prefix_length < length && buffer[prefix_length] != 0;
2641 ++prefix_length)
2642 /* Empty loop */ ;
2644 /* prefix_length should now be at the trailing '\0' of the translated
2645 * keyword, but it may already be over the end. None of this arithmetic
2646 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2647 * systems the available allocation may overflow.
2649 ++prefix_length;
2651 if (compressed == 0 && prefix_length <= length)
2652 uncompressed_length = length - prefix_length;
2654 else if (compressed != 0 && prefix_length < length)
2656 uncompressed_length = PNG_SIZE_MAX;
2658 /* TODO: at present png_decompress_chunk imposes a single application
2659 * level memory limit, this should be split to different values for
2660 * iCCP and text chunks.
2662 if (png_decompress_chunk(png_ptr, length, prefix_length,
2663 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2664 buffer = png_ptr->read_buffer;
2666 else
2667 errmsg = png_ptr->zstream.msg;
2670 else
2671 errmsg = "truncated";
2673 if (errmsg == NULL)
2675 png_text text;
2677 buffer[uncompressed_length+prefix_length] = 0;
2679 if (compressed == 0)
2680 text.compression = PNG_ITXT_COMPRESSION_NONE;
2682 else
2683 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2685 text.key = (png_charp)buffer;
2686 text.lang = (png_charp)buffer + language_offset;
2687 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2688 text.text = (png_charp)buffer + prefix_length;
2689 text.text_length = 0;
2690 text.itxt_length = uncompressed_length;
2692 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2693 errmsg = "insufficient memory";
2697 else
2698 errmsg = "bad compression info";
2700 if (errmsg != NULL)
2701 png_chunk_benign_error(png_ptr, errmsg);
2703 #endif
2705 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2706 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2707 static int
2708 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2710 png_alloc_size_t limit = PNG_SIZE_MAX;
2712 if (png_ptr->unknown_chunk.data != NULL)
2714 png_free(png_ptr, png_ptr->unknown_chunk.data);
2715 png_ptr->unknown_chunk.data = NULL;
2718 # ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
2719 if (png_ptr->user_chunk_malloc_max > 0 &&
2720 png_ptr->user_chunk_malloc_max < limit)
2721 limit = png_ptr->user_chunk_malloc_max;
2723 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2724 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2725 limit = PNG_USER_CHUNK_MALLOC_MAX;
2726 # endif
2728 if (length <= limit)
2730 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2731 /* The following is safe because of the PNG_SIZE_MAX init above */
2732 png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
2733 /* 'mode' is a flag array, only the bottom four bits matter here */
2734 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2736 if (length == 0)
2737 png_ptr->unknown_chunk.data = NULL;
2739 else
2741 /* Do a 'warn' here - it is handled below. */
2742 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2743 png_malloc_warn(png_ptr, length));
2747 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2749 /* This is benign because we clean up correctly */
2750 png_crc_finish(png_ptr, length);
2751 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2752 return 0;
2755 else
2757 if (length > 0)
2758 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2759 png_crc_finish(png_ptr, 0);
2760 return 1;
2763 #endif /* READ_UNKNOWN_CHUNKS */
2765 /* Handle an unknown, or known but disabled, chunk */
2766 void /* PRIVATE */
2767 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2768 png_uint_32 length, int keep)
2770 int handled = 0; /* the chunk was handled */
2772 png_debug(1, "in png_handle_unknown");
2774 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2775 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2776 * the bug which meant that setting a non-default behavior for a specific
2777 * chunk would be ignored (the default was always used unless a user
2778 * callback was installed).
2780 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2781 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2782 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2783 * This is just an optimization to avoid multiple calls to the lookup
2784 * function.
2786 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2787 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2788 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2789 # endif
2790 # endif
2792 /* One of the following methods will read the chunk or skip it (at least one
2793 * of these is always defined because this is the only way to switch on
2794 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2796 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2797 /* The user callback takes precedence over the chunk keep value, but the
2798 * keep value is still required to validate a save of a critical chunk.
2800 if (png_ptr->read_user_chunk_fn != NULL)
2802 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2804 /* Callback to user unknown chunk handler */
2805 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2806 &png_ptr->unknown_chunk);
2808 /* ret is:
2809 * negative: An error occurred; png_chunk_error will be called.
2810 * zero: The chunk was not handled, the chunk will be discarded
2811 * unless png_set_keep_unknown_chunks has been used to set
2812 * a 'keep' behavior for this particular chunk, in which
2813 * case that will be used. A critical chunk will cause an
2814 * error at this point unless it is to be saved.
2815 * positive: The chunk was handled, libpng will ignore/discard it.
2817 if (ret < 0)
2818 png_chunk_error(png_ptr, "error in user chunk");
2820 else if (ret == 0)
2822 /* If the keep value is 'default' or 'never' override it, but
2823 * still error out on critical chunks unless the keep value is
2824 * 'always' While this is weird it is the behavior in 1.4.12.
2825 * A possible improvement would be to obey the value set for the
2826 * chunk, but this would be an API change that would probably
2827 * damage some applications.
2829 * The png_app_warning below catches the case that matters, where
2830 * the application has not set specific save or ignore for this
2831 * chunk or global save or ignore.
2833 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2835 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2836 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2838 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2839 png_app_warning(png_ptr,
2840 "forcing save of an unhandled chunk;"
2841 " please call png_set_keep_unknown_chunks");
2842 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
2844 # endif
2845 keep = PNG_HANDLE_CHUNK_IF_SAFE;
2849 else /* chunk was handled */
2851 handled = 1;
2852 /* Critical chunks can be safely discarded at this point. */
2853 keep = PNG_HANDLE_CHUNK_NEVER;
2857 else
2858 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
2861 else
2862 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
2863 # endif /* READ_USER_CHUNKS */
2865 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
2867 /* keep is currently just the per-chunk setting, if there was no
2868 * setting change it to the global default now (not that this may
2869 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
2870 * if not simply skip the chunk.
2872 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
2873 keep = png_ptr->unknown_default;
2875 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2876 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2877 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2879 if (png_cache_unknown_chunk(png_ptr, length) == 0)
2880 keep = PNG_HANDLE_CHUNK_NEVER;
2883 else
2884 png_crc_finish(png_ptr, length);
2886 # else
2887 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
2888 # error no method to support READ_UNKNOWN_CHUNKS
2889 # endif
2892 /* If here there is no read callback pointer set and no support is
2893 * compiled in to just save the unknown chunks, so simply skip this
2894 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
2895 * the app has erroneously asked for unknown chunk saving when there
2896 * is no support.
2898 if (keep > PNG_HANDLE_CHUNK_NEVER)
2899 png_app_error(png_ptr, "no unknown chunk support available");
2901 png_crc_finish(png_ptr, length);
2903 # endif
2905 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
2906 /* Now store the chunk in the chunk list if appropriate, and if the limits
2907 * permit it.
2909 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2910 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2911 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2913 # ifdef PNG_USER_LIMITS_SUPPORTED
2914 switch (png_ptr->user_chunk_cache_max)
2916 case 2:
2917 png_ptr->user_chunk_cache_max = 1;
2918 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2919 /* FALL THROUGH */
2920 case 1:
2921 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
2922 * chunk being skipped, now there will be a hard error below.
2924 break;
2926 default: /* not at limit */
2927 --(png_ptr->user_chunk_cache_max);
2928 /* FALL THROUGH */
2929 case 0: /* no limit */
2930 # endif /* USER_LIMITS */
2931 /* Here when the limit isn't reached or when limits are compiled
2932 * out; store the chunk.
2934 png_set_unknown_chunks(png_ptr, info_ptr,
2935 &png_ptr->unknown_chunk, 1);
2936 handled = 1;
2937 # ifdef PNG_USER_LIMITS_SUPPORTED
2938 break;
2940 # endif
2942 # else /* no store support: the chunk must be handled by the user callback */
2943 PNG_UNUSED(info_ptr)
2944 # endif
2946 /* Regardless of the error handling below the cached data (if any) can be
2947 * freed now. Notice that the data is not freed if there is a png_error, but
2948 * it will be freed by destroy_read_struct.
2950 if (png_ptr->unknown_chunk.data != NULL)
2951 png_free(png_ptr, png_ptr->unknown_chunk.data);
2952 png_ptr->unknown_chunk.data = NULL;
2954 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
2955 /* There is no support to read an unknown chunk, so just skip it. */
2956 png_crc_finish(png_ptr, length);
2957 PNG_UNUSED(info_ptr)
2958 PNG_UNUSED(keep)
2959 #endif /* !READ_UNKNOWN_CHUNKS */
2961 /* Check for unhandled critical chunks */
2962 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
2963 png_chunk_error(png_ptr, "unhandled critical chunk");
2966 /* This function is called to verify that a chunk name is valid.
2967 * This function can't have the "critical chunk check" incorporated
2968 * into it, since in the future we will need to be able to call user
2969 * functions to handle unknown critical chunks after we check that
2970 * the chunk name itself is valid.
2973 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
2975 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
2978 void /* PRIVATE */
2979 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
2981 int i;
2983 png_debug(1, "in png_check_chunk_name");
2985 for (i=1; i<=4; ++i)
2987 int c = chunk_name & 0xff;
2989 if (c < 65 || c > 122 || (c > 90 && c < 97))
2990 png_chunk_error(png_ptr, "invalid chunk type");
2992 chunk_name >>= 8;
2996 /* Combines the row recently read in with the existing pixels in the row. This
2997 * routine takes care of alpha and transparency if requested. This routine also
2998 * handles the two methods of progressive display of interlaced images,
2999 * depending on the 'display' value; if 'display' is true then the whole row
3000 * (dp) is filled from the start by replicating the available pixels. If
3001 * 'display' is false only those pixels present in the pass are filled in.
3003 void /* PRIVATE */
3004 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3006 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3007 png_const_bytep sp = png_ptr->row_buf + 1;
3008 png_alloc_size_t row_width = png_ptr->width;
3009 unsigned int pass = png_ptr->pass;
3010 png_bytep end_ptr = 0;
3011 png_byte end_byte = 0;
3012 unsigned int end_mask;
3014 png_debug(1, "in png_combine_row");
3016 /* Added in 1.5.6: it should not be possible to enter this routine until at
3017 * least one row has been read from the PNG data and transformed.
3019 if (pixel_depth == 0)
3020 png_error(png_ptr, "internal row logic error");
3022 /* Added in 1.5.4: the pixel depth should match the information returned by
3023 * any call to png_read_update_info at this point. Do not continue if we got
3024 * this wrong.
3026 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3027 PNG_ROWBYTES(pixel_depth, row_width))
3028 png_error(png_ptr, "internal row size calculation error");
3030 /* Don't expect this to ever happen: */
3031 if (row_width == 0)
3032 png_error(png_ptr, "internal row width error");
3034 /* Preserve the last byte in cases where only part of it will be overwritten,
3035 * the multiply below may overflow, we don't care because ANSI-C guarantees
3036 * we get the low bits.
3038 end_mask = (pixel_depth * row_width) & 7;
3039 if (end_mask != 0)
3041 /* end_ptr == NULL is a flag to say do nothing */
3042 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3043 end_byte = *end_ptr;
3044 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3045 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3046 /* little-endian byte */
3047 end_mask = 0xff << end_mask;
3049 else /* big-endian byte */
3050 # endif
3051 end_mask = 0xff >> end_mask;
3052 /* end_mask is now the bits to *keep* from the destination row */
3055 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3056 * will also happen if interlacing isn't supported or if the application
3057 * does not call png_set_interlace_handling(). In the latter cases the
3058 * caller just gets a sequence of the unexpanded rows from each interlace
3059 * pass.
3061 #ifdef PNG_READ_INTERLACING_SUPPORTED
3062 if (png_ptr->interlaced != 0 &&
3063 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3064 pass < 6 && (display == 0 ||
3065 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3066 (display == 1 && (pass & 1) != 0)))
3068 /* Narrow images may have no bits in a pass; the caller should handle
3069 * this, but this test is cheap:
3071 if (row_width <= PNG_PASS_START_COL(pass))
3072 return;
3074 if (pixel_depth < 8)
3076 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3077 * into 32 bits, then a single loop over the bytes using the four byte
3078 * values in the 32-bit mask can be used. For the 'display' option the
3079 * expanded mask may also not require any masking within a byte. To
3080 * make this work the PACKSWAP option must be taken into account - it
3081 * simply requires the pixels to be reversed in each byte.
3083 * The 'regular' case requires a mask for each of the first 6 passes,
3084 * the 'display' case does a copy for the even passes in the range
3085 * 0..6. This has already been handled in the test above.
3087 * The masks are arranged as four bytes with the first byte to use in
3088 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3089 * not) of the pixels in each byte.
3091 * NOTE: the whole of this logic depends on the caller of this function
3092 * only calling it on rows appropriate to the pass. This function only
3093 * understands the 'x' logic; the 'y' logic is handled by the caller.
3095 * The following defines allow generation of compile time constant bit
3096 * masks for each pixel depth and each possibility of swapped or not
3097 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3098 * is in the range 0..7; and the result is 1 if the pixel is to be
3099 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3100 * for the block method.
3102 * With some compilers a compile time expression of the general form:
3104 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3106 * Produces warnings with values of 'shift' in the range 33 to 63
3107 * because the right hand side of the ?: expression is evaluated by
3108 * the compiler even though it isn't used. Microsoft Visual C (various
3109 * versions) and the Intel C compiler are known to do this. To avoid
3110 * this the following macros are used in 1.5.6. This is a temporary
3111 * solution to avoid destabilizing the code during the release process.
3113 # if PNG_USE_COMPILE_TIME_MASKS
3114 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3115 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3116 # else
3117 # define PNG_LSR(x,s) ((x)>>(s))
3118 # define PNG_LSL(x,s) ((x)<<(s))
3119 # endif
3120 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3121 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3122 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3123 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3125 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3126 * little endian - the first pixel is at bit 0 - however the extra
3127 * parameter 's' can be set to cause the mask position to be swapped
3128 * within each byte, to match the PNG format. This is done by XOR of
3129 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3131 # define PIXEL_MASK(p,x,d,s) \
3132 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3134 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3136 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3137 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3139 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3140 * cases the result needs replicating, for the 4-bpp case the above
3141 * generates a full 32 bits.
3143 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3145 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3146 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3147 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3149 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3150 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3151 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3153 #if PNG_USE_COMPILE_TIME_MASKS
3154 /* Utility macros to construct all the masks for a depth/swap
3155 * combination. The 's' parameter says whether the format is PNG
3156 * (big endian bytes) or not. Only the three odd-numbered passes are
3157 * required for the display/block algorithm.
3159 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3160 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3162 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3164 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3166 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3167 * then pass:
3169 static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3171 /* Little-endian byte masks for PACKSWAP */
3172 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3173 /* Normal (big-endian byte) masks - PNG format */
3174 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3177 /* display_mask has only three entries for the odd passes, so index by
3178 * pass>>1.
3180 static PNG_CONST png_uint_32 display_mask[2][3][3] =
3182 /* Little-endian byte masks for PACKSWAP */
3183 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3184 /* Normal (big-endian byte) masks - PNG format */
3185 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3188 # define MASK(pass,depth,display,png)\
3189 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3190 row_mask[png][DEPTH_INDEX(depth)][pass])
3192 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3193 /* This is the runtime alternative: it seems unlikely that this will
3194 * ever be either smaller or faster than the compile time approach.
3196 # define MASK(pass,depth,display,png)\
3197 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3198 #endif /* !USE_COMPILE_TIME_MASKS */
3200 /* Use the appropriate mask to copy the required bits. In some cases
3201 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3202 * the number of pixels, but the code copies bytes, so it is necessary
3203 * to special case the end.
3205 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3206 png_uint_32 mask;
3208 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3209 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3210 mask = MASK(pass, pixel_depth, display, 0);
3212 else
3213 # endif
3214 mask = MASK(pass, pixel_depth, display, 1);
3216 for (;;)
3218 png_uint_32 m;
3220 /* It doesn't matter in the following if png_uint_32 has more than
3221 * 32 bits because the high bits always match those in m<<24; it is,
3222 * however, essential to use OR here, not +, because of this.
3224 m = mask;
3225 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3226 m &= 0xff;
3228 if (m != 0) /* something to copy */
3230 if (m != 0xff)
3231 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3232 else
3233 *dp = *sp;
3236 /* NOTE: this may overwrite the last byte with garbage if the image
3237 * is not an exact number of bytes wide; libpng has always done
3238 * this.
3240 if (row_width <= pixels_per_byte)
3241 break; /* May need to restore part of the last byte */
3243 row_width -= pixels_per_byte;
3244 ++dp;
3245 ++sp;
3249 else /* pixel_depth >= 8 */
3251 unsigned int bytes_to_copy, bytes_to_jump;
3253 /* Validate the depth - it must be a multiple of 8 */
3254 if (pixel_depth & 7)
3255 png_error(png_ptr, "invalid user transform pixel depth");
3257 pixel_depth >>= 3; /* now in bytes */
3258 row_width *= pixel_depth;
3260 /* Regardless of pass number the Adam 7 interlace always results in a
3261 * fixed number of pixels to copy then to skip. There may be a
3262 * different number of pixels to skip at the start though.
3265 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3267 row_width -= offset;
3268 dp += offset;
3269 sp += offset;
3272 /* Work out the bytes to copy. */
3273 if (display != 0)
3275 /* When doing the 'block' algorithm the pixel in the pass gets
3276 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3277 * passes are skipped above - the entire expanded row is copied.
3279 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3281 /* But don't allow this number to exceed the actual row width. */
3282 if (bytes_to_copy > row_width)
3283 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3286 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3287 bytes_to_copy = pixel_depth;
3289 /* In Adam7 there is a constant offset between where the pixels go. */
3290 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3292 /* And simply copy these bytes. Some optimization is possible here,
3293 * depending on the value of 'bytes_to_copy'. Special case the low
3294 * byte counts, which we know to be frequent.
3296 * Notice that these cases all 'return' rather than 'break' - this
3297 * avoids an unnecessary test on whether to restore the last byte
3298 * below.
3300 switch (bytes_to_copy)
3302 case 1:
3303 for (;;)
3305 *dp = *sp;
3307 if (row_width <= bytes_to_jump)
3308 return;
3310 dp += bytes_to_jump;
3311 sp += bytes_to_jump;
3312 row_width -= bytes_to_jump;
3315 case 2:
3316 /* There is a possibility of a partial copy at the end here; this
3317 * slows the code down somewhat.
3321 dp[0] = sp[0], dp[1] = sp[1];
3323 if (row_width <= bytes_to_jump)
3324 return;
3326 sp += bytes_to_jump;
3327 dp += bytes_to_jump;
3328 row_width -= bytes_to_jump;
3330 while (row_width > 1);
3332 /* And there can only be one byte left at this point: */
3333 *dp = *sp;
3334 return;
3336 case 3:
3337 /* This can only be the RGB case, so each copy is exactly one
3338 * pixel and it is not necessary to check for a partial copy.
3340 for (;;)
3342 dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
3344 if (row_width <= bytes_to_jump)
3345 return;
3347 sp += bytes_to_jump;
3348 dp += bytes_to_jump;
3349 row_width -= bytes_to_jump;
3352 default:
3353 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3354 /* Check for double byte alignment and, if possible, use a
3355 * 16-bit copy. Don't attempt this for narrow images - ones that
3356 * are less than an interlace panel wide. Don't attempt it for
3357 * wide bytes_to_copy either - use the memcpy there.
3359 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3360 png_isaligned(dp, png_uint_16) &&
3361 png_isaligned(sp, png_uint_16) &&
3362 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3363 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3365 /* Everything is aligned for png_uint_16 copies, but try for
3366 * png_uint_32 first.
3368 if (png_isaligned(dp, png_uint_32) != 0 &&
3369 png_isaligned(sp, png_uint_32) != 0 &&
3370 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3371 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3373 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3374 png_const_uint_32p sp32 = png_aligncastconst(
3375 png_const_uint_32p, sp);
3376 size_t skip = (bytes_to_jump-bytes_to_copy) /
3377 (sizeof (png_uint_32));
3381 size_t c = bytes_to_copy;
3384 *dp32++ = *sp32++;
3385 c -= (sizeof (png_uint_32));
3387 while (c > 0);
3389 if (row_width <= bytes_to_jump)
3390 return;
3392 dp32 += skip;
3393 sp32 += skip;
3394 row_width -= bytes_to_jump;
3396 while (bytes_to_copy <= row_width);
3398 /* Get to here when the row_width truncates the final copy.
3399 * There will be 1-3 bytes left to copy, so don't try the
3400 * 16-bit loop below.
3402 dp = (png_bytep)dp32;
3403 sp = (png_const_bytep)sp32;
3405 *dp++ = *sp++;
3406 while (--row_width > 0);
3407 return;
3410 /* Else do it in 16-bit quantities, but only if the size is
3411 * not too large.
3413 else
3415 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3416 png_const_uint_16p sp16 = png_aligncastconst(
3417 png_const_uint_16p, sp);
3418 size_t skip = (bytes_to_jump-bytes_to_copy) /
3419 (sizeof (png_uint_16));
3423 size_t c = bytes_to_copy;
3426 *dp16++ = *sp16++;
3427 c -= (sizeof (png_uint_16));
3429 while (c > 0);
3431 if (row_width <= bytes_to_jump)
3432 return;
3434 dp16 += skip;
3435 sp16 += skip;
3436 row_width -= bytes_to_jump;
3438 while (bytes_to_copy <= row_width);
3440 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3441 dp = (png_bytep)dp16;
3442 sp = (png_const_bytep)sp16;
3444 *dp++ = *sp++;
3445 while (--row_width > 0);
3446 return;
3449 #endif /* ALIGN_TYPE code */
3451 /* The true default - use a memcpy: */
3452 for (;;)
3454 memcpy(dp, sp, bytes_to_copy);
3456 if (row_width <= bytes_to_jump)
3457 return;
3459 sp += bytes_to_jump;
3460 dp += bytes_to_jump;
3461 row_width -= bytes_to_jump;
3462 if (bytes_to_copy > row_width)
3463 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3467 /* NOT REACHED*/
3468 } /* pixel_depth >= 8 */
3470 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3472 else
3473 #endif /* READ_INTERLACING */
3475 /* If here then the switch above wasn't used so just memcpy the whole row
3476 * from the temporary row buffer (notice that this overwrites the end of the
3477 * destination row if it is a partial byte.)
3479 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3481 /* Restore the overwritten bits from the last byte if necessary. */
3482 if (end_ptr != NULL)
3483 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3486 #ifdef PNG_READ_INTERLACING_SUPPORTED
3487 void /* PRIVATE */
3488 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3489 png_uint_32 transformations /* Because these may affect the byte layout */)
3491 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3492 /* Offset to next interlace block */
3493 static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3495 png_debug(1, "in png_do_read_interlace");
3496 if (row != NULL && row_info != NULL)
3498 png_uint_32 final_width;
3500 final_width = row_info->width * png_pass_inc[pass];
3502 switch (row_info->pixel_depth)
3504 case 1:
3506 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
3507 png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
3508 int sshift, dshift;
3509 int s_start, s_end, s_inc;
3510 int jstop = png_pass_inc[pass];
3511 png_byte v;
3512 png_uint_32 i;
3513 int j;
3515 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3516 if ((transformations & PNG_PACKSWAP) != 0)
3518 sshift = (int)((row_info->width + 7) & 0x07);
3519 dshift = (int)((final_width + 7) & 0x07);
3520 s_start = 7;
3521 s_end = 0;
3522 s_inc = -1;
3525 else
3526 #endif
3528 sshift = 7 - (int)((row_info->width + 7) & 0x07);
3529 dshift = 7 - (int)((final_width + 7) & 0x07);
3530 s_start = 0;
3531 s_end = 7;
3532 s_inc = 1;
3535 for (i = 0; i < row_info->width; i++)
3537 v = (png_byte)((*sp >> sshift) & 0x01);
3538 for (j = 0; j < jstop; j++)
3540 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3541 tmp |= v << dshift;
3542 *dp = (png_byte)(tmp & 0xff);
3544 if (dshift == s_end)
3546 dshift = s_start;
3547 dp--;
3550 else
3551 dshift += s_inc;
3554 if (sshift == s_end)
3556 sshift = s_start;
3557 sp--;
3560 else
3561 sshift += s_inc;
3563 break;
3566 case 2:
3568 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3569 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3570 int sshift, dshift;
3571 int s_start, s_end, s_inc;
3572 int jstop = png_pass_inc[pass];
3573 png_uint_32 i;
3575 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3576 if ((transformations & PNG_PACKSWAP) != 0)
3578 sshift = (int)(((row_info->width + 3) & 0x03) << 1);
3579 dshift = (int)(((final_width + 3) & 0x03) << 1);
3580 s_start = 6;
3581 s_end = 0;
3582 s_inc = -2;
3585 else
3586 #endif
3588 sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
3589 dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
3590 s_start = 0;
3591 s_end = 6;
3592 s_inc = 2;
3595 for (i = 0; i < row_info->width; i++)
3597 png_byte v;
3598 int j;
3600 v = (png_byte)((*sp >> sshift) & 0x03);
3601 for (j = 0; j < jstop; j++)
3603 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3604 tmp |= v << dshift;
3605 *dp = (png_byte)(tmp & 0xff);
3607 if (dshift == s_end)
3609 dshift = s_start;
3610 dp--;
3613 else
3614 dshift += s_inc;
3617 if (sshift == s_end)
3619 sshift = s_start;
3620 sp--;
3623 else
3624 sshift += s_inc;
3626 break;
3629 case 4:
3631 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
3632 png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
3633 int sshift, dshift;
3634 int s_start, s_end, s_inc;
3635 png_uint_32 i;
3636 int jstop = png_pass_inc[pass];
3638 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3639 if ((transformations & PNG_PACKSWAP) != 0)
3641 sshift = (int)(((row_info->width + 1) & 0x01) << 2);
3642 dshift = (int)(((final_width + 1) & 0x01) << 2);
3643 s_start = 4;
3644 s_end = 0;
3645 s_inc = -4;
3648 else
3649 #endif
3651 sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
3652 dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
3653 s_start = 0;
3654 s_end = 4;
3655 s_inc = 4;
3658 for (i = 0; i < row_info->width; i++)
3660 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
3661 int j;
3663 for (j = 0; j < jstop; j++)
3665 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
3666 tmp |= v << dshift;
3667 *dp = (png_byte)(tmp & 0xff);
3669 if (dshift == s_end)
3671 dshift = s_start;
3672 dp--;
3675 else
3676 dshift += s_inc;
3679 if (sshift == s_end)
3681 sshift = s_start;
3682 sp--;
3685 else
3686 sshift += s_inc;
3688 break;
3691 default:
3693 png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
3695 png_bytep sp = row + (png_size_t)(row_info->width - 1)
3696 * pixel_bytes;
3698 png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
3700 int jstop = png_pass_inc[pass];
3701 png_uint_32 i;
3703 for (i = 0; i < row_info->width; i++)
3705 png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
3706 int j;
3708 memcpy(v, sp, pixel_bytes);
3710 for (j = 0; j < jstop; j++)
3712 memcpy(dp, v, pixel_bytes);
3713 dp -= pixel_bytes;
3716 sp -= pixel_bytes;
3718 break;
3722 row_info->width = final_width;
3723 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
3725 #ifndef PNG_READ_PACKSWAP_SUPPORTED
3726 PNG_UNUSED(transformations) /* Silence compiler warning */
3727 #endif
3729 #endif /* READ_INTERLACING */
3731 static void
3732 png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
3733 png_const_bytep prev_row)
3735 png_size_t i;
3736 png_size_t istop = row_info->rowbytes;
3737 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3738 png_bytep rp = row + bpp;
3740 PNG_UNUSED(prev_row)
3742 for (i = bpp; i < istop; i++)
3744 *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
3745 rp++;
3749 static void
3750 png_read_filter_row_up(png_row_infop row_info, png_bytep row,
3751 png_const_bytep prev_row)
3753 png_size_t i;
3754 png_size_t istop = row_info->rowbytes;
3755 png_bytep rp = row;
3756 png_const_bytep pp = prev_row;
3758 for (i = 0; i < istop; i++)
3760 *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
3761 rp++;
3765 static void
3766 png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
3767 png_const_bytep prev_row)
3769 png_size_t i;
3770 png_bytep rp = row;
3771 png_const_bytep pp = prev_row;
3772 unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
3773 png_size_t istop = row_info->rowbytes - bpp;
3775 for (i = 0; i < bpp; i++)
3777 *rp = (png_byte)(((int)(*rp) +
3778 ((int)(*pp++) / 2 )) & 0xff);
3780 rp++;
3783 for (i = 0; i < istop; i++)
3785 *rp = (png_byte)(((int)(*rp) +
3786 (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
3788 rp++;
3792 static void
3793 png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
3794 png_const_bytep prev_row)
3796 png_bytep rp_end = row + row_info->rowbytes;
3797 int a, c;
3799 /* First pixel/byte */
3800 c = *prev_row++;
3801 a = *row + c;
3802 *row++ = (png_byte)a;
3804 /* Remainder */
3805 while (row < rp_end)
3807 int b, pa, pb, pc, p;
3809 a &= 0xff; /* From previous iteration or start */
3810 b = *prev_row++;
3812 p = b - c;
3813 pc = a - c;
3815 # ifdef PNG_USE_ABS
3816 pa = abs(p);
3817 pb = abs(pc);
3818 pc = abs(p + pc);
3819 # else
3820 pa = p < 0 ? -p : p;
3821 pb = pc < 0 ? -pc : pc;
3822 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3823 # endif
3825 /* Find the best predictor, the least of pa, pb, pc favoring the earlier
3826 * ones in the case of a tie.
3828 if (pb < pa) pa = pb, a = b;
3829 if (pc < pa) a = c;
3831 /* Calculate the current pixel in a, and move the previous row pixel to c
3832 * for the next time round the loop
3834 c = b;
3835 a += *row;
3836 *row++ = (png_byte)a;
3840 static void
3841 png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
3842 png_const_bytep prev_row)
3844 int bpp = (row_info->pixel_depth + 7) >> 3;
3845 png_bytep rp_end = row + bpp;
3847 /* Process the first pixel in the row completely (this is the same as 'up'
3848 * because there is only one candidate predictor for the first row).
3850 while (row < rp_end)
3852 int a = *row + *prev_row++;
3853 *row++ = (png_byte)a;
3856 /* Remainder */
3857 rp_end += row_info->rowbytes - bpp;
3859 while (row < rp_end)
3861 int a, b, c, pa, pb, pc, p;
3863 c = *(prev_row - bpp);
3864 a = *(row - bpp);
3865 b = *prev_row++;
3867 p = b - c;
3868 pc = a - c;
3870 # ifdef PNG_USE_ABS
3871 pa = abs(p);
3872 pb = abs(pc);
3873 pc = abs(p + pc);
3874 # else
3875 pa = p < 0 ? -p : p;
3876 pb = pc < 0 ? -pc : pc;
3877 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
3878 # endif
3880 if (pb < pa) pa = pb, a = b;
3881 if (pc < pa) a = c;
3883 a += *row;
3884 *row++ = (png_byte)a;
3888 static void
3889 png_init_filter_functions(png_structrp pp)
3890 /* This function is called once for every PNG image (except for PNG images
3891 * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
3892 * implementations required to reverse the filtering of PNG rows. Reversing
3893 * the filter is the first transformation performed on the row data. It is
3894 * performed in place, therefore an implementation can be selected based on
3895 * the image pixel format. If the implementation depends on image width then
3896 * take care to ensure that it works correctly if the image is interlaced -
3897 * interlacing causes the actual row width to vary.
3900 unsigned int bpp = (pp->pixel_depth + 7) >> 3;
3902 pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
3903 pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
3904 pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
3905 if (bpp == 1)
3906 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3907 png_read_filter_row_paeth_1byte_pixel;
3908 else
3909 pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
3910 png_read_filter_row_paeth_multibyte_pixel;
3912 #ifdef PNG_FILTER_OPTIMIZATIONS
3913 /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to
3914 * call to install hardware optimizations for the above functions; simply
3915 * replace whatever elements of the pp->read_filter[] array with a hardware
3916 * specific (or, for that matter, generic) optimization.
3918 * To see an example of this examine what configure.ac does when
3919 * --enable-arm-neon is specified on the command line.
3921 PNG_FILTER_OPTIMIZATIONS(pp, bpp);
3922 #endif
3925 void /* PRIVATE */
3926 png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
3927 png_const_bytep prev_row, int filter)
3929 /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define
3930 * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic
3931 * implementations. See png_init_filter_functions above.
3933 if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
3935 if (pp->read_filter[0] == NULL)
3936 png_init_filter_functions(pp);
3938 pp->read_filter[filter-1](row_info, row, prev_row);
3942 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
3943 void /* PRIVATE */
3944 png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
3945 png_alloc_size_t avail_out)
3947 /* Loop reading IDATs and decompressing the result into output[avail_out] */
3948 png_ptr->zstream.next_out = output;
3949 png_ptr->zstream.avail_out = 0; /* safety: set below */
3951 if (output == NULL)
3952 avail_out = 0;
3956 int ret;
3957 png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
3959 if (png_ptr->zstream.avail_in == 0)
3961 uInt avail_in;
3962 png_bytep buffer;
3964 while (png_ptr->idat_size == 0)
3966 png_crc_finish(png_ptr, 0);
3968 png_ptr->idat_size = png_read_chunk_header(png_ptr);
3969 /* This is an error even in the 'check' case because the code just
3970 * consumed a non-IDAT header.
3972 if (png_ptr->chunk_name != png_IDAT)
3973 png_error(png_ptr, "Not enough image data");
3976 avail_in = png_ptr->IDAT_read_size;
3978 if (avail_in > png_ptr->idat_size)
3979 avail_in = (uInt)png_ptr->idat_size;
3981 /* A PNG with a gradually increasing IDAT size will defeat this attempt
3982 * to minimize memory usage by causing lots of re-allocs, but
3983 * realistically doing IDAT_read_size re-allocs is not likely to be a
3984 * big problem.
3986 buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);
3988 png_crc_read(png_ptr, buffer, avail_in);
3989 png_ptr->idat_size -= avail_in;
3991 png_ptr->zstream.next_in = buffer;
3992 png_ptr->zstream.avail_in = avail_in;
3995 /* And set up the output side. */
3996 if (output != NULL) /* standard read */
3998 uInt out = ZLIB_IO_MAX;
4000 if (out > avail_out)
4001 out = (uInt)avail_out;
4003 avail_out -= out;
4004 png_ptr->zstream.avail_out = out;
4007 else /* after last row, checking for end */
4009 png_ptr->zstream.next_out = tmpbuf;
4010 png_ptr->zstream.avail_out = (sizeof tmpbuf);
4013 /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4014 * process. If the LZ stream is truncated the sequential reader will
4015 * terminally damage the stream, above, by reading the chunk header of the
4016 * following chunk (it then exits with png_error).
4018 * TODO: deal more elegantly with truncated IDAT lists.
4020 ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
4022 /* Take the unconsumed output back. */
4023 if (output != NULL)
4024 avail_out += png_ptr->zstream.avail_out;
4026 else /* avail_out counts the extra bytes */
4027 avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4029 png_ptr->zstream.avail_out = 0;
4031 if (ret == Z_STREAM_END)
4033 /* Do this for safety; we won't read any more into this row. */
4034 png_ptr->zstream.next_out = NULL;
4036 png_ptr->mode |= PNG_AFTER_IDAT;
4037 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4039 if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4040 png_chunk_benign_error(png_ptr, "Extra compressed data");
4041 break;
4044 if (ret != Z_OK)
4046 png_zstream_error(png_ptr, ret);
4048 if (output != NULL)
4049 png_chunk_error(png_ptr, png_ptr->zstream.msg);
4051 else /* checking */
4053 png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4054 return;
4057 } while (avail_out > 0);
4059 if (avail_out > 0)
4061 /* The stream ended before the image; this is the same as too few IDATs so
4062 * should be handled the same way.
4064 if (output != NULL)
4065 png_error(png_ptr, "Not enough image data");
4067 else /* the deflate stream contained extra data */
4068 png_chunk_benign_error(png_ptr, "Too much image data");
4072 void /* PRIVATE */
4073 png_read_finish_IDAT(png_structrp png_ptr)
4075 /* We don't need any more data and the stream should have ended, however the
4076 * LZ end code may actually not have been processed. In this case we must
4077 * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4078 * may still remain to be consumed.
4080 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4082 /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4083 * the compressed stream, but the stream may be damaged too, so even after
4084 * this call we may need to terminate the zstream ownership.
4086 png_read_IDAT_data(png_ptr, NULL, 0);
4087 png_ptr->zstream.next_out = NULL; /* safety */
4089 /* Now clear everything out for safety; the following may not have been
4090 * done.
4092 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4094 png_ptr->mode |= PNG_AFTER_IDAT;
4095 png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4099 /* If the zstream has not been released do it now *and* terminate the reading
4100 * of the final IDAT chunk.
4102 if (png_ptr->zowner == png_IDAT)
4104 /* Always do this; the pointers otherwise point into the read buffer. */
4105 png_ptr->zstream.next_in = NULL;
4106 png_ptr->zstream.avail_in = 0;
4108 /* Now we no longer own the zstream. */
4109 png_ptr->zowner = 0;
4111 /* The slightly weird semantics of the sequential IDAT reading is that we
4112 * are always in or at the end of an IDAT chunk, so we always need to do a
4113 * crc_finish here. If idat_size is non-zero we also need to read the
4114 * spurious bytes at the end of the chunk now.
4116 (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4120 void /* PRIVATE */
4121 png_read_finish_row(png_structrp png_ptr)
4123 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4125 /* Start of interlace block */
4126 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4128 /* Offset to next interlace block */
4129 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4131 /* Start of interlace block in the y direction */
4132 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4134 /* Offset to next interlace block in the y direction */
4135 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4137 png_debug(1, "in png_read_finish_row");
4138 png_ptr->row_number++;
4139 if (png_ptr->row_number < png_ptr->num_rows)
4140 return;
4142 if (png_ptr->interlaced != 0)
4144 png_ptr->row_number = 0;
4146 /* TO DO: don't do this if prev_row isn't needed (requires
4147 * read-ahead of the next row's filter byte.
4149 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4153 png_ptr->pass++;
4155 if (png_ptr->pass >= 7)
4156 break;
4158 png_ptr->iwidth = (png_ptr->width +
4159 png_pass_inc[png_ptr->pass] - 1 -
4160 png_pass_start[png_ptr->pass]) /
4161 png_pass_inc[png_ptr->pass];
4163 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4165 png_ptr->num_rows = (png_ptr->height +
4166 png_pass_yinc[png_ptr->pass] - 1 -
4167 png_pass_ystart[png_ptr->pass]) /
4168 png_pass_yinc[png_ptr->pass];
4171 else /* if (png_ptr->transformations & PNG_INTERLACE) */
4172 break; /* libpng deinterlacing sees every row */
4174 } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4176 if (png_ptr->pass < 7)
4177 return;
4180 /* Here after at the end of the last row of the last pass. */
4181 png_read_finish_IDAT(png_ptr);
4183 #endif /* SEQUENTIAL_READ */
4185 void /* PRIVATE */
4186 png_read_start_row(png_structrp png_ptr)
4188 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4190 /* Start of interlace block */
4191 static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
4193 /* Offset to next interlace block */
4194 static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
4196 /* Start of interlace block in the y direction */
4197 static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
4199 /* Offset to next interlace block in the y direction */
4200 static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
4202 int max_pixel_depth;
4203 png_size_t row_bytes;
4205 png_debug(1, "in png_read_start_row");
4207 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
4208 png_init_read_transformations(png_ptr);
4209 #endif
4210 if (png_ptr->interlaced != 0)
4212 if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4213 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4214 png_pass_ystart[0]) / png_pass_yinc[0];
4216 else
4217 png_ptr->num_rows = png_ptr->height;
4219 png_ptr->iwidth = (png_ptr->width +
4220 png_pass_inc[png_ptr->pass] - 1 -
4221 png_pass_start[png_ptr->pass]) /
4222 png_pass_inc[png_ptr->pass];
4225 else
4227 png_ptr->num_rows = png_ptr->height;
4228 png_ptr->iwidth = png_ptr->width;
4231 max_pixel_depth = png_ptr->pixel_depth;
4233 /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4234 * calculations to calculate the final pixel depth, then
4235 * png_do_read_transforms actually does the transforms. This means that the
4236 * code which effectively calculates this value is actually repeated in three
4237 * separate places. They must all match. Innocent changes to the order of
4238 * transformations can and will break libpng in a way that causes memory
4239 * overwrites.
4241 * TODO: fix this.
4243 #ifdef PNG_READ_PACK_SUPPORTED
4244 if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4245 max_pixel_depth = 8;
4246 #endif
4248 #ifdef PNG_READ_EXPAND_SUPPORTED
4249 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4251 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4253 if (png_ptr->num_trans != 0)
4254 max_pixel_depth = 32;
4256 else
4257 max_pixel_depth = 24;
4260 else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4262 if (max_pixel_depth < 8)
4263 max_pixel_depth = 8;
4265 if (png_ptr->num_trans != 0)
4266 max_pixel_depth *= 2;
4269 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4271 if (png_ptr->num_trans != 0)
4273 max_pixel_depth *= 4;
4274 max_pixel_depth /= 3;
4278 #endif
4280 #ifdef PNG_READ_EXPAND_16_SUPPORTED
4281 if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4283 # ifdef PNG_READ_EXPAND_SUPPORTED
4284 /* In fact it is an error if it isn't supported, but checking is
4285 * the safe way.
4287 if ((png_ptr->transformations & PNG_EXPAND) != 0)
4289 if (png_ptr->bit_depth < 16)
4290 max_pixel_depth *= 2;
4292 else
4293 # endif
4294 png_ptr->transformations &= ~PNG_EXPAND_16;
4296 #endif
4298 #ifdef PNG_READ_FILLER_SUPPORTED
4299 if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4301 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4303 if (max_pixel_depth <= 8)
4304 max_pixel_depth = 16;
4306 else
4307 max_pixel_depth = 32;
4310 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4311 png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4313 if (max_pixel_depth <= 32)
4314 max_pixel_depth = 32;
4316 else
4317 max_pixel_depth = 64;
4320 #endif
4322 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4323 if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4325 if (
4326 #ifdef PNG_READ_EXPAND_SUPPORTED
4327 (png_ptr->num_trans != 0 &&
4328 (png_ptr->transformations & PNG_EXPAND) != 0) ||
4329 #endif
4330 #ifdef PNG_READ_FILLER_SUPPORTED
4331 (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4332 #endif
4333 png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4335 if (max_pixel_depth <= 16)
4336 max_pixel_depth = 32;
4338 else
4339 max_pixel_depth = 64;
4342 else
4344 if (max_pixel_depth <= 8)
4346 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4347 max_pixel_depth = 32;
4349 else
4350 max_pixel_depth = 24;
4353 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4354 max_pixel_depth = 64;
4356 else
4357 max_pixel_depth = 48;
4360 #endif
4362 #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4363 defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4364 if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4366 int user_pixel_depth = png_ptr->user_transform_depth *
4367 png_ptr->user_transform_channels;
4369 if (user_pixel_depth > max_pixel_depth)
4370 max_pixel_depth = user_pixel_depth;
4372 #endif
4374 /* This value is stored in png_struct and double checked in the row read
4375 * code.
4377 png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4378 png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4380 /* Align the width on the next larger 8 pixels. Mainly used
4381 * for interlacing
4383 row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4384 /* Calculate the maximum bytes needed, adding a byte and a pixel
4385 * for safety's sake
4387 row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4388 1 + ((max_pixel_depth + 7) >> 3);
4390 #ifdef PNG_MAX_MALLOC_64K
4391 if (row_bytes > (png_uint_32)65536L)
4392 png_error(png_ptr, "This image requires a row greater than 64KB");
4393 #endif
4395 if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4397 png_free(png_ptr, png_ptr->big_row_buf);
4398 png_free(png_ptr, png_ptr->big_prev_row);
4400 if (png_ptr->interlaced != 0)
4401 png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4402 row_bytes + 48);
4404 else
4405 png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4407 png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4409 #ifdef PNG_ALIGNED_MEMORY_SUPPORTED
4410 /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4411 * of padding before and after row_buf; treat prev_row similarly.
4412 * NOTE: the alignment is to the start of the pixels, one beyond the start
4413 * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this
4414 * was incorrect; the filter byte was aligned, which had the exact
4415 * opposite effect of that intended.
4418 png_bytep temp = png_ptr->big_row_buf + 32;
4419 int extra = (int)((temp - (png_bytep)0) & 0x0f);
4420 png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4422 temp = png_ptr->big_prev_row + 32;
4423 extra = (int)((temp - (png_bytep)0) & 0x0f);
4424 png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4427 #else
4428 /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4429 png_ptr->row_buf = png_ptr->big_row_buf + 31;
4430 png_ptr->prev_row = png_ptr->big_prev_row + 31;
4431 #endif
4432 png_ptr->old_big_row_buf_size = row_bytes + 48;
4435 #ifdef PNG_MAX_MALLOC_64K
4436 if (png_ptr->rowbytes > 65535)
4437 png_error(png_ptr, "This image requires a row greater than 64KB");
4439 #endif
4440 if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4441 png_error(png_ptr, "Row has too many bytes to allocate in memory");
4443 memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4445 png_debug1(3, "width = %u,", png_ptr->width);
4446 png_debug1(3, "height = %u,", png_ptr->height);
4447 png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4448 png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4449 png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4450 png_debug1(3, "irowbytes = %lu",
4451 (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4453 /* The sequential reader needs a buffer for IDAT, but the progressive reader
4454 * does not, so free the read buffer now regardless; the sequential reader
4455 * reallocates it on demand.
4457 if (png_ptr->read_buffer != 0)
4459 png_bytep buffer = png_ptr->read_buffer;
4461 png_ptr->read_buffer_size = 0;
4462 png_ptr->read_buffer = NULL;
4463 png_free(png_ptr, buffer);
4466 /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4467 * value from the stream (note that this will result in a fatal error if the
4468 * IDAT stream has a bogus deflate header window_bits value, but this should
4469 * not be happening any longer!)
4471 if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4472 png_error(png_ptr, png_ptr->zstream.msg);
4474 png_ptr->flags |= PNG_FLAG_ROW_INIT;
4476 #endif /* READ */