ee584a8c406383970396d15acab052fd76fefac6
[reactos.git] / reactos / dll / 3rdparty / libpng / pngrutil.c
1
2 /* pngrutil.c - utilities to read a PNG file
3 *
4 * Last changed in libpng 1.6.19 [November 12, 2015]
5 * Copyright (c) 1998-2015 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
8 *
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
12 *
13 * This file contains routines that are only called from within
14 * libpng itself during the course of reading an image.
15 */
16
17 #include "pngpriv.h"
18
19 #ifdef PNG_READ_SUPPORTED
20
21 png_uint_32 PNGAPI
22 png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
23 {
24 png_uint_32 uval = png_get_uint_32(buf);
25
26 if (uval > PNG_UINT_31_MAX)
27 png_error(png_ptr, "PNG unsigned integer out of range");
28
29 return (uval);
30 }
31
32 #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED)
33 /* The following is a variation on the above for use with the fixed
34 * point values used for gAMA and cHRM. Instead of png_error it
35 * issues a warning and returns (-1) - an invalid value because both
36 * gAMA and cHRM use *unsigned* integers for fixed point values.
37 */
38 #define PNG_FIXED_ERROR (-1)
39
40 static png_fixed_point /* PRIVATE */
41 png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf)
42 {
43 png_uint_32 uval = png_get_uint_32(buf);
44
45 if (uval <= PNG_UINT_31_MAX)
46 return (png_fixed_point)uval; /* known to be in range */
47
48 /* The caller can turn off the warning by passing NULL. */
49 if (png_ptr != NULL)
50 png_warning(png_ptr, "PNG fixed point integer out of range");
51
52 return PNG_FIXED_ERROR;
53 }
54 #endif
55
56 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
57 /* NOTE: the read macros will obscure these definitions, so that if
58 * PNG_USE_READ_MACROS is set the library will not use them internally,
59 * but the APIs will still be available externally.
60 *
61 * The parentheses around "PNGAPI function_name" in the following three
62 * functions are necessary because they allow the macros to co-exist with
63 * these (unused but exported) functions.
64 */
65
66 /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
67 png_uint_32 (PNGAPI
68 png_get_uint_32)(png_const_bytep buf)
69 {
70 png_uint_32 uval =
71 ((png_uint_32)(*(buf )) << 24) +
72 ((png_uint_32)(*(buf + 1)) << 16) +
73 ((png_uint_32)(*(buf + 2)) << 8) +
74 ((png_uint_32)(*(buf + 3)) ) ;
75
76 return uval;
77 }
78
79 /* Grab a signed 32-bit integer from a buffer in big-endian format. The
80 * data is stored in the PNG file in two's complement format and there
81 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
82 * the following code does a two's complement to native conversion.
83 */
84 png_int_32 (PNGAPI
85 png_get_int_32)(png_const_bytep buf)
86 {
87 png_uint_32 uval = png_get_uint_32(buf);
88 if ((uval & 0x80000000) == 0) /* non-negative */
89 return uval;
90
91 uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */
92 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. */
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 */
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 */
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 */
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 */
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 */
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
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
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 PNG_ZLIB_VERNUM >= 0x1240
374
375 # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW)
376 int window_bits;
377
378 if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
379 PNG_OPTION_ON)
380 window_bits = 15;
381
382 else
383 window_bits = 0;
384 # else
385 # define window_bits 0
386 # endif
387 #endif
388
389 /* Set this for safety, just in case the previous owner left pointers to
390 * memory allocations.
391 */
392 png_ptr->zstream.next_in = NULL;
393 png_ptr->zstream.avail_in = 0;
394 png_ptr->zstream.next_out = NULL;
395 png_ptr->zstream.avail_out = 0;
396
397 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
398 {
399 #if PNG_ZLIB_VERNUM < 0x1240
400 ret = inflateReset(&png_ptr->zstream);
401 #else
402 ret = inflateReset2(&png_ptr->zstream, window_bits);
403 #endif
404 }
405
406 else
407 {
408 #if PNG_ZLIB_VERNUM < 0x1240
409 ret = inflateInit(&png_ptr->zstream);
410 #else
411 ret = inflateInit2(&png_ptr->zstream, window_bits);
412 #endif
413
414 if (ret == Z_OK)
415 png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
416 }
417
418 if (ret == Z_OK)
419 png_ptr->zowner = owner;
420
421 else
422 png_zstream_error(png_ptr, ret);
423
424 return ret;
425 }
426
427 #ifdef window_bits
428 # undef window_bits
429 #endif
430 }
431
432 #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
433 /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
434 * allow the caller to do multiple calls if required. If the 'finish' flag is
435 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
436 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
437 * Z_OK or Z_STREAM_END will be returned on success.
438 *
439 * The input and output sizes are updated to the actual amounts of data consumed
440 * or written, not the amount available (as in a z_stream). The data pointers
441 * are not changed, so the next input is (data+input_size) and the next
442 * available output is (output+output_size).
443 */
444 static int
445 png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
446 /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
447 /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
448 {
449 if (png_ptr->zowner == owner) /* Else not claimed */
450 {
451 int ret;
452 png_alloc_size_t avail_out = *output_size_ptr;
453 png_uint_32 avail_in = *input_size_ptr;
454
455 /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
456 * can't even necessarily handle 65536 bytes) because the type uInt is
457 * "16 bits or more". Consequently it is necessary to chunk the input to
458 * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
459 * maximum value that can be stored in a uInt.) It is possible to set
460 * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
461 * a performance advantage, because it reduces the amount of data accessed
462 * at each step and that may give the OS more time to page it in.
463 */
464 png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
465 /* avail_in and avail_out are set below from 'size' */
466 png_ptr->zstream.avail_in = 0;
467 png_ptr->zstream.avail_out = 0;
468
469 /* Read directly into the output if it is available (this is set to
470 * a local buffer below if output is NULL).
471 */
472 if (output != NULL)
473 png_ptr->zstream.next_out = output;
474
475 do
476 {
477 uInt avail;
478 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
479
480 /* zlib INPUT BUFFER */
481 /* The setting of 'avail_in' used to be outside the loop; by setting it
482 * inside it is possible to chunk the input to zlib and simply rely on
483 * zlib to advance the 'next_in' pointer. This allows arbitrary
484 * amounts of data to be passed through zlib at the unavoidable cost of
485 * requiring a window save (memcpy of up to 32768 output bytes)
486 * every ZLIB_IO_MAX input bytes.
487 */
488 avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
489
490 avail = ZLIB_IO_MAX;
491
492 if (avail_in < avail)
493 avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
494
495 avail_in -= avail;
496 png_ptr->zstream.avail_in = avail;
497
498 /* zlib OUTPUT BUFFER */
499 avail_out += png_ptr->zstream.avail_out; /* not written last time */
500
501 avail = ZLIB_IO_MAX; /* maximum zlib can process */
502
503 if (output == NULL)
504 {
505 /* Reset the output buffer each time round if output is NULL and
506 * make available the full buffer, up to 'remaining_space'
507 */
508 png_ptr->zstream.next_out = local_buffer;
509 if ((sizeof local_buffer) < avail)
510 avail = (sizeof local_buffer);
511 }
512
513 if (avail_out < avail)
514 avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
515
516 png_ptr->zstream.avail_out = avail;
517 avail_out -= avail;
518
519 /* zlib inflate call */
520 /* In fact 'avail_out' may be 0 at this point, that happens at the end
521 * of the read when the final LZ end code was not passed at the end of
522 * the previous chunk of input data. Tell zlib if we have reached the
523 * end of the output buffer.
524 */
525 ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH :
526 (finish ? Z_FINISH : Z_SYNC_FLUSH));
527 } while (ret == Z_OK);
528
529 /* For safety kill the local buffer pointer now */
530 if (output == NULL)
531 png_ptr->zstream.next_out = NULL;
532
533 /* Claw back the 'size' and 'remaining_space' byte counts. */
534 avail_in += png_ptr->zstream.avail_in;
535 avail_out += png_ptr->zstream.avail_out;
536
537 /* Update the input and output sizes; the updated values are the amount
538 * consumed or written, effectively the inverse of what zlib uses.
539 */
540 if (avail_out > 0)
541 *output_size_ptr -= avail_out;
542
543 if (avail_in > 0)
544 *input_size_ptr -= avail_in;
545
546 /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
547 png_zstream_error(png_ptr, ret);
548 return ret;
549 }
550
551 else
552 {
553 /* This is a bad internal error. The recovery assigns to the zstream msg
554 * pointer, which is not owned by the caller, but this is safe; it's only
555 * used on errors!
556 */
557 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
558 return Z_STREAM_ERROR;
559 }
560 }
561
562 /*
563 * Decompress trailing data in a chunk. The assumption is that read_buffer
564 * points at an allocated area holding the contents of a chunk with a
565 * trailing compressed part. What we get back is an allocated area
566 * holding the original prefix part and an uncompressed version of the
567 * trailing part (the malloc area passed in is freed).
568 */
569 static int
570 png_decompress_chunk(png_structrp png_ptr,
571 png_uint_32 chunklength, png_uint_32 prefix_size,
572 png_alloc_size_t *newlength /* must be initialized to the maximum! */,
573 int terminate /*add a '\0' to the end of the uncompressed data*/)
574 {
575 /* TODO: implement different limits for different types of chunk.
576 *
577 * The caller supplies *newlength set to the maximum length of the
578 * uncompressed data, but this routine allocates space for the prefix and
579 * maybe a '\0' terminator too. We have to assume that 'prefix_size' is
580 * limited only by the maximum chunk size.
581 */
582 png_alloc_size_t limit = PNG_SIZE_MAX;
583
584 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
585 if (png_ptr->user_chunk_malloc_max > 0 &&
586 png_ptr->user_chunk_malloc_max < limit)
587 limit = png_ptr->user_chunk_malloc_max;
588 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
589 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
590 limit = PNG_USER_CHUNK_MALLOC_MAX;
591 # endif
592
593 if (limit >= prefix_size + (terminate != 0))
594 {
595 int ret;
596
597 limit -= prefix_size + (terminate != 0);
598
599 if (limit < *newlength)
600 *newlength = limit;
601
602 /* Now try to claim the stream. */
603 ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
604
605 if (ret == Z_OK)
606 {
607 png_uint_32 lzsize = chunklength - prefix_size;
608
609 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
610 /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
611 /* output: */ NULL, newlength);
612
613 if (ret == Z_STREAM_END)
614 {
615 /* Use 'inflateReset' here, not 'inflateReset2' because this
616 * preserves the previously decided window size (otherwise it would
617 * be necessary to store the previous window size.) In practice
618 * this doesn't matter anyway, because png_inflate will call inflate
619 * with Z_FINISH in almost all cases, so the window will not be
620 * maintained.
621 */
622 if (inflateReset(&png_ptr->zstream) == Z_OK)
623 {
624 /* Because of the limit checks above we know that the new,
625 * expanded, size will fit in a size_t (let alone an
626 * png_alloc_size_t). Use png_malloc_base here to avoid an
627 * extra OOM message.
628 */
629 png_alloc_size_t new_size = *newlength;
630 png_alloc_size_t buffer_size = prefix_size + new_size +
631 (terminate != 0);
632 png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
633 buffer_size));
634
635 if (text != NULL)
636 {
637 ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
638 png_ptr->read_buffer + prefix_size, &lzsize,
639 text + prefix_size, newlength);
640
641 if (ret == Z_STREAM_END)
642 {
643 if (new_size == *newlength)
644 {
645 if (terminate != 0)
646 text[prefix_size + *newlength] = 0;
647
648 if (prefix_size > 0)
649 memcpy(text, png_ptr->read_buffer, prefix_size);
650
651 {
652 png_bytep old_ptr = png_ptr->read_buffer;
653
654 png_ptr->read_buffer = text;
655 png_ptr->read_buffer_size = buffer_size;
656 text = old_ptr; /* freed below */
657 }
658 }
659
660 else
661 {
662 /* The size changed on the second read, there can be no
663 * guarantee that anything is correct at this point.
664 * The 'msg' pointer has been set to "unexpected end of
665 * LZ stream", which is fine, but return an error code
666 * that the caller won't accept.
667 */
668 ret = PNG_UNEXPECTED_ZLIB_RETURN;
669 }
670 }
671
672 else if (ret == Z_OK)
673 ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
674
675 /* Free the text pointer (this is the old read_buffer on
676 * success)
677 */
678 png_free(png_ptr, text);
679
680 /* This really is very benign, but it's still an error because
681 * the extra space may otherwise be used as a Trojan Horse.
682 */
683 if (ret == Z_STREAM_END &&
684 chunklength - prefix_size != lzsize)
685 png_chunk_benign_error(png_ptr, "extra compressed data");
686 }
687
688 else
689 {
690 /* Out of memory allocating the buffer */
691 ret = Z_MEM_ERROR;
692 png_zstream_error(png_ptr, Z_MEM_ERROR);
693 }
694 }
695
696 else
697 {
698 /* inflateReset failed, store the error message */
699 png_zstream_error(png_ptr, ret);
700
701 if (ret == Z_STREAM_END)
702 ret = PNG_UNEXPECTED_ZLIB_RETURN;
703 }
704 }
705
706 else if (ret == Z_OK)
707 ret = PNG_UNEXPECTED_ZLIB_RETURN;
708
709 /* Release the claimed stream */
710 png_ptr->zowner = 0;
711 }
712
713 else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
714 ret = PNG_UNEXPECTED_ZLIB_RETURN;
715
716 return ret;
717 }
718
719 else
720 {
721 /* Application/configuration limits exceeded */
722 png_zstream_error(png_ptr, Z_MEM_ERROR);
723 return Z_MEM_ERROR;
724 }
725 }
726 #endif /* READ_COMPRESSED_TEXT */
727
728 #ifdef PNG_READ_iCCP_SUPPORTED
729 /* Perform a partial read and decompress, producing 'avail_out' bytes and
730 * reading from the current chunk as required.
731 */
732 static int
733 png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
734 png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
735 int finish)
736 {
737 if (png_ptr->zowner == png_ptr->chunk_name)
738 {
739 int ret;
740
741 /* next_in and avail_in must have been initialized by the caller. */
742 png_ptr->zstream.next_out = next_out;
743 png_ptr->zstream.avail_out = 0; /* set in the loop */
744
745 do
746 {
747 if (png_ptr->zstream.avail_in == 0)
748 {
749 if (read_size > *chunk_bytes)
750 read_size = (uInt)*chunk_bytes;
751 *chunk_bytes -= read_size;
752
753 if (read_size > 0)
754 png_crc_read(png_ptr, read_buffer, read_size);
755
756 png_ptr->zstream.next_in = read_buffer;
757 png_ptr->zstream.avail_in = read_size;
758 }
759
760 if (png_ptr->zstream.avail_out == 0)
761 {
762 uInt avail = ZLIB_IO_MAX;
763 if (avail > *out_size)
764 avail = (uInt)*out_size;
765 *out_size -= avail;
766
767 png_ptr->zstream.avail_out = avail;
768 }
769
770 /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
771 * the available output is produced; this allows reading of truncated
772 * streams.
773 */
774 ret = inflate(&png_ptr->zstream,
775 *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
776 }
777 while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
778
779 *out_size += png_ptr->zstream.avail_out;
780 png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
781
782 /* Ensure the error message pointer is always set: */
783 png_zstream_error(png_ptr, ret);
784 return ret;
785 }
786
787 else
788 {
789 png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
790 return Z_STREAM_ERROR;
791 }
792 }
793 #endif
794
795 /* Read and check the IDHR chunk */
796
797 void /* PRIVATE */
798 png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
799 {
800 png_byte buf[13];
801 png_uint_32 width, height;
802 int bit_depth, color_type, compression_type, filter_type;
803 int interlace_type;
804
805 png_debug(1, "in png_handle_IHDR");
806
807 if ((png_ptr->mode & PNG_HAVE_IHDR) != 0)
808 png_chunk_error(png_ptr, "out of place");
809
810 /* Check the length */
811 if (length != 13)
812 png_chunk_error(png_ptr, "invalid");
813
814 png_ptr->mode |= PNG_HAVE_IHDR;
815
816 png_crc_read(png_ptr, buf, 13);
817 png_crc_finish(png_ptr, 0);
818
819 width = png_get_uint_31(png_ptr, buf);
820 height = png_get_uint_31(png_ptr, buf + 4);
821 bit_depth = buf[8];
822 color_type = buf[9];
823 compression_type = buf[10];
824 filter_type = buf[11];
825 interlace_type = buf[12];
826
827 /* Set internal variables */
828 png_ptr->width = width;
829 png_ptr->height = height;
830 png_ptr->bit_depth = (png_byte)bit_depth;
831 png_ptr->interlaced = (png_byte)interlace_type;
832 png_ptr->color_type = (png_byte)color_type;
833 #ifdef PNG_MNG_FEATURES_SUPPORTED
834 png_ptr->filter_type = (png_byte)filter_type;
835 #endif
836 png_ptr->compression_type = (png_byte)compression_type;
837
838 /* Find number of channels */
839 switch (png_ptr->color_type)
840 {
841 default: /* invalid, png_set_IHDR calls png_error */
842 case PNG_COLOR_TYPE_GRAY:
843 case PNG_COLOR_TYPE_PALETTE:
844 png_ptr->channels = 1;
845 break;
846
847 case PNG_COLOR_TYPE_RGB:
848 png_ptr->channels = 3;
849 break;
850
851 case PNG_COLOR_TYPE_GRAY_ALPHA:
852 png_ptr->channels = 2;
853 break;
854
855 case PNG_COLOR_TYPE_RGB_ALPHA:
856 png_ptr->channels = 4;
857 break;
858 }
859
860 /* Set up other useful info */
861 png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
862 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
863 png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
864 png_debug1(3, "channels = %d", png_ptr->channels);
865 png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
866 png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
867 color_type, interlace_type, compression_type, filter_type);
868 }
869
870 /* Read and check the palette */
871 void /* PRIVATE */
872 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
873 {
874 png_color palette[PNG_MAX_PALETTE_LENGTH];
875 int max_palette_length, num, i;
876 #ifdef PNG_POINTER_INDEXING_SUPPORTED
877 png_colorp pal_ptr;
878 #endif
879
880 png_debug(1, "in png_handle_PLTE");
881
882 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
883 png_chunk_error(png_ptr, "missing IHDR");
884
885 /* Moved to before the 'after IDAT' check below because otherwise duplicate
886 * PLTE chunks are potentially ignored (the spec says there shall not be more
887 * than one PLTE, the error is not treated as benign, so this check trumps
888 * the requirement that PLTE appears before IDAT.)
889 */
890 else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
891 png_chunk_error(png_ptr, "duplicate");
892
893 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
894 {
895 /* This is benign because the non-benign error happened before, when an
896 * IDAT was encountered in a color-mapped image with no PLTE.
897 */
898 png_crc_finish(png_ptr, length);
899 png_chunk_benign_error(png_ptr, "out of place");
900 return;
901 }
902
903 png_ptr->mode |= PNG_HAVE_PLTE;
904
905 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
906 {
907 png_crc_finish(png_ptr, length);
908 png_chunk_benign_error(png_ptr, "ignored in grayscale PNG");
909 return;
910 }
911
912 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
913 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
914 {
915 png_crc_finish(png_ptr, length);
916 return;
917 }
918 #endif
919
920 if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
921 {
922 png_crc_finish(png_ptr, length);
923
924 if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
925 png_chunk_benign_error(png_ptr, "invalid");
926
927 else
928 png_chunk_error(png_ptr, "invalid");
929
930 return;
931 }
932
933 /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
934 num = (int)length / 3;
935
936 /* If the palette has 256 or fewer entries but is too large for the bit
937 * depth, we don't issue an error, to preserve the behavior of previous
938 * libpng versions. We silently truncate the unused extra palette entries
939 * here.
940 */
941 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
942 max_palette_length = (1 << png_ptr->bit_depth);
943 else
944 max_palette_length = PNG_MAX_PALETTE_LENGTH;
945
946 if (num > max_palette_length)
947 num = max_palette_length;
948
949 #ifdef PNG_POINTER_INDEXING_SUPPORTED
950 for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
951 {
952 png_byte buf[3];
953
954 png_crc_read(png_ptr, buf, 3);
955 pal_ptr->red = buf[0];
956 pal_ptr->green = buf[1];
957 pal_ptr->blue = buf[2];
958 }
959 #else
960 for (i = 0; i < num; i++)
961 {
962 png_byte buf[3];
963
964 png_crc_read(png_ptr, buf, 3);
965 /* Don't depend upon png_color being any order */
966 palette[i].red = buf[0];
967 palette[i].green = buf[1];
968 palette[i].blue = buf[2];
969 }
970 #endif
971
972 /* If we actually need the PLTE chunk (ie for a paletted image), we do
973 * whatever the normal CRC configuration tells us. However, if we
974 * have an RGB image, the PLTE can be considered ancillary, so
975 * we will act as though it is.
976 */
977 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
978 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
979 #endif
980 {
981 png_crc_finish(png_ptr, (int) length - num * 3);
982 }
983
984 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
985 else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */
986 {
987 /* If we don't want to use the data from an ancillary chunk,
988 * we have two options: an error abort, or a warning and we
989 * ignore the data in this chunk (which should be OK, since
990 * it's considered ancillary for a RGB or RGBA image).
991 *
992 * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the
993 * chunk type to determine whether to check the ancillary or the critical
994 * flags.
995 */
996 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0)
997 {
998 if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0)
999 return;
1000
1001 else
1002 png_chunk_error(png_ptr, "CRC error");
1003 }
1004
1005 /* Otherwise, we (optionally) emit a warning and use the chunk. */
1006 else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0)
1007 png_chunk_warning(png_ptr, "CRC error");
1008 }
1009 #endif
1010
1011 /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its
1012 * own copy of the palette. This has the side effect that when png_start_row
1013 * is called (this happens after any call to png_read_update_info) the
1014 * info_ptr palette gets changed. This is extremely unexpected and
1015 * confusing.
1016 *
1017 * Fix this by not sharing the palette in this way.
1018 */
1019 png_set_PLTE(png_ptr, info_ptr, palette, num);
1020
1021 /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before
1022 * IDAT. Prior to 1.6.0 this was not checked; instead the code merely
1023 * checked the apparent validity of a tRNS chunk inserted before PLTE on a
1024 * palette PNG. 1.6.0 attempts to rigorously follow the standard and
1025 * therefore does a benign error if the erroneous condition is detected *and*
1026 * cancels the tRNS if the benign error returns. The alternative is to
1027 * amend the standard since it would be rather hypocritical of the standards
1028 * maintainers to ignore it.
1029 */
1030 #ifdef PNG_READ_tRNS_SUPPORTED
1031 if (png_ptr->num_trans > 0 ||
1032 (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0))
1033 {
1034 /* Cancel this because otherwise it would be used if the transforms
1035 * require it. Don't cancel the 'valid' flag because this would prevent
1036 * detection of duplicate chunks.
1037 */
1038 png_ptr->num_trans = 0;
1039
1040 if (info_ptr != NULL)
1041 info_ptr->num_trans = 0;
1042
1043 png_chunk_benign_error(png_ptr, "tRNS must be after");
1044 }
1045 #endif
1046
1047 #ifdef PNG_READ_hIST_SUPPORTED
1048 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1049 png_chunk_benign_error(png_ptr, "hIST must be after");
1050 #endif
1051
1052 #ifdef PNG_READ_bKGD_SUPPORTED
1053 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1054 png_chunk_benign_error(png_ptr, "bKGD must be after");
1055 #endif
1056 }
1057
1058 void /* PRIVATE */
1059 png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1060 {
1061 png_debug(1, "in png_handle_IEND");
1062
1063 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 ||
1064 (png_ptr->mode & PNG_HAVE_IDAT) == 0)
1065 png_chunk_error(png_ptr, "out of place");
1066
1067 png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1068
1069 png_crc_finish(png_ptr, length);
1070
1071 if (length != 0)
1072 png_chunk_benign_error(png_ptr, "invalid");
1073
1074 PNG_UNUSED(info_ptr)
1075 }
1076
1077 #ifdef PNG_READ_gAMA_SUPPORTED
1078 void /* PRIVATE */
1079 png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1080 {
1081 png_fixed_point igamma;
1082 png_byte buf[4];
1083
1084 png_debug(1, "in png_handle_gAMA");
1085
1086 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1087 png_chunk_error(png_ptr, "missing IHDR");
1088
1089 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1090 {
1091 png_crc_finish(png_ptr, length);
1092 png_chunk_benign_error(png_ptr, "out of place");
1093 return;
1094 }
1095
1096 if (length != 4)
1097 {
1098 png_crc_finish(png_ptr, length);
1099 png_chunk_benign_error(png_ptr, "invalid");
1100 return;
1101 }
1102
1103 png_crc_read(png_ptr, buf, 4);
1104
1105 if (png_crc_finish(png_ptr, 0) != 0)
1106 return;
1107
1108 igamma = png_get_fixed_point(NULL, buf);
1109
1110 png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma);
1111 png_colorspace_sync(png_ptr, info_ptr);
1112 }
1113 #endif
1114
1115 #ifdef PNG_READ_sBIT_SUPPORTED
1116 void /* PRIVATE */
1117 png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1118 {
1119 unsigned int truelen, i;
1120 png_byte sample_depth;
1121 png_byte buf[4];
1122
1123 png_debug(1, "in png_handle_sBIT");
1124
1125 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1126 png_chunk_error(png_ptr, "missing IHDR");
1127
1128 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1129 {
1130 png_crc_finish(png_ptr, length);
1131 png_chunk_benign_error(png_ptr, "out of place");
1132 return;
1133 }
1134
1135 if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0)
1136 {
1137 png_crc_finish(png_ptr, length);
1138 png_chunk_benign_error(png_ptr, "duplicate");
1139 return;
1140 }
1141
1142 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1143 {
1144 truelen = 3;
1145 sample_depth = 8;
1146 }
1147
1148 else
1149 {
1150 truelen = png_ptr->channels;
1151 sample_depth = png_ptr->bit_depth;
1152 }
1153
1154 if (length != truelen || length > 4)
1155 {
1156 png_chunk_benign_error(png_ptr, "invalid");
1157 png_crc_finish(png_ptr, length);
1158 return;
1159 }
1160
1161 buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1162 png_crc_read(png_ptr, buf, truelen);
1163
1164 if (png_crc_finish(png_ptr, 0) != 0)
1165 return;
1166
1167 for (i=0; i<truelen; ++i)
1168 {
1169 if (buf[i] == 0 || buf[i] > sample_depth)
1170 {
1171 png_chunk_benign_error(png_ptr, "invalid");
1172 return;
1173 }
1174 }
1175
1176 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1177 {
1178 png_ptr->sig_bit.red = buf[0];
1179 png_ptr->sig_bit.green = buf[1];
1180 png_ptr->sig_bit.blue = buf[2];
1181 png_ptr->sig_bit.alpha = buf[3];
1182 }
1183
1184 else
1185 {
1186 png_ptr->sig_bit.gray = buf[0];
1187 png_ptr->sig_bit.red = buf[0];
1188 png_ptr->sig_bit.green = buf[0];
1189 png_ptr->sig_bit.blue = buf[0];
1190 png_ptr->sig_bit.alpha = buf[1];
1191 }
1192
1193 png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1194 }
1195 #endif
1196
1197 #ifdef PNG_READ_cHRM_SUPPORTED
1198 void /* PRIVATE */
1199 png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1200 {
1201 png_byte buf[32];
1202 png_xy xy;
1203
1204 png_debug(1, "in png_handle_cHRM");
1205
1206 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1207 png_chunk_error(png_ptr, "missing IHDR");
1208
1209 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1210 {
1211 png_crc_finish(png_ptr, length);
1212 png_chunk_benign_error(png_ptr, "out of place");
1213 return;
1214 }
1215
1216 if (length != 32)
1217 {
1218 png_crc_finish(png_ptr, length);
1219 png_chunk_benign_error(png_ptr, "invalid");
1220 return;
1221 }
1222
1223 png_crc_read(png_ptr, buf, 32);
1224
1225 if (png_crc_finish(png_ptr, 0) != 0)
1226 return;
1227
1228 xy.whitex = png_get_fixed_point(NULL, buf);
1229 xy.whitey = png_get_fixed_point(NULL, buf + 4);
1230 xy.redx = png_get_fixed_point(NULL, buf + 8);
1231 xy.redy = png_get_fixed_point(NULL, buf + 12);
1232 xy.greenx = png_get_fixed_point(NULL, buf + 16);
1233 xy.greeny = png_get_fixed_point(NULL, buf + 20);
1234 xy.bluex = png_get_fixed_point(NULL, buf + 24);
1235 xy.bluey = png_get_fixed_point(NULL, buf + 28);
1236
1237 if (xy.whitex == PNG_FIXED_ERROR ||
1238 xy.whitey == PNG_FIXED_ERROR ||
1239 xy.redx == PNG_FIXED_ERROR ||
1240 xy.redy == PNG_FIXED_ERROR ||
1241 xy.greenx == PNG_FIXED_ERROR ||
1242 xy.greeny == PNG_FIXED_ERROR ||
1243 xy.bluex == PNG_FIXED_ERROR ||
1244 xy.bluey == PNG_FIXED_ERROR)
1245 {
1246 png_chunk_benign_error(png_ptr, "invalid values");
1247 return;
1248 }
1249
1250 /* If a colorspace error has already been output skip this chunk */
1251 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1252 return;
1253
1254 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0)
1255 {
1256 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1257 png_colorspace_sync(png_ptr, info_ptr);
1258 png_chunk_benign_error(png_ptr, "duplicate");
1259 return;
1260 }
1261
1262 png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
1263 (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy,
1264 1/*prefer cHRM values*/);
1265 png_colorspace_sync(png_ptr, info_ptr);
1266 }
1267 #endif
1268
1269 #ifdef PNG_READ_sRGB_SUPPORTED
1270 void /* PRIVATE */
1271 png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1272 {
1273 png_byte intent;
1274
1275 png_debug(1, "in png_handle_sRGB");
1276
1277 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1278 png_chunk_error(png_ptr, "missing IHDR");
1279
1280 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1281 {
1282 png_crc_finish(png_ptr, length);
1283 png_chunk_benign_error(png_ptr, "out of place");
1284 return;
1285 }
1286
1287 if (length != 1)
1288 {
1289 png_crc_finish(png_ptr, length);
1290 png_chunk_benign_error(png_ptr, "invalid");
1291 return;
1292 }
1293
1294 png_crc_read(png_ptr, &intent, 1);
1295
1296 if (png_crc_finish(png_ptr, 0) != 0)
1297 return;
1298
1299 /* If a colorspace error has already been output skip this chunk */
1300 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1301 return;
1302
1303 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1304 * this.
1305 */
1306 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0)
1307 {
1308 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1309 png_colorspace_sync(png_ptr, info_ptr);
1310 png_chunk_benign_error(png_ptr, "too many profiles");
1311 return;
1312 }
1313
1314 (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent);
1315 png_colorspace_sync(png_ptr, info_ptr);
1316 }
1317 #endif /* READ_sRGB */
1318
1319 #ifdef PNG_READ_iCCP_SUPPORTED
1320 void /* PRIVATE */
1321 png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1322 /* Note: this does not properly handle profiles that are > 64K under DOS */
1323 {
1324 png_const_charp errmsg = NULL; /* error message output, or no error */
1325 int finished = 0; /* crc checked */
1326
1327 png_debug(1, "in png_handle_iCCP");
1328
1329 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1330 png_chunk_error(png_ptr, "missing IHDR");
1331
1332 else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0)
1333 {
1334 png_crc_finish(png_ptr, length);
1335 png_chunk_benign_error(png_ptr, "out of place");
1336 return;
1337 }
1338
1339 /* Consistent with all the above colorspace handling an obviously *invalid*
1340 * chunk is just ignored, so does not invalidate the color space. An
1341 * alternative is to set the 'invalid' flags at the start of this routine
1342 * and only clear them in they were not set before and all the tests pass.
1343 * The minimum 'deflate' stream is assumed to be just the 2 byte header and
1344 * 4 byte checksum. The keyword must be at least one character and there is
1345 * a terminator (0) byte and the compression method.
1346 */
1347 if (length < 9)
1348 {
1349 png_crc_finish(png_ptr, length);
1350 png_chunk_benign_error(png_ptr, "too short");
1351 return;
1352 }
1353
1354 /* If a colorspace error has already been output skip this chunk */
1355 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)
1356 {
1357 png_crc_finish(png_ptr, length);
1358 return;
1359 }
1360
1361 /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect
1362 * this.
1363 */
1364 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0)
1365 {
1366 uInt read_length, keyword_length;
1367 char keyword[81];
1368
1369 /* Find the keyword; the keyword plus separator and compression method
1370 * bytes can be at most 81 characters long.
1371 */
1372 read_length = 81; /* maximum */
1373 if (read_length > length)
1374 read_length = (uInt)length;
1375
1376 png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1377 length -= read_length;
1378
1379 keyword_length = 0;
1380 while (keyword_length < 80 && keyword_length < read_length &&
1381 keyword[keyword_length] != 0)
1382 ++keyword_length;
1383
1384 /* TODO: make the keyword checking common */
1385 if (keyword_length >= 1 && keyword_length <= 79)
1386 {
1387 /* We only understand '0' compression - deflate - so if we get a
1388 * different value we can't safely decode the chunk.
1389 */
1390 if (keyword_length+1 < read_length &&
1391 keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1392 {
1393 read_length -= keyword_length+2;
1394
1395 if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1396 {
1397 Byte profile_header[132];
1398 Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1399 png_alloc_size_t size = (sizeof profile_header);
1400
1401 png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1402 png_ptr->zstream.avail_in = read_length;
1403 (void)png_inflate_read(png_ptr, local_buffer,
1404 (sizeof local_buffer), &length, profile_header, &size,
1405 0/*finish: don't, because the output is too small*/);
1406
1407 if (size == 0)
1408 {
1409 /* We have the ICC profile header; do the basic header checks.
1410 */
1411 const png_uint_32 profile_length =
1412 png_get_uint_32(profile_header);
1413
1414 if (png_icc_check_length(png_ptr, &png_ptr->colorspace,
1415 keyword, profile_length) != 0)
1416 {
1417 /* The length is apparently ok, so we can check the 132
1418 * byte header.
1419 */
1420 if (png_icc_check_header(png_ptr, &png_ptr->colorspace,
1421 keyword, profile_length, profile_header,
1422 png_ptr->color_type) != 0)
1423 {
1424 /* Now read the tag table; a variable size buffer is
1425 * needed at this point, allocate one for the whole
1426 * profile. The header check has already validated
1427 * that none of these stuff will overflow.
1428 */
1429 const png_uint_32 tag_count = png_get_uint_32(
1430 profile_header+128);
1431 png_bytep profile = png_read_buffer(png_ptr,
1432 profile_length, 2/*silent*/);
1433
1434 if (profile != NULL)
1435 {
1436 memcpy(profile, profile_header,
1437 (sizeof profile_header));
1438
1439 size = 12 * tag_count;
1440
1441 (void)png_inflate_read(png_ptr, local_buffer,
1442 (sizeof local_buffer), &length,
1443 profile + (sizeof profile_header), &size, 0);
1444
1445 /* Still expect a buffer error because we expect
1446 * there to be some tag data!
1447 */
1448 if (size == 0)
1449 {
1450 if (png_icc_check_tag_table(png_ptr,
1451 &png_ptr->colorspace, keyword, profile_length,
1452 profile) != 0)
1453 {
1454 /* The profile has been validated for basic
1455 * security issues, so read the whole thing in.
1456 */
1457 size = profile_length - (sizeof profile_header)
1458 - 12 * tag_count;
1459
1460 (void)png_inflate_read(png_ptr, local_buffer,
1461 (sizeof local_buffer), &length,
1462 profile + (sizeof profile_header) +
1463 12 * tag_count, &size, 1/*finish*/);
1464
1465 if (length > 0 && !(png_ptr->flags &
1466 PNG_FLAG_BENIGN_ERRORS_WARN))
1467 errmsg = "extra compressed data";
1468
1469 /* But otherwise allow extra data: */
1470 else if (size == 0)
1471 {
1472 if (length > 0)
1473 {
1474 /* This can be handled completely, so
1475 * keep going.
1476 */
1477 png_chunk_warning(png_ptr,
1478 "extra compressed data");
1479 }
1480
1481 png_crc_finish(png_ptr, length);
1482 finished = 1;
1483
1484 # ifdef PNG_sRGB_SUPPORTED
1485 /* Check for a match against sRGB */
1486 png_icc_set_sRGB(png_ptr,
1487 &png_ptr->colorspace, profile,
1488 png_ptr->zstream.adler);
1489 # endif
1490
1491 /* Steal the profile for info_ptr. */
1492 if (info_ptr != NULL)
1493 {
1494 png_free_data(png_ptr, info_ptr,
1495 PNG_FREE_ICCP, 0);
1496
1497 info_ptr->iccp_name = png_voidcast(char*,
1498 png_malloc_base(png_ptr,
1499 keyword_length+1));
1500 if (info_ptr->iccp_name != NULL)
1501 {
1502 memcpy(info_ptr->iccp_name, keyword,
1503 keyword_length+1);
1504 info_ptr->iccp_proflen =
1505 profile_length;
1506 info_ptr->iccp_profile = profile;
1507 png_ptr->read_buffer = NULL; /*steal*/
1508 info_ptr->free_me |= PNG_FREE_ICCP;
1509 info_ptr->valid |= PNG_INFO_iCCP;
1510 }
1511
1512 else
1513 {
1514 png_ptr->colorspace.flags |=
1515 PNG_COLORSPACE_INVALID;
1516 errmsg = "out of memory";
1517 }
1518 }
1519
1520 /* else the profile remains in the read
1521 * buffer which gets reused for subsequent
1522 * chunks.
1523 */
1524
1525 if (info_ptr != NULL)
1526 png_colorspace_sync(png_ptr, info_ptr);
1527
1528 if (errmsg == NULL)
1529 {
1530 png_ptr->zowner = 0;
1531 return;
1532 }
1533 }
1534
1535 else if (size > 0)
1536 errmsg = "truncated";
1537
1538 #ifndef __COVERITY__
1539 else
1540 errmsg = png_ptr->zstream.msg;
1541 #endif
1542 }
1543
1544 /* else png_icc_check_tag_table output an error */
1545 }
1546
1547 else /* profile truncated */
1548 errmsg = png_ptr->zstream.msg;
1549 }
1550
1551 else
1552 errmsg = "out of memory";
1553 }
1554
1555 /* else png_icc_check_header output an error */
1556 }
1557
1558 /* else png_icc_check_length output an error */
1559 }
1560
1561 else /* profile truncated */
1562 errmsg = png_ptr->zstream.msg;
1563
1564 /* Release the stream */
1565 png_ptr->zowner = 0;
1566 }
1567
1568 else /* png_inflate_claim failed */
1569 errmsg = png_ptr->zstream.msg;
1570 }
1571
1572 else
1573 errmsg = "bad compression method"; /* or missing */
1574 }
1575
1576 else
1577 errmsg = "bad keyword";
1578 }
1579
1580 else
1581 errmsg = "too many profiles";
1582
1583 /* Failure: the reason is in 'errmsg' */
1584 if (finished == 0)
1585 png_crc_finish(png_ptr, length);
1586
1587 png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID;
1588 png_colorspace_sync(png_ptr, info_ptr);
1589 if (errmsg != NULL) /* else already output */
1590 png_chunk_benign_error(png_ptr, errmsg);
1591 }
1592 #endif /* READ_iCCP */
1593
1594 #ifdef PNG_READ_sPLT_SUPPORTED
1595 void /* PRIVATE */
1596 png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1597 /* Note: this does not properly handle chunks that are > 64K under DOS */
1598 {
1599 png_bytep entry_start, buffer;
1600 png_sPLT_t new_palette;
1601 png_sPLT_entryp pp;
1602 png_uint_32 data_length;
1603 int entry_size, i;
1604 png_uint_32 skip = 0;
1605 png_uint_32 dl;
1606 png_size_t max_dl;
1607
1608 png_debug(1, "in png_handle_sPLT");
1609
1610 #ifdef PNG_USER_LIMITS_SUPPORTED
1611 if (png_ptr->user_chunk_cache_max != 0)
1612 {
1613 if (png_ptr->user_chunk_cache_max == 1)
1614 {
1615 png_crc_finish(png_ptr, length);
1616 return;
1617 }
1618
1619 if (--png_ptr->user_chunk_cache_max == 1)
1620 {
1621 png_warning(png_ptr, "No space in chunk cache for sPLT");
1622 png_crc_finish(png_ptr, length);
1623 return;
1624 }
1625 }
1626 #endif
1627
1628 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1629 png_chunk_error(png_ptr, "missing IHDR");
1630
1631 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1632 {
1633 png_crc_finish(png_ptr, length);
1634 png_chunk_benign_error(png_ptr, "out of place");
1635 return;
1636 }
1637
1638 #ifdef PNG_MAX_MALLOC_64K
1639 if (length > 65535U)
1640 {
1641 png_crc_finish(png_ptr, length);
1642 png_chunk_benign_error(png_ptr, "too large to fit in memory");
1643 return;
1644 }
1645 #endif
1646
1647 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
1648 if (buffer == NULL)
1649 {
1650 png_crc_finish(png_ptr, length);
1651 png_chunk_benign_error(png_ptr, "out of memory");
1652 return;
1653 }
1654
1655
1656 /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1657 * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1658 * potential breakage point if the types in pngconf.h aren't exactly right.
1659 */
1660 png_crc_read(png_ptr, buffer, length);
1661
1662 if (png_crc_finish(png_ptr, skip) != 0)
1663 return;
1664
1665 buffer[length] = 0;
1666
1667 for (entry_start = buffer; *entry_start; entry_start++)
1668 /* Empty loop to find end of name */ ;
1669
1670 ++entry_start;
1671
1672 /* A sample depth should follow the separator, and we should be on it */
1673 if (entry_start > buffer + length - 2)
1674 {
1675 png_warning(png_ptr, "malformed sPLT chunk");
1676 return;
1677 }
1678
1679 new_palette.depth = *entry_start++;
1680 entry_size = (new_palette.depth == 8 ? 6 : 10);
1681 /* This must fit in a png_uint_32 because it is derived from the original
1682 * chunk data length.
1683 */
1684 data_length = length - (png_uint_32)(entry_start - buffer);
1685
1686 /* Integrity-check the data length */
1687 if ((data_length % entry_size) != 0)
1688 {
1689 png_warning(png_ptr, "sPLT chunk has bad length");
1690 return;
1691 }
1692
1693 dl = (png_int_32)(data_length / entry_size);
1694 max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1695
1696 if (dl > max_dl)
1697 {
1698 png_warning(png_ptr, "sPLT chunk too long");
1699 return;
1700 }
1701
1702 new_palette.nentries = (png_int_32)(data_length / entry_size);
1703
1704 new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
1705 png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry)));
1706
1707 if (new_palette.entries == NULL)
1708 {
1709 png_warning(png_ptr, "sPLT chunk requires too much memory");
1710 return;
1711 }
1712
1713 #ifdef PNG_POINTER_INDEXING_SUPPORTED
1714 for (i = 0; i < new_palette.nentries; i++)
1715 {
1716 pp = new_palette.entries + i;
1717
1718 if (new_palette.depth == 8)
1719 {
1720 pp->red = *entry_start++;
1721 pp->green = *entry_start++;
1722 pp->blue = *entry_start++;
1723 pp->alpha = *entry_start++;
1724 }
1725
1726 else
1727 {
1728 pp->red = png_get_uint_16(entry_start); entry_start += 2;
1729 pp->green = png_get_uint_16(entry_start); entry_start += 2;
1730 pp->blue = png_get_uint_16(entry_start); entry_start += 2;
1731 pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1732 }
1733
1734 pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1735 }
1736 #else
1737 pp = new_palette.entries;
1738
1739 for (i = 0; i < new_palette.nentries; i++)
1740 {
1741
1742 if (new_palette.depth == 8)
1743 {
1744 pp[i].red = *entry_start++;
1745 pp[i].green = *entry_start++;
1746 pp[i].blue = *entry_start++;
1747 pp[i].alpha = *entry_start++;
1748 }
1749
1750 else
1751 {
1752 pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
1753 pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
1754 pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
1755 pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
1756 }
1757
1758 pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2;
1759 }
1760 #endif
1761
1762 /* Discard all chunk data except the name and stash that */
1763 new_palette.name = (png_charp)buffer;
1764
1765 png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1766
1767 png_free(png_ptr, new_palette.entries);
1768 }
1769 #endif /* READ_sPLT */
1770
1771 #ifdef PNG_READ_tRNS_SUPPORTED
1772 void /* PRIVATE */
1773 png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1774 {
1775 png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1776
1777 png_debug(1, "in png_handle_tRNS");
1778
1779 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1780 png_chunk_error(png_ptr, "missing IHDR");
1781
1782 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
1783 {
1784 png_crc_finish(png_ptr, length);
1785 png_chunk_benign_error(png_ptr, "out of place");
1786 return;
1787 }
1788
1789 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)
1790 {
1791 png_crc_finish(png_ptr, length);
1792 png_chunk_benign_error(png_ptr, "duplicate");
1793 return;
1794 }
1795
1796 if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1797 {
1798 png_byte buf[2];
1799
1800 if (length != 2)
1801 {
1802 png_crc_finish(png_ptr, length);
1803 png_chunk_benign_error(png_ptr, "invalid");
1804 return;
1805 }
1806
1807 png_crc_read(png_ptr, buf, 2);
1808 png_ptr->num_trans = 1;
1809 png_ptr->trans_color.gray = png_get_uint_16(buf);
1810 }
1811
1812 else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1813 {
1814 png_byte buf[6];
1815
1816 if (length != 6)
1817 {
1818 png_crc_finish(png_ptr, length);
1819 png_chunk_benign_error(png_ptr, "invalid");
1820 return;
1821 }
1822
1823 png_crc_read(png_ptr, buf, length);
1824 png_ptr->num_trans = 1;
1825 png_ptr->trans_color.red = png_get_uint_16(buf);
1826 png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1827 png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1828 }
1829
1830 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1831 {
1832 if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1833 {
1834 /* TODO: is this actually an error in the ISO spec? */
1835 png_crc_finish(png_ptr, length);
1836 png_chunk_benign_error(png_ptr, "out of place");
1837 return;
1838 }
1839
1840 if (length > (unsigned int) png_ptr->num_palette ||
1841 length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1842 length == 0)
1843 {
1844 png_crc_finish(png_ptr, length);
1845 png_chunk_benign_error(png_ptr, "invalid");
1846 return;
1847 }
1848
1849 png_crc_read(png_ptr, readbuf, length);
1850 png_ptr->num_trans = (png_uint_16)length;
1851 }
1852
1853 else
1854 {
1855 png_crc_finish(png_ptr, length);
1856 png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1857 return;
1858 }
1859
1860 if (png_crc_finish(png_ptr, 0) != 0)
1861 {
1862 png_ptr->num_trans = 0;
1863 return;
1864 }
1865
1866 /* TODO: this is a horrible side effect in the palette case because the
1867 * png_struct ends up with a pointer to the tRNS buffer owned by the
1868 * png_info. Fix this.
1869 */
1870 png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1871 &(png_ptr->trans_color));
1872 }
1873 #endif
1874
1875 #ifdef PNG_READ_bKGD_SUPPORTED
1876 void /* PRIVATE */
1877 png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1878 {
1879 unsigned int truelen;
1880 png_byte buf[6];
1881 png_color_16 background;
1882
1883 png_debug(1, "in png_handle_bKGD");
1884
1885 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1886 png_chunk_error(png_ptr, "missing IHDR");
1887
1888 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1889 (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1890 (png_ptr->mode & PNG_HAVE_PLTE) == 0))
1891 {
1892 png_crc_finish(png_ptr, length);
1893 png_chunk_benign_error(png_ptr, "out of place");
1894 return;
1895 }
1896
1897 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0)
1898 {
1899 png_crc_finish(png_ptr, length);
1900 png_chunk_benign_error(png_ptr, "duplicate");
1901 return;
1902 }
1903
1904 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1905 truelen = 1;
1906
1907 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1908 truelen = 6;
1909
1910 else
1911 truelen = 2;
1912
1913 if (length != truelen)
1914 {
1915 png_crc_finish(png_ptr, length);
1916 png_chunk_benign_error(png_ptr, "invalid");
1917 return;
1918 }
1919
1920 png_crc_read(png_ptr, buf, truelen);
1921
1922 if (png_crc_finish(png_ptr, 0) != 0)
1923 return;
1924
1925 /* We convert the index value into RGB components so that we can allow
1926 * arbitrary RGB values for background when we have transparency, and
1927 * so it is easy to determine the RGB values of the background color
1928 * from the info_ptr struct.
1929 */
1930 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1931 {
1932 background.index = buf[0];
1933
1934 if (info_ptr != NULL && info_ptr->num_palette != 0)
1935 {
1936 if (buf[0] >= info_ptr->num_palette)
1937 {
1938 png_chunk_benign_error(png_ptr, "invalid index");
1939 return;
1940 }
1941
1942 background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1943 background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1944 background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1945 }
1946
1947 else
1948 background.red = background.green = background.blue = 0;
1949
1950 background.gray = 0;
1951 }
1952
1953 else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1954 {
1955 background.index = 0;
1956 background.red =
1957 background.green =
1958 background.blue =
1959 background.gray = png_get_uint_16(buf);
1960 }
1961
1962 else
1963 {
1964 background.index = 0;
1965 background.red = png_get_uint_16(buf);
1966 background.green = png_get_uint_16(buf + 2);
1967 background.blue = png_get_uint_16(buf + 4);
1968 background.gray = 0;
1969 }
1970
1971 png_set_bKGD(png_ptr, info_ptr, &background);
1972 }
1973 #endif
1974
1975 #ifdef PNG_READ_hIST_SUPPORTED
1976 void /* PRIVATE */
1977 png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1978 {
1979 unsigned int num, i;
1980 png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
1981
1982 png_debug(1, "in png_handle_hIST");
1983
1984 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
1985 png_chunk_error(png_ptr, "missing IHDR");
1986
1987 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 ||
1988 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
1989 {
1990 png_crc_finish(png_ptr, length);
1991 png_chunk_benign_error(png_ptr, "out of place");
1992 return;
1993 }
1994
1995 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0)
1996 {
1997 png_crc_finish(png_ptr, length);
1998 png_chunk_benign_error(png_ptr, "duplicate");
1999 return;
2000 }
2001
2002 num = length / 2 ;
2003
2004 if (num != (unsigned int) png_ptr->num_palette ||
2005 num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
2006 {
2007 png_crc_finish(png_ptr, length);
2008 png_chunk_benign_error(png_ptr, "invalid");
2009 return;
2010 }
2011
2012 for (i = 0; i < num; i++)
2013 {
2014 png_byte buf[2];
2015
2016 png_crc_read(png_ptr, buf, 2);
2017 readbuf[i] = png_get_uint_16(buf);
2018 }
2019
2020 if (png_crc_finish(png_ptr, 0) != 0)
2021 return;
2022
2023 png_set_hIST(png_ptr, info_ptr, readbuf);
2024 }
2025 #endif
2026
2027 #ifdef PNG_READ_pHYs_SUPPORTED
2028 void /* PRIVATE */
2029 png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2030 {
2031 png_byte buf[9];
2032 png_uint_32 res_x, res_y;
2033 int unit_type;
2034
2035 png_debug(1, "in png_handle_pHYs");
2036
2037 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2038 png_chunk_error(png_ptr, "missing IHDR");
2039
2040 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2041 {
2042 png_crc_finish(png_ptr, length);
2043 png_chunk_benign_error(png_ptr, "out of place");
2044 return;
2045 }
2046
2047 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0)
2048 {
2049 png_crc_finish(png_ptr, length);
2050 png_chunk_benign_error(png_ptr, "duplicate");
2051 return;
2052 }
2053
2054 if (length != 9)
2055 {
2056 png_crc_finish(png_ptr, length);
2057 png_chunk_benign_error(png_ptr, "invalid");
2058 return;
2059 }
2060
2061 png_crc_read(png_ptr, buf, 9);
2062
2063 if (png_crc_finish(png_ptr, 0) != 0)
2064 return;
2065
2066 res_x = png_get_uint_32(buf);
2067 res_y = png_get_uint_32(buf + 4);
2068 unit_type = buf[8];
2069 png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2070 }
2071 #endif
2072
2073 #ifdef PNG_READ_oFFs_SUPPORTED
2074 void /* PRIVATE */
2075 png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2076 {
2077 png_byte buf[9];
2078 png_int_32 offset_x, offset_y;
2079 int unit_type;
2080
2081 png_debug(1, "in png_handle_oFFs");
2082
2083 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2084 png_chunk_error(png_ptr, "missing IHDR");
2085
2086 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2087 {
2088 png_crc_finish(png_ptr, length);
2089 png_chunk_benign_error(png_ptr, "out of place");
2090 return;
2091 }
2092
2093 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0)
2094 {
2095 png_crc_finish(png_ptr, length);
2096 png_chunk_benign_error(png_ptr, "duplicate");
2097 return;
2098 }
2099
2100 if (length != 9)
2101 {
2102 png_crc_finish(png_ptr, length);
2103 png_chunk_benign_error(png_ptr, "invalid");
2104 return;
2105 }
2106
2107 png_crc_read(png_ptr, buf, 9);
2108
2109 if (png_crc_finish(png_ptr, 0) != 0)
2110 return;
2111
2112 offset_x = png_get_int_32(buf);
2113 offset_y = png_get_int_32(buf + 4);
2114 unit_type = buf[8];
2115 png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2116 }
2117 #endif
2118
2119 #ifdef PNG_READ_pCAL_SUPPORTED
2120 /* Read the pCAL chunk (described in the PNG Extensions document) */
2121 void /* PRIVATE */
2122 png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2123 {
2124 png_int_32 X0, X1;
2125 png_byte type, nparams;
2126 png_bytep buffer, buf, units, endptr;
2127 png_charpp params;
2128 int i;
2129
2130 png_debug(1, "in png_handle_pCAL");
2131
2132 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2133 png_chunk_error(png_ptr, "missing IHDR");
2134
2135 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2136 {
2137 png_crc_finish(png_ptr, length);
2138 png_chunk_benign_error(png_ptr, "out of place");
2139 return;
2140 }
2141
2142 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0)
2143 {
2144 png_crc_finish(png_ptr, length);
2145 png_chunk_benign_error(png_ptr, "duplicate");
2146 return;
2147 }
2148
2149 png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2150 length + 1);
2151
2152 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2153
2154 if (buffer == NULL)
2155 {
2156 png_crc_finish(png_ptr, length);
2157 png_chunk_benign_error(png_ptr, "out of memory");
2158 return;
2159 }
2160
2161 png_crc_read(png_ptr, buffer, length);
2162
2163 if (png_crc_finish(png_ptr, 0) != 0)
2164 return;
2165
2166 buffer[length] = 0; /* Null terminate the last string */
2167
2168 png_debug(3, "Finding end of pCAL purpose string");
2169 for (buf = buffer; *buf; buf++)
2170 /* Empty loop */ ;
2171
2172 endptr = buffer + length;
2173
2174 /* We need to have at least 12 bytes after the purpose string
2175 * in order to get the parameter information.
2176 */
2177 if (endptr <= buf + 12)
2178 {
2179 png_chunk_benign_error(png_ptr, "invalid");
2180 return;
2181 }
2182
2183 png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2184 X0 = png_get_int_32((png_bytep)buf+1);
2185 X1 = png_get_int_32((png_bytep)buf+5);
2186 type = buf[9];
2187 nparams = buf[10];
2188 units = buf + 11;
2189
2190 png_debug(3, "Checking pCAL equation type and number of parameters");
2191 /* Check that we have the right number of parameters for known
2192 * equation types.
2193 */
2194 if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2195 (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2196 (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2197 (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2198 {
2199 png_chunk_benign_error(png_ptr, "invalid parameter count");
2200 return;
2201 }
2202
2203 else if (type >= PNG_EQUATION_LAST)
2204 {
2205 png_chunk_benign_error(png_ptr, "unrecognized equation type");
2206 }
2207
2208 for (buf = units; *buf; buf++)
2209 /* Empty loop to move past the units string. */ ;
2210
2211 png_debug(3, "Allocating pCAL parameters array");
2212
2213 params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2214 nparams * (sizeof (png_charp))));
2215
2216 if (params == NULL)
2217 {
2218 png_chunk_benign_error(png_ptr, "out of memory");
2219 return;
2220 }
2221
2222 /* Get pointers to the start of each parameter string. */
2223 for (i = 0; i < nparams; i++)
2224 {
2225 buf++; /* Skip the null string terminator from previous parameter. */
2226
2227 png_debug1(3, "Reading pCAL parameter %d", i);
2228
2229 for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2230 /* Empty loop to move past each parameter string */ ;
2231
2232 /* Make sure we haven't run out of data yet */
2233 if (buf > endptr)
2234 {
2235 png_free(png_ptr, params);
2236 png_chunk_benign_error(png_ptr, "invalid data");
2237 return;
2238 }
2239 }
2240
2241 png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2242 (png_charp)units, params);
2243
2244 png_free(png_ptr, params);
2245 }
2246 #endif
2247
2248 #ifdef PNG_READ_sCAL_SUPPORTED
2249 /* Read the sCAL chunk */
2250 void /* PRIVATE */
2251 png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2252 {
2253 png_bytep buffer;
2254 png_size_t i;
2255 int state;
2256
2257 png_debug(1, "in png_handle_sCAL");
2258
2259 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2260 png_chunk_error(png_ptr, "missing IHDR");
2261
2262 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2263 {
2264 png_crc_finish(png_ptr, length);
2265 png_chunk_benign_error(png_ptr, "out of place");
2266 return;
2267 }
2268
2269 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0)
2270 {
2271 png_crc_finish(png_ptr, length);
2272 png_chunk_benign_error(png_ptr, "duplicate");
2273 return;
2274 }
2275
2276 /* Need unit type, width, \0, height: minimum 4 bytes */
2277 else if (length < 4)
2278 {
2279 png_crc_finish(png_ptr, length);
2280 png_chunk_benign_error(png_ptr, "invalid");
2281 return;
2282 }
2283
2284 png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2285 length + 1);
2286
2287 buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/);
2288
2289 if (buffer == NULL)
2290 {
2291 png_chunk_benign_error(png_ptr, "out of memory");
2292 png_crc_finish(png_ptr, length);
2293 return;
2294 }
2295
2296 png_crc_read(png_ptr, buffer, length);
2297 buffer[length] = 0; /* Null terminate the last string */
2298
2299 if (png_crc_finish(png_ptr, 0) != 0)
2300 return;
2301
2302 /* Validate the unit. */
2303 if (buffer[0] != 1 && buffer[0] != 2)
2304 {
2305 png_chunk_benign_error(png_ptr, "invalid unit");
2306 return;
2307 }
2308
2309 /* Validate the ASCII numbers, need two ASCII numbers separated by
2310 * a '\0' and they need to fit exactly in the chunk data.
2311 */
2312 i = 1;
2313 state = 0;
2314
2315 if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2316 i >= length || buffer[i++] != 0)
2317 png_chunk_benign_error(png_ptr, "bad width format");
2318
2319 else if (PNG_FP_IS_POSITIVE(state) == 0)
2320 png_chunk_benign_error(png_ptr, "non-positive width");
2321
2322 else
2323 {
2324 png_size_t heighti = i;
2325
2326 state = 0;
2327 if (png_check_fp_number((png_const_charp)buffer, length,
2328 &state, &i) == 0 || i != length)
2329 png_chunk_benign_error(png_ptr, "bad height format");
2330
2331 else if (PNG_FP_IS_POSITIVE(state) == 0)
2332 png_chunk_benign_error(png_ptr, "non-positive height");
2333
2334 else
2335 /* This is the (only) success case. */
2336 png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2337 (png_charp)buffer+1, (png_charp)buffer+heighti);
2338 }
2339 }
2340 #endif
2341
2342 #ifdef PNG_READ_tIME_SUPPORTED
2343 void /* PRIVATE */
2344 png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2345 {
2346 png_byte buf[7];
2347 png_time mod_time;
2348
2349 png_debug(1, "in png_handle_tIME");
2350
2351 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2352 png_chunk_error(png_ptr, "missing IHDR");
2353
2354 else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0)
2355 {
2356 png_crc_finish(png_ptr, length);
2357 png_chunk_benign_error(png_ptr, "duplicate");
2358 return;
2359 }
2360
2361 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2362 png_ptr->mode |= PNG_AFTER_IDAT;
2363
2364 if (length != 7)
2365 {
2366 png_crc_finish(png_ptr, length);
2367 png_chunk_benign_error(png_ptr, "invalid");
2368 return;
2369 }
2370
2371 png_crc_read(png_ptr, buf, 7);
2372
2373 if (png_crc_finish(png_ptr, 0) != 0)
2374 return;
2375
2376 mod_time.second = buf[6];
2377 mod_time.minute = buf[5];
2378 mod_time.hour = buf[4];
2379 mod_time.day = buf[3];
2380 mod_time.month = buf[2];
2381 mod_time.year = png_get_uint_16(buf);
2382
2383 png_set_tIME(png_ptr, info_ptr, &mod_time);
2384 }
2385 #endif
2386
2387 #ifdef PNG_READ_tEXt_SUPPORTED
2388 /* Note: this does not properly handle chunks that are > 64K under DOS */
2389 void /* PRIVATE */
2390 png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2391 {
2392 png_text text_info;
2393 png_bytep buffer;
2394 png_charp key;
2395 png_charp text;
2396 png_uint_32 skip = 0;
2397
2398 png_debug(1, "in png_handle_tEXt");
2399
2400 #ifdef PNG_USER_LIMITS_SUPPORTED
2401 if (png_ptr->user_chunk_cache_max != 0)
2402 {
2403 if (png_ptr->user_chunk_cache_max == 1)
2404 {
2405 png_crc_finish(png_ptr, length);
2406 return;
2407 }
2408
2409 if (--png_ptr->user_chunk_cache_max == 1)
2410 {
2411 png_crc_finish(png_ptr, length);
2412 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2413 return;
2414 }
2415 }
2416 #endif
2417
2418 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2419 png_chunk_error(png_ptr, "missing IHDR");
2420
2421 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2422 png_ptr->mode |= PNG_AFTER_IDAT;
2423
2424 #ifdef PNG_MAX_MALLOC_64K
2425 if (length > 65535U)
2426 {
2427 png_crc_finish(png_ptr, length);
2428 png_chunk_benign_error(png_ptr, "too large to fit in memory");
2429 return;
2430 }
2431 #endif
2432
2433 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2434
2435 if (buffer == NULL)
2436 {
2437 png_chunk_benign_error(png_ptr, "out of memory");
2438 return;
2439 }
2440
2441 png_crc_read(png_ptr, buffer, length);
2442
2443 if (png_crc_finish(png_ptr, skip) != 0)
2444 return;
2445
2446 key = (png_charp)buffer;
2447 key[length] = 0;
2448
2449 for (text = key; *text; text++)
2450 /* Empty loop to find end of key */ ;
2451
2452 if (text != key + length)
2453 text++;
2454
2455 text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2456 text_info.key = key;
2457 text_info.lang = NULL;
2458 text_info.lang_key = NULL;
2459 text_info.itxt_length = 0;
2460 text_info.text = text;
2461 text_info.text_length = strlen(text);
2462
2463 if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0)
2464 png_warning(png_ptr, "Insufficient memory to process text chunk");
2465 }
2466 #endif
2467
2468 #ifdef PNG_READ_zTXt_SUPPORTED
2469 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2470 void /* PRIVATE */
2471 png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2472 {
2473 png_const_charp errmsg = NULL;
2474 png_bytep buffer;
2475 png_uint_32 keyword_length;
2476
2477 png_debug(1, "in png_handle_zTXt");
2478
2479 #ifdef PNG_USER_LIMITS_SUPPORTED
2480 if (png_ptr->user_chunk_cache_max != 0)
2481 {
2482 if (png_ptr->user_chunk_cache_max == 1)
2483 {
2484 png_crc_finish(png_ptr, length);
2485 return;
2486 }
2487
2488 if (--png_ptr->user_chunk_cache_max == 1)
2489 {
2490 png_crc_finish(png_ptr, length);
2491 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2492 return;
2493 }
2494 }
2495 #endif
2496
2497 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2498 png_chunk_error(png_ptr, "missing IHDR");
2499
2500 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2501 png_ptr->mode |= PNG_AFTER_IDAT;
2502
2503 buffer = png_read_buffer(png_ptr, length, 2/*silent*/);
2504
2505 if (buffer == NULL)
2506 {
2507 png_crc_finish(png_ptr, length);
2508 png_chunk_benign_error(png_ptr, "out of memory");
2509 return;
2510 }
2511
2512 png_crc_read(png_ptr, buffer, length);
2513
2514 if (png_crc_finish(png_ptr, 0) != 0)
2515 return;
2516
2517 /* TODO: also check that the keyword contents match the spec! */
2518 for (keyword_length = 0;
2519 keyword_length < length && buffer[keyword_length] != 0;
2520 ++keyword_length)
2521 /* Empty loop to find end of name */ ;
2522
2523 if (keyword_length > 79 || keyword_length < 1)
2524 errmsg = "bad keyword";
2525
2526 /* zTXt must have some LZ data after the keyword, although it may expand to
2527 * zero bytes; we need a '\0' at the end of the keyword, the compression type
2528 * then the LZ data:
2529 */
2530 else if (keyword_length + 3 > length)
2531 errmsg = "truncated";
2532
2533 else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2534 errmsg = "unknown compression type";
2535
2536 else
2537 {
2538 png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2539
2540 /* TODO: at present png_decompress_chunk imposes a single application
2541 * level memory limit, this should be split to different values for iCCP
2542 * and text chunks.
2543 */
2544 if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2545 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2546 {
2547 png_text text;
2548
2549 /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except
2550 * for the extra compression type byte and the fact that it isn't
2551 * necessarily '\0' terminated.
2552 */
2553 buffer = png_ptr->read_buffer;
2554 buffer[uncompressed_length+(keyword_length+2)] = 0;
2555
2556 text.compression = PNG_TEXT_COMPRESSION_zTXt;
2557 text.key = (png_charp)buffer;
2558 text.text = (png_charp)(buffer + keyword_length+2);
2559 text.text_length = uncompressed_length;
2560 text.itxt_length = 0;
2561 text.lang = NULL;
2562 text.lang_key = NULL;
2563
2564 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2565 errmsg = "insufficient memory";
2566 }
2567
2568 else
2569 errmsg = png_ptr->zstream.msg;
2570 }
2571
2572 if (errmsg != NULL)
2573 png_chunk_benign_error(png_ptr, errmsg);
2574 }
2575 #endif
2576
2577 #ifdef PNG_READ_iTXt_SUPPORTED
2578 /* Note: this does not correctly handle chunks that are > 64K under DOS */
2579 void /* PRIVATE */
2580 png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2581 {
2582 png_const_charp errmsg = NULL;
2583 png_bytep buffer;
2584 png_uint_32 prefix_length;
2585
2586 png_debug(1, "in png_handle_iTXt");
2587
2588 #ifdef PNG_USER_LIMITS_SUPPORTED
2589 if (png_ptr->user_chunk_cache_max != 0)
2590 {
2591 if (png_ptr->user_chunk_cache_max == 1)
2592 {
2593 png_crc_finish(png_ptr, length);
2594 return;
2595 }
2596
2597 if (--png_ptr->user_chunk_cache_max == 1)
2598 {
2599 png_crc_finish(png_ptr, length);
2600 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2601 return;
2602 }
2603 }
2604 #endif
2605
2606 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
2607 png_chunk_error(png_ptr, "missing IHDR");
2608
2609 if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2610 png_ptr->mode |= PNG_AFTER_IDAT;
2611
2612 buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/);
2613
2614 if (buffer == NULL)
2615 {
2616 png_crc_finish(png_ptr, length);
2617 png_chunk_benign_error(png_ptr, "out of memory");
2618 return;
2619 }
2620
2621 png_crc_read(png_ptr, buffer, length);
2622
2623 if (png_crc_finish(png_ptr, 0) != 0)
2624 return;
2625
2626 /* First the keyword. */
2627 for (prefix_length=0;
2628 prefix_length < length && buffer[prefix_length] != 0;
2629 ++prefix_length)
2630 /* Empty loop */ ;
2631
2632 /* Perform a basic check on the keyword length here. */
2633 if (prefix_length > 79 || prefix_length < 1)
2634 errmsg = "bad keyword";
2635
2636 /* Expect keyword, compression flag, compression type, language, translated
2637 * keyword (both may be empty but are 0 terminated) then the text, which may
2638 * be empty.
2639 */
2640 else if (prefix_length + 5 > length)
2641 errmsg = "truncated";
2642
2643 else if (buffer[prefix_length+1] == 0 ||
2644 (buffer[prefix_length+1] == 1 &&
2645 buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2646 {
2647 int compressed = buffer[prefix_length+1] != 0;
2648 png_uint_32 language_offset, translated_keyword_offset;
2649 png_alloc_size_t uncompressed_length = 0;
2650
2651 /* Now the language tag */
2652 prefix_length += 3;
2653 language_offset = prefix_length;
2654
2655 for (; prefix_length < length && buffer[prefix_length] != 0;
2656 ++prefix_length)
2657 /* Empty loop */ ;
2658
2659 /* WARNING: the length may be invalid here, this is checked below. */
2660 translated_keyword_offset = ++prefix_length;
2661
2662 for (; prefix_length < length && buffer[prefix_length] != 0;
2663 ++prefix_length)
2664 /* Empty loop */ ;
2665
2666 /* prefix_length should now be at the trailing '\0' of the translated
2667 * keyword, but it may already be over the end. None of this arithmetic
2668 * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2669 * systems the available allocation may overflow.
2670 */
2671 ++prefix_length;
2672
2673 if (compressed == 0 && prefix_length <= length)
2674 uncompressed_length = length - prefix_length;
2675
2676 else if (compressed != 0 && prefix_length < length)
2677 {
2678 uncompressed_length = PNG_SIZE_MAX;
2679
2680 /* TODO: at present png_decompress_chunk imposes a single application
2681 * level memory limit, this should be split to different values for
2682 * iCCP and text chunks.
2683 */
2684 if (png_decompress_chunk(png_ptr, length, prefix_length,
2685 &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2686 buffer = png_ptr->read_buffer;
2687
2688 else
2689 errmsg = png_ptr->zstream.msg;
2690 }
2691
2692 else
2693 errmsg = "truncated";
2694
2695 if (errmsg == NULL)
2696 {
2697 png_text text;
2698
2699 buffer[uncompressed_length+prefix_length] = 0;
2700
2701 if (compressed == 0)
2702 text.compression = PNG_ITXT_COMPRESSION_NONE;
2703
2704 else
2705 text.compression = PNG_ITXT_COMPRESSION_zTXt;
2706
2707 text.key = (png_charp)buffer;
2708 text.lang = (png_charp)buffer + language_offset;
2709 text.lang_key = (png_charp)buffer + translated_keyword_offset;
2710 text.text = (png_charp)buffer + prefix_length;
2711 text.text_length = 0;
2712 text.itxt_length = uncompressed_length;
2713
2714 if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0)
2715 errmsg = "insufficient memory";
2716 }
2717 }
2718
2719 else
2720 errmsg = "bad compression info";
2721
2722 if (errmsg != NULL)
2723 png_chunk_benign_error(png_ptr, errmsg);
2724 }
2725 #endif
2726
2727 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2728 /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2729 static int
2730 png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2731 {
2732 png_alloc_size_t limit = PNG_SIZE_MAX;
2733
2734 if (png_ptr->unknown_chunk.data != NULL)
2735 {
2736 png_free(png_ptr, png_ptr->unknown_chunk.data);
2737 png_ptr->unknown_chunk.data = NULL;
2738 }
2739
2740 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
2741 if (png_ptr->user_chunk_malloc_max > 0 &&
2742 png_ptr->user_chunk_malloc_max < limit)
2743 limit = png_ptr->user_chunk_malloc_max;
2744
2745 # elif PNG_USER_CHUNK_MALLOC_MAX > 0
2746 if (PNG_USER_CHUNK_MALLOC_MAX < limit)
2747 limit = PNG_USER_CHUNK_MALLOC_MAX;
2748 # endif
2749
2750 if (length <= limit)
2751 {
2752 PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2753 /* The following is safe because of the PNG_SIZE_MAX init above */
2754 png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/;
2755 /* 'mode' is a flag array, only the bottom four bits matter here */
2756 png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2757
2758 if (length == 0)
2759 png_ptr->unknown_chunk.data = NULL;
2760
2761 else
2762 {
2763 /* Do a 'warn' here - it is handled below. */
2764 png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2765 png_malloc_warn(png_ptr, length));
2766 }
2767 }
2768
2769 if (png_ptr->unknown_chunk.data == NULL && length > 0)
2770 {
2771 /* This is benign because we clean up correctly */
2772 png_crc_finish(png_ptr, length);
2773 png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2774 return 0;
2775 }
2776
2777 else
2778 {
2779 if (length > 0)
2780 png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2781 png_crc_finish(png_ptr, 0);
2782 return 1;
2783 }
2784 }
2785 #endif /* READ_UNKNOWN_CHUNKS */
2786
2787 /* Handle an unknown, or known but disabled, chunk */
2788 void /* PRIVATE */
2789 png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2790 png_uint_32 length, int keep)
2791 {
2792 int handled = 0; /* the chunk was handled */
2793
2794 png_debug(1, "in png_handle_unknown");
2795
2796 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2797 /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2798 * the bug which meant that setting a non-default behavior for a specific
2799 * chunk would be ignored (the default was always used unless a user
2800 * callback was installed).
2801 *
2802 * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2803 * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2804 * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2805 * This is just an optimization to avoid multiple calls to the lookup
2806 * function.
2807 */
2808 # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2809 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2810 keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2811 # endif
2812 # endif
2813
2814 /* One of the following methods will read the chunk or skip it (at least one
2815 * of these is always defined because this is the only way to switch on
2816 * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2817 */
2818 # ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2819 /* The user callback takes precedence over the chunk keep value, but the
2820 * keep value is still required to validate a save of a critical chunk.
2821 */
2822 if (png_ptr->read_user_chunk_fn != NULL)
2823 {
2824 if (png_cache_unknown_chunk(png_ptr, length) != 0)
2825 {
2826 /* Callback to user unknown chunk handler */
2827 int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2828 &png_ptr->unknown_chunk);
2829
2830 /* ret is:
2831 * negative: An error occurred; png_chunk_error will be called.
2832 * zero: The chunk was not handled, the chunk will be discarded
2833 * unless png_set_keep_unknown_chunks has been used to set
2834 * a 'keep' behavior for this particular chunk, in which
2835 * case that will be used. A critical chunk will cause an
2836 * error at this point unless it is to be saved.
2837 * positive: The chunk was handled, libpng will ignore/discard it.
2838 */
2839 if (ret < 0)
2840 png_chunk_error(png_ptr, "error in user chunk");
2841
2842 else if (ret == 0)
2843 {
2844 /* If the keep value is 'default' or 'never' override it, but
2845 * still error out on critical chunks unless the keep value is
2846 * 'always' While this is weird it is the behavior in 1.4.12.
2847 * A possible improvement would be to obey the value set for the
2848 * chunk, but this would be an API change that would probably
2849 * damage some applications.
2850 *
2851 * The png_app_warning below catches the case that matters, where
2852 * the application has not set specific save or ignore for this
2853 * chunk or global save or ignore.
2854 */
2855 if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
2856 {
2857 # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2858 if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
2859 {
2860 png_chunk_warning(png_ptr, "Saving unknown chunk:");
2861 png_app_warning(png_ptr,
2862 "forcing save of an unhandled chunk;"
2863 " please call png_set_keep_unknown_chunks");
2864 /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
2865 }
2866 # endif
2867 keep = PNG_HANDLE_CHUNK_IF_SAFE;
2868 }
2869 }
2870
2871 else /* chunk was handled */
2872 {
2873 handled = 1;
2874 /* Critical chunks can be safely discarded at this point. */
2875 keep = PNG_HANDLE_CHUNK_NEVER;
2876 }
2877 }
2878
2879 else
2880 keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
2881 }
2882
2883 else
2884 /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
2885 # endif /* READ_USER_CHUNKS */
2886
2887 # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
2888 {
2889 /* keep is currently just the per-chunk setting, if there was no
2890 * setting change it to the global default now (not that this may
2891 * still be AS_DEFAULT) then obtain the cache of the chunk if required,
2892 * if not simply skip the chunk.
2893 */
2894 if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
2895 keep = png_ptr->unknown_default;
2896
2897 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2898 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2899 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2900 {
2901 if (png_cache_unknown_chunk(png_ptr, length) == 0)
2902 keep = PNG_HANDLE_CHUNK_NEVER;
2903 }
2904
2905 else
2906 png_crc_finish(png_ptr, length);
2907 }
2908 # else
2909 # ifndef PNG_READ_USER_CHUNKS_SUPPORTED
2910 # error no method to support READ_UNKNOWN_CHUNKS
2911 # endif
2912
2913 {
2914 /* If here there is no read callback pointer set and no support is
2915 * compiled in to just save the unknown chunks, so simply skip this
2916 * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then
2917 * the app has erroneously asked for unknown chunk saving when there
2918 * is no support.
2919 */
2920 if (keep > PNG_HANDLE_CHUNK_NEVER)
2921 png_app_error(png_ptr, "no unknown chunk support available");
2922
2923 png_crc_finish(png_ptr, length);
2924 }
2925 # endif
2926
2927 # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
2928 /* Now store the chunk in the chunk list if appropriate, and if the limits
2929 * permit it.
2930 */
2931 if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
2932 (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
2933 PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
2934 {
2935 # ifdef PNG_USER_LIMITS_SUPPORTED
2936 switch (png_ptr->user_chunk_cache_max)
2937 {
2938 case 2:
2939 png_ptr->user_chunk_cache_max = 1;
2940 png_chunk_benign_error(png_ptr, "no space in chunk cache");
2941 /* FALL THROUGH */
2942 case 1:
2943 /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
2944 * chunk being skipped, now there will be a hard error below.
2945 */
2946 break;
2947
2948 default: /* not at limit */
2949 --(png_ptr->user_chunk_cache_max);
2950 /* FALL THROUGH */
2951 case 0: /* no limit */
2952 # endif /* USER_LIMITS */
2953 /* Here when the limit isn't reached or when limits are compiled
2954 * out; store the chunk.
2955 */
2956 png_set_unknown_chunks(png_ptr, info_ptr,
2957 &png_ptr->unknown_chunk, 1);
2958 handled = 1;
2959 # ifdef PNG_USER_LIMITS_SUPPORTED
2960 break;
2961 }
2962 # endif
2963 }
2964 # else /* no store support: the chunk must be handled by the user callback */
2965 PNG_UNUSED(info_ptr)
2966 # endif
2967
2968 /* Regardless of the error handling below the cached data (if any) can be
2969 * freed now. Notice that the data is not freed if there is a png_error, but
2970 * it will be freed by destroy_read_struct.
2971 */
2972 if (png_ptr->unknown_chunk.data != NULL)
2973 png_free(png_ptr, png_ptr->unknown_chunk.data);
2974 png_ptr->unknown_chunk.data = NULL;
2975
2976 #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
2977 /* There is no support to read an unknown chunk, so just skip it. */
2978 png_crc_finish(png_ptr, length);
2979 PNG_UNUSED(info_ptr)
2980 PNG_UNUSED(keep)
2981 #endif /* !READ_UNKNOWN_CHUNKS */
2982
2983 /* Check for unhandled critical chunks */
2984 if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
2985 png_chunk_error(png_ptr, "unhandled critical chunk");
2986 }
2987
2988 /* This function is called to verify that a chunk name is valid.
2989 * This function can't have the "critical chunk check" incorporated
2990 * into it, since in the future we will need to be able to call user
2991 * functions to handle unknown critical chunks after we check that
2992 * the chunk name itself is valid.
2993 */
2994
2995 /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is:
2996 *
2997 * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
2998 */
2999
3000 void /* PRIVATE */
3001 png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name)
3002 {
3003 int i;
3004
3005 png_debug(1, "in png_check_chunk_name");
3006
3007 for (i=1; i<=4; ++i)
3008 {
3009 int c = chunk_name & 0xff;
3010
3011 if (c < 65 || c > 122 || (c > 90 && c < 97))
3012 png_chunk_error(png_ptr, "invalid chunk type");
3013
3014 chunk_name >>= 8;
3015 }
3016 }
3017
3018 /* Combines the row recently read in with the existing pixels in the row. This
3019 * routine takes care of alpha and transparency if requested. This routine also
3020 * handles the two methods of progressive display of interlaced images,
3021 * depending on the 'display' value; if 'display' is true then the whole row
3022 * (dp) is filled from the start by replicating the available pixels. If
3023 * 'display' is false only those pixels present in the pass are filled in.
3024 */
3025 void /* PRIVATE */
3026 png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3027 {
3028 unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3029 png_const_bytep sp = png_ptr->row_buf + 1;
3030 png_alloc_size_t row_width = png_ptr->width;
3031 unsigned int pass = png_ptr->pass;
3032 png_bytep end_ptr = 0;
3033 png_byte end_byte = 0;
3034 unsigned int end_mask;
3035
3036 png_debug(1, "in png_combine_row");
3037
3038 /* Added in 1.5.6: it should not be possible to enter this routine until at
3039 * least one row has been read from the PNG data and transformed.
3040 */
3041 if (pixel_depth == 0)
3042 png_error(png_ptr, "internal row logic error");
3043
3044 /* Added in 1.5.4: the pixel depth should match the information returned by
3045 * any call to png_read_update_info at this point. Do not continue if we got
3046 * this wrong.
3047 */
3048 if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3049 PNG_ROWBYTES(pixel_depth, row_width))
3050 png_error(png_ptr, "internal row size calculation error");
3051
3052 /* Don't expect this to ever happen: */
3053 if (row_width == 0)
3054 png_error(png_ptr, "internal row width error");
3055
3056 /* Preserve the last byte in cases where only part of it will be overwritten,
3057 * the multiply below may overflow, we don't care because ANSI-C guarantees
3058 * we get the low bits.
3059 */
3060 end_mask = (pixel_depth * row_width) & 7;
3061 if (end_mask != 0)
3062 {
3063 /* end_ptr == NULL is a flag to say do nothing */
3064 end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3065 end_byte = *end_ptr;
3066 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3067 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3068 /* little-endian byte */
3069 end_mask = 0xff << end_mask;
3070
3071 else /* big-endian byte */
3072 # endif
3073 end_mask = 0xff >> end_mask;
3074 /* end_mask is now the bits to *keep* from the destination row */
3075 }
3076
3077 /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3078 * will also happen if interlacing isn't supported or if the application
3079 * does not call png_set_interlace_handling(). In the latter cases the
3080 * caller just gets a sequence of the unexpanded rows from each interlace
3081 * pass.
3082 */
3083 #ifdef PNG_READ_INTERLACING_SUPPORTED
3084 if (png_ptr->interlaced != 0 &&
3085 (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3086 pass < 6 && (display == 0 ||
3087 /* The following copies everything for 'display' on passes 0, 2 and 4. */
3088 (display == 1 && (pass & 1) != 0)))
3089 {
3090 /* Narrow images may have no bits in a pass; the caller should handle
3091 * this, but this test is cheap:
3092 */
3093 if (row_width <= PNG_PASS_START_COL(pass))
3094 return;
3095
3096 if (pixel_depth < 8)
3097 {
3098 /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3099 * into 32 bits, then a single loop over the bytes using the four byte
3100 * values in the 32-bit mask can be used. For the 'display' option the
3101 * expanded mask may also not require any masking within a byte. To
3102 * make this work the PACKSWAP option must be taken into account - it
3103 * simply requires the pixels to be reversed in each byte.
3104 *
3105 * The 'regular' case requires a mask for each of the first 6 passes,
3106 * the 'display' case does a copy for the even passes in the range
3107 * 0..6. This has already been handled in the test above.
3108 *
3109 * The masks are arranged as four bytes with the first byte to use in
3110 * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3111 * not) of the pixels in each byte.
3112 *
3113 * NOTE: the whole of this logic depends on the caller of this function
3114 * only calling it on rows appropriate to the pass. This function only
3115 * understands the 'x' logic; the 'y' logic is handled by the caller.
3116 *
3117 * The following defines allow generation of compile time constant bit
3118 * masks for each pixel depth and each possibility of swapped or not
3119 * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index,
3120 * is in the range 0..7; and the result is 1 if the pixel is to be
3121 * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B'
3122 * for the block method.
3123 *
3124 * With some compilers a compile time expression of the general form:
3125 *
3126 * (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3127 *
3128 * Produces warnings with values of 'shift' in the range 33 to 63
3129 * because the right hand side of the ?: expression is evaluated by
3130 * the compiler even though it isn't used. Microsoft Visual C (various
3131 * versions) and the Intel C compiler are known to do this. To avoid
3132 * this the following macros are used in 1.5.6. This is a temporary
3133 * solution to avoid destabilizing the code during the release process.
3134 */
3135 # if PNG_USE_COMPILE_TIME_MASKS
3136 # define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3137 # define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3138 # else
3139 # define PNG_LSR(x,s) ((x)>>(s))
3140 # define PNG_LSL(x,s) ((x)<<(s))
3141 # endif
3142 # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3143 PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3144 # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3145 PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3146
3147 /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is
3148 * little endian - the first pixel is at bit 0 - however the extra
3149 * parameter 's' can be set to cause the mask position to be swapped
3150 * within each byte, to match the PNG format. This is done by XOR of
3151 * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3152 */
3153 # define PIXEL_MASK(p,x,d,s) \
3154 (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3155
3156 /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3157 */
3158 # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3159 # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3160
3161 /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp
3162 * cases the result needs replicating, for the 4-bpp case the above
3163 * generates a full 32 bits.
3164 */
3165 # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3166
3167 # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3168 S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3169 S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3170
3171 # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3172 B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3173 B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3174
3175 #if PNG_USE_COMPILE_TIME_MASKS
3176 /* Utility macros to construct all the masks for a depth/swap
3177 * combination. The 's' parameter says whether the format is PNG
3178 * (big endian bytes) or not. Only the three odd-numbered passes are
3179 * required for the display/block algorithm.
3180 */
3181 # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3182 S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3183
3184 # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3185
3186 # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3187
3188 /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3189 * then pass:
3190 */
3191 static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3192 {
3193 /* Little-endian byte masks for PACKSWAP */
3194 { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3195 /* Normal (big-endian byte) masks - PNG format */
3196 { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3197 };
3198
3199 /* display_mask has only three entries for the odd passes, so index by
3200 * pass>>1.
3201 */
3202 static PNG_CONST png_uint_32 display_mask[2][3][3] =
3203 {
3204 /* Little-endian byte masks for PACKSWAP */
3205 { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3206 /* Normal (big-endian byte) masks - PNG format */
3207 { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3208 };
3209
3210 # define MASK(pass,depth,display,png)\
3211 ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3212 row_mask[png][DEPTH_INDEX(depth)][pass])
3213
3214 #else /* !PNG_USE_COMPILE_TIME_MASKS */
3215 /* This is the runtime alternative: it seems unlikely that this will
3216 * ever be either smaller or faster than the compile time approach.
3217 */
3218 # define MASK(pass,depth,display,png)\
3219 ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3220 #endif /* !USE_COMPILE_TIME_MASKS */
3221
3222 /* Use the appropriate mask to copy the required bits. In some cases
3223 * the byte mask will be 0 or 0xff; optimize these cases. row_width is
3224 * the number of pixels, but the code copies bytes, so it is necessary
3225 * to special case the end.
3226 */
3227 png_uint_32 pixels_per_byte = 8 / pixel_depth;
3228 png_uint_32 mask;
3229
3230 # ifdef PNG_READ_PACKSWAP_SUPPORTED
3231 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3232 mask = MASK(pass, pixel_depth, display, 0);
3233
3234 else
3235 # endif
3236 mask = MASK(pass, pixel_depth, display, 1);
3237
3238 for (;;)
3239 {
3240 png_uint_32 m;
3241
3242 /* It doesn't matter in the following if png_uint_32 has more than
3243 * 32 bits because the high bits always match those in m<<24; it is,
3244 * however, essential to use OR here, not +, because of this.
3245 */
3246 m = mask;
3247 mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3248 m &= 0xff;
3249
3250 if (m != 0) /* something to copy */
3251 {
3252 if (m != 0xff)
3253 *dp = (png_byte)((*dp & ~m) | (*sp & m));
3254 else
3255 *dp = *sp;
3256 }
3257
3258 /* NOTE: this may overwrite the last byte with garbage if the image
3259 * is not an exact number of bytes wide; libpng has always done
3260 * this.
3261 */
3262 if (row_width <= pixels_per_byte)
3263 break; /* May need to restore part of the last byte */
3264
3265 row_width -= pixels_per_byte;
3266 ++dp;
3267 ++sp;
3268 }
3269 }
3270
3271 else /* pixel_depth >= 8 */
3272 {
3273 unsigned int bytes_to_copy, bytes_to_jump;
3274
3275 /* Validate the depth - it must be a multiple of 8 */
3276 if (pixel_depth & 7)
3277 png_error(png_ptr, "invalid user transform pixel depth");
3278
3279 pixel_depth >>= 3; /* now in bytes */
3280 row_width *= pixel_depth;
3281
3282 /* Regardless of pass number the Adam 7 interlace always results in a
3283 * fixed number of pixels to copy then to skip. There may be a
3284 * different number of pixels to skip at the start though.
3285 */
3286 {
3287 unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3288
3289 row_width -= offset;
3290 dp += offset;
3291 sp += offset;
3292 }
3293
3294 /* Work out the bytes to copy. */
3295 if (display != 0)
3296 {
3297 /* When doing the 'block' algorithm the pixel in the pass gets
3298 * replicated to adjacent pixels. This is why the even (0,2,4,6)
3299 * passes are skipped above - the entire expanded row is copied.
3300 */
3301 bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3302
3303 /* But don't allow this number to exceed the actual row width. */
3304 if (bytes_to_copy > row_width)
3305 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3306 }
3307
3308 else /* normal row; Adam7 only ever gives us one pixel to copy. */
3309 bytes_to_copy = pixel_depth;
3310
3311 /* In Adam7 there is a constant offset between where the pixels go. */
3312 bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3313
3314 /* And simply copy these bytes. Some optimization is possible here,
3315 * depending on the value of 'bytes_to_copy'. Special case the low
3316 * byte counts, which we know to be frequent.
3317 *
3318 * Notice that these cases all 'return' rather than 'break' - this
3319 * avoids an unnecessary test on whether to restore the last byte
3320 * below.
3321 */
3322 switch (bytes_to_copy)
3323 {
3324 case 1:
3325 for (;;)
3326 {
3327 *dp = *sp;
3328
3329 if (row_width <= bytes_to_jump)
3330 return;
3331
3332 dp += bytes_to_jump;
3333 sp += bytes_to_jump;
3334 row_width -= bytes_to_jump;
3335 }
3336
3337 case 2:
3338 /* There is a possibility of a partial copy at the end here; this
3339 * slows the code down somewhat.
3340 */
3341 do
3342 {
3343 dp[0] = sp[0], dp[1] = sp[1];
3344
3345 if (row_width <= bytes_to_jump)
3346 return;
3347
3348 sp += bytes_to_jump;
3349 dp += bytes_to_jump;
3350 row_width -= bytes_to_jump;
3351 }
3352 while (row_width > 1);
3353
3354 /* And there can only be one byte left at this point: */
3355 *dp = *sp;
3356 return;
3357
3358 case 3:
3359 /* This can only be the RGB case, so each copy is exactly one
3360 * pixel and it is not necessary to check for a partial copy.
3361 */
3362 for (;;)
3363 {
3364 dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2];
3365
3366 if (row_width <= bytes_to_jump)
3367 return;
3368
3369 sp += bytes_to_jump;
3370 dp += bytes_to_jump;
3371 row_width -= bytes_to_jump;
3372 }
3373
3374 default:
3375 #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3376 /* Check for double byte alignment and, if possible, use a
3377 * 16-bit copy. Don't attempt this for narrow images - ones that
3378 * are less than an interlace panel wide. Don't attempt it for
3379 * wide bytes_to_copy either - use the memcpy there.
3380 */
3381 if (bytes_to_copy < 16 /*else use memcpy*/ &&
3382 png_isaligned(dp, png_uint_16) &&
3383 png_isaligned(sp, png_uint_16) &&
3384 bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3385 bytes_to_jump % (sizeof (png_uint_16)) == 0)
3386 {
3387 /* Everything is aligned for png_uint_16 copies, but try for
3388 * png_uint_32 first.
3389 */
3390 if (png_isaligned(dp, png_uint_32) != 0 &&
3391 png_isaligned(sp, png_uint_32) != 0 &&
3392 bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3393 bytes_to_jump % (sizeof (png_uint_32)) == 0)
3394 {
3395 png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3396 png_const_uint_32p sp32 = png_aligncastconst(
3397 png_const_uint_32p, sp);
3398 size_t skip = (bytes_to_jump-bytes_to_copy) /
3399 (sizeof (png_uint_32));
3400
3401 do
3402 {
3403 size_t c = bytes_to_copy;
3404 do
3405 {
3406 *dp32++ = *sp32++;
3407 c -= (sizeof (png_uint_32));
3408 }
3409 while (c > 0);
3410
3411 if (row_width <= bytes_to_jump)
3412 return;
3413
3414 dp32 += skip;
3415 sp32 += skip;
3416 row_width -= bytes_to_jump;
3417 }
3418 while (bytes_to_copy <= row_width);
3419
3420 /* Get to here when the row_width truncates the final copy.
3421 * There will be 1-3 bytes left to copy, so don't try the
3422 * 16-bit loop below.
3423 */
3424 dp = (png_bytep)dp32;
3425 sp = (png_const_bytep)sp32;
3426 do
3427 *dp++ = *sp++;
3428 while (--row_width > 0);
3429 return;
3430 }
3431
3432 /* Else do it in 16-bit quantities, but only if the size is
3433 * not too large.
3434 */
3435 else
3436 {
3437 png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3438 png_const_uint_16p sp16 = png_aligncastconst(
3439 png_const_uint_16p, sp);
3440 size_t skip = (bytes_to_jump-bytes_to_copy) /
3441 (sizeof (png_uint_16));
3442
3443 do
3444 {
3445 size_t c = bytes_to_copy;
3446 do
3447 {
3448 *dp16++ = *sp16++;
3449 c -= (sizeof (png_uint_16));
3450 }
3451 while (c > 0);
3452
3453 if (row_width <= bytes_to_jump)
3454 return;
3455
3456 dp16 += skip;
3457 sp16 += skip;
3458 row_width -= bytes_to_jump;
3459 }
3460 while (bytes_to_copy <= row_width);
3461
3462 /* End of row - 1 byte left, bytes_to_copy > row_width: */
3463 dp = (png_bytep)dp16;
3464 sp = (png_const_bytep)sp16;
3465 do
3466 *dp++ = *sp++;
3467 while (--row_width > 0);
3468 return;
3469 }
3470 }
3471 #endif /* ALIGN_TYPE code */
3472
3473 /* The true default - use a memcpy: */
3474 for (;;)
3475 {
3476 memcpy(dp, sp, bytes_to_copy);
3477
3478 if (row_width <= bytes_to_jump)
3479 return;
3480
3481 sp += bytes_to_jump;
3482 dp += bytes_to_jump;
3483 row_width -= bytes_to_jump;
3484 if (bytes_to_copy > row_width)
3485 bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3486 }
3487 }
3488
3489 /* NOT REACHED*/
3490 } /* pixel_depth >= 8 */
3491
3492 /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3493 }
3494 else
3495 #endif /* READ_INTERLACING */
3496
3497 /* If here then the switch above wasn't used so just memcpy the whole row
3498 * from the temporary row buffer (notice that this overwrites the end of the
3499 * destination row if it is a partial byte.)
3500 */
3501 memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3502
3503 /* Restore the overwritten bits from the last byte if necessary. */
3504 if (end_ptr != NULL)
3505 *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3506 }
3507
3508 #ifdef PNG_READ_INTERLACING_SUPPORTED
3509 void /* PRIVATE */
3510 png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3511 png_uint_32 transformations /* Because these may affect the byte layout */)
3512 {
3513 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
3514 /* Offset to next interlace block */
3515 static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
3516
3517 png_debug(1, "in png_do_read_interlace");
3518 if (row != NULL && row_info != NULL)
3519 {
3520 png_uint_32 final_width;
3521
3522 final_width = row_info->width * png_pass_inc[pass];
3523
3524 switch (row_info->pixel_depth)
3525 {
3526 case 1:
3527 {
3528 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
3529 png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
3530 int sshift, dshift;
3531 int s_start, s_end, s_inc;
3532 int jstop = png_pass_inc[pass];
3533 png_byte v;
3534 png_uint_32 i;
3535 int j;
3536
3537 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3538 if ((transformations & PNG_PACKSWAP) != 0)
3539 {
3540 sshift = (int)((row_info->width + 7) & 0x07);
3541 dshift = (int)((final_width + 7) & 0x07);
3542 s_start = 7;
3543 s_end = 0;
3544 s_inc = -1;
3545 }
3546
3547 else
3548 #endif
3549 {
3550 sshift = 7 - (int)((row_info->width + 7) & 0x07);
3551 dshift = 7 - (int)((final_width + 7) & 0x07);
3552 s_start = 0;
3553 s_end = 7;
3554 s_inc = 1;
3555 }
3556
3557 for (i = 0; i < row_info->width; i++)
3558 {
3559 v = (png_byte)((*sp >> sshift) & 0x01);
3560 for (j = 0; j < jstop; j++)
3561 {
3562 unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3563 tmp |= v << dshift;
3564 *dp = (png_byte)(tmp & 0xff);
3565
3566 if (dshift == s_end)
3567 {
3568 dshift = s_start;
3569 dp--;
3570 }
3571
3572 else
3573 dshift += s_inc;
3574 }
3575
3576 if (sshift == s_end)
3577 {
3578 sshift = s_start;
3579 sp--;
3580 }
3581
3582 else
3583 sshift += s_inc;
3584 }
3585 break;
3586 }
3587
3588 case 2:
3589 {
3590 png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3591 png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3592 int sshift, dshift;
3593 int s_start, s_end, s_inc;
3594 int jstop = png_pass_inc[pass];
3595 png_uint_32 i;
3596
3597 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3598 if ((transformations & PNG_PACKSWAP) != 0)
3599 {
3600 sshift = (int)(((row_info->width + 3) & 0x03) << 1);
3601 dshift = (int)(((final_width + 3) & 0x03) << 1);
3602 s_start = 6;
3603 s_end = 0;
3604 s_inc = -2;
3605 }
3606
3607 else
3608 #endif
3609 {
3610 sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
3611 dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
3612 s_start = 0;
3613 s_end = 6;
3614 s_inc = 2;
3615 }
3616
3617 for (i = 0; i < row_info->width; i++)
3618 {
3619 png_byte v;
3620 int j;
3621
3622 v = (png_byte)((*sp >> sshift) & 0x03);
3623 for (j = 0; j < jstop; j++)
3624 {
3625 unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
3626 tmp |= v << dshift;
3627 *dp = (png_byte)(tmp & 0xff);
3628
3629 if (dshift == s_end)
3630 {
3631 dshift = s_start;
3632 dp--;
3633 }
3634
3635 else
3636 dshift += s_inc;
3637 }
3638
3639 if (sshift == s_end)
3640 {
3641 sshift = s_start;
3642 sp--;
3643 }
3644
3645 else
3646 sshift += s_inc;
3647 }
3648 break;
3649 }
3650
3651 case 4:
3652 {
3653 png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
3654 png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
3655 int sshift, dshift;
3656 int s_start, s_end, s_inc;
3657 png_uint_32 i;
3658 int jstop = png_pass_inc[pass];
3659
3660 #ifdef PNG_READ_PACKSWAP_SUPPORTED
3661 if ((transformations & PNG_PACKSWAP) != 0)
3662 {
3663 sshift = (int)(((row_info->width + 1) & 0x01) << 2);
3664 dshift = (int)(((final_width + 1) & 0x01) << 2);
3665 s_start = 4;
3666 s_end = 0;
3667 s_inc = -4;
3668 }
3669
3670 else
3671 #endif
3672 {
3673 sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
3674 dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
3675 s_start = 0;
3676 s_end = 4;
3677 s_inc = 4;
3678 }
3679
3680 for (i = 0; i < row_info->width; i++)
3681 {
3682 png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
3683 int j;
3684
3685 for (j = 0; j < jstop; j++)
3686 {
3687 unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
3688 tmp |= v << dshift;
3689 *dp = (png_byte)(tmp & 0xff);
3690
3691 if (dshift == s_end)
3692 {
3693 dshift = s_start;
3694 dp--;
3695 }
3696
3697 else
3698 dshift += s_inc;
3699 }
3700
3701 if (sshift == s_end)
3702 {
3703 sshift = s_start;
3704 sp--;
3705 }
3706
3707 else
3708 sshift += s_inc;
3709 }
3710 break;
3711 }
3712
3713 default:
3714 {
3715 png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
3716