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