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