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