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