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