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