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