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