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