Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4460 lines
142KB

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