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