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