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