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