Hint added.
[AROS.git] / workbench / libs / png / contrib / tools / pngfix.c
blob63d70116944f7938e6f6b02dbcd17b0b1f57805e
1 /* pngfix.c
3 * Copyright (c) 2013 John Cunningham Bowler
5 * Last changed in libpng 1.6.3 [July 18, 2013]
7 * This code is released under the libpng license.
8 * For conditions of distribution and use, see the disclaimer
9 * and license in png.h
11 * Tool to check and fix the zlib inflate 'too far back' problem, see the usage
12 * message for more information.
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <assert.h>
21 #define implies(x,y) assert(!(x) || (y))
23 #ifdef __GNUC__
24 /* This is used to fix the error:
26 * pngfix.c:
27 * In function 'zlib_advance':
28 * pngfix.c:181:13: error: assuming signed overflow does not
29 * occur when simplifying conditional to constant [-Werror=strict-overflow]
31 # define FIX_GCC volatile
32 #else
33 # define FIX_GCC
34 # error not tested
35 #endif
37 #define PROGRAM_NAME "pngfix"
39 /* Define the following to use this program against your installed libpng,
40 * rather than the one being built here:
42 #ifdef PNG_FREESTANDING_TESTS
43 # include <png.h>
44 #else
45 # include "../../png.h"
46 #endif
48 #if PNG_LIBPNG_VER < 10603 /* 1.6.3 */
49 # error "pngfix will not work with libpng prior to 1.6.3"
50 #endif
52 #ifdef PNG_READ_SUPPORTED
53 #include <zlib.h>
55 #ifndef PNG_MAXIMUM_INFLATE_WINDOW
56 # error "pngfix not supported in this libpng version"
57 #endif
59 #if PNG_ZLIB_VERNUM >= 0x1240
61 /* Copied from pngpriv.h */
62 #ifdef __cplusplus
63 # define png_voidcast(type, value) static_cast<type>(value)
64 # define png_constcast(type, value) const_cast<type>(value)
65 # define png_aligncast(type, value) \
66 static_cast<type>(static_cast<void*>(value))
67 # define png_aligncastconst(type, value) \
68 static_cast<type>(static_cast<const void*>(value))
69 #else
70 # define png_voidcast(type, value) (value)
71 # define png_constcast(type, value) ((type)(value))
72 # define png_aligncast(type, value) ((void*)(value))
73 # define png_aligncastconst(type, value) ((const void*)(value))
74 #endif /* __cplusplus */
76 #if PNG_LIBPNG_VER < 10700
77 /* Chunk tags (copied from pngpriv.h) */
78 #define PNG_32b(b,s) ((png_uint_32)(b) << (s))
79 #define PNG_U32(b1,b2,b3,b4) \
80 (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
82 /* Constants for known chunk types. */
83 #define png_IDAT PNG_U32( 73, 68, 65, 84)
84 #define png_IEND PNG_U32( 73, 69, 78, 68)
85 #define png_IHDR PNG_U32( 73, 72, 68, 82)
86 #define png_PLTE PNG_U32( 80, 76, 84, 69)
87 #define png_bKGD PNG_U32( 98, 75, 71, 68)
88 #define png_cHRM PNG_U32( 99, 72, 82, 77)
89 #define png_fRAc PNG_U32(102, 82, 65, 99) /* registered, not defined */
90 #define png_gAMA PNG_U32(103, 65, 77, 65)
91 #define png_gIFg PNG_U32(103, 73, 70, 103)
92 #define png_gIFt PNG_U32(103, 73, 70, 116) /* deprecated */
93 #define png_gIFx PNG_U32(103, 73, 70, 120)
94 #define png_hIST PNG_U32(104, 73, 83, 84)
95 #define png_iCCP PNG_U32(105, 67, 67, 80)
96 #define png_iTXt PNG_U32(105, 84, 88, 116)
97 #define png_oFFs PNG_U32(111, 70, 70, 115)
98 #define png_pCAL PNG_U32(112, 67, 65, 76)
99 #define png_pHYs PNG_U32(112, 72, 89, 115)
100 #define png_sBIT PNG_U32(115, 66, 73, 84)
101 #define png_sCAL PNG_U32(115, 67, 65, 76)
102 #define png_sPLT PNG_U32(115, 80, 76, 84)
103 #define png_sRGB PNG_U32(115, 82, 71, 66)
104 #define png_sTER PNG_U32(115, 84, 69, 82)
105 #define png_tEXt PNG_U32(116, 69, 88, 116)
106 #define png_tIME PNG_U32(116, 73, 77, 69)
107 #define png_tRNS PNG_U32(116, 82, 78, 83)
108 #define png_zTXt PNG_U32(122, 84, 88, 116)
109 #endif
111 /* The 8 byte signature as a pair of 32 bit quantities */
112 #define sig1 PNG_U32(137, 80, 78, 71)
113 #define sig2 PNG_U32( 13, 10, 26, 10)
115 /* Is the chunk critical? */
116 #define CRITICAL(chunk) (((chunk) & PNG_U32(32,0,0,0)) == 0)
118 /* Is it safe to copy? */
119 #define SAFE_TO_COPY(chunk) (((chunk) & PNG_U32(0,0,0,32)) != 0)
121 /********************************* UTILITIES **********************************/
122 /* UNREACHED is a value to cause an assert to fail. Because of the way the
123 * assert macro is written the string "UNREACHED" is produced in the error
124 * message.
126 #define UNREACHED 0
128 /* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8 byte
129 * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so
130 * arithmetic of 80-bit numbers is sufficient. This representation uses an
131 * arbitrary length array of png_uint_16 digits (0..65535). The representation
132 * is little endian.
134 * The arithmetic functions take zero to two uarb values together with the
135 * number of digits in those values and write the result to the given uarb
136 * (always the first argument) returning the number of digits in the result.
137 * If the result is negative the return value is also negative (this would
138 * normally be an error).
140 typedef png_uint_16 udigit; /* A 'unum' is an array of these */
141 typedef png_uint_16p uarb;
142 typedef png_const_uint_16p uarbc;
144 #define UDIGITS(unum) ((sizeof unum)/(sizeof (udigit))
145 /* IMPORTANT: only apply this to an array, applied to a pointer the result
146 * will typically be '2', which is not useful.
149 static int
150 uarb_set(uarb result, png_alloc_size_t val)
151 /* Set (initialize) 'result' to 'val'. The size required for 'result' must
152 * be determined by the caller from a knowledge of the maximum for 'val'.
155 int ndigits = 0;
157 while (val > 0)
159 result[ndigits++] = (png_uint_16)(val & 0xffff);
160 val >>= 16;
163 return ndigits;
166 static int
167 uarb_copy(uarb to, uarb from, int idigits)
168 /* Copy a uarb, may reduce the digit count */
170 int d, odigits;
172 for (d=odigits=0; d<idigits; ++d)
173 if ((to[d] = from[d]) != 0)
174 odigits = d+1;
176 return odigits;
179 static int
180 uarb_inc(uarb num, int in_digits, png_int_32 add)
181 /* This is a signed 32-bit add, except that to avoid overflow the value added
182 * or subtracted must be no more than 2^31-65536. A negative result
183 * indicates a negative number (which is an error below). The size of
184 * 'num' should be max(in_digits+1,2) for arbitrary 'add' but can be just
185 * in_digits+1 if add is known to be in the range -65535..65535.
188 FIX_GCC int out_digits = 0;
190 while (out_digits < in_digits)
192 add += num[out_digits];
193 num[out_digits++] = (png_uint_16)(add & 0xffff);
194 add >>= 16;
197 while (add != 0 && add != (-1))
199 num[out_digits++] = (png_uint_16)(add & 0xffff);
200 add >>= 16;
203 if (add == 0)
205 while (out_digits > 0 && num[out_digits-1] == 0)
206 --out_digits;
207 return out_digits; /* may be 0 */
210 else /* negative result */
212 while (out_digits > 1 && num[out_digits-1] == 0xffff)
213 --out_digits;
215 return -out_digits;
219 static int
220 uarb_add32(uarb num, int in_digits, png_uint_32 add)
221 /* As above but this works with any 32-bit value and only does 'add' */
223 if (in_digits > 0)
225 in_digits = uarb_inc(num, in_digits, add & 0xffff);
226 return uarb_inc(num+1, in_digits-1, add >> 16)+1;
229 return uarb_set(num, add);
232 static int
233 uarb_mult_digit(uarb acc, int a_digits, uarb num, FIX_GCC int n_digits,
234 png_uint_16 val)
235 /* Primitive one-digit multiply - 'val' must be 0..65535. Note that this
236 * primitive is a multiply and accumulate - the result of *num * val is added
237 * to *acc.
239 * This is a one-digit multiply, so the product may be up to one digit longer
240 * than 'num', however the add to 'acc' means that the caller must ensure
241 * that 'acc' is at least one digit longer than this *and* at least one digit
242 * longer than the current length of 'acc'. (Or the caller must otherwise
243 * ensure 'adigits' is adequate from knowledge of the values.)
246 /* The digits in *acc, *num and val are in the range 0..65535, so the
247 * result below is at most (65535*65535)+2*65635 = 65535*(65535+2), which is
248 * exactly 0xffffffff.
250 if (val > 0 && n_digits > 0) /* Else the product is 0 */
252 png_uint_32 carry = 0;
253 int out_digits = 0;
255 while (out_digits < n_digits || carry > 0)
257 if (out_digits < a_digits)
258 carry += acc[out_digits];
260 if (out_digits < n_digits)
261 carry += (png_uint_32)num[out_digits] * val;
263 acc[out_digits++] = (png_uint_16)(carry & 0xffff);
264 carry >>= 16;
267 /* So carry is 0 and all the input digits have been consumed. This means
268 * that it is possible to skip any remaining digits in acc.
270 if (out_digits > a_digits)
271 return out_digits;
274 return a_digits;
277 static int
278 uarb_mult32(uarb acc, int a_digits, uarb num, int n_digits, png_uint_32 val)
279 /* calculate acc += num * val, 'val' may be any 32-bit value, 'acc' and 'num'
280 * may be any value, returns the number of digits in 'acc'.
283 if (n_digits > 0 && val > 0)
285 a_digits = uarb_mult_digit(acc, a_digits, num, n_digits,
286 (png_uint_16)(val & 0xffff));
288 /* Because n_digits and val are >0 the following must be true: */
289 assert(a_digits > 0);
291 val >>= 16;
292 if (val > 0)
293 a_digits = uarb_mult_digit(acc+1, a_digits-1, num, n_digits,
294 (png_uint_16)val) + 1;
297 return a_digits;
300 static int
301 uarb_shift(uarb inout, int ndigits, unsigned int right_shift)
302 /* Shift inout right by right_shift bits, right_shift must be in the range
303 * 1..15
306 FIX_GCC int i = ndigits;
307 png_uint_16 carry = 0;
309 assert(right_shift >= 1 && right_shift <= 15);
311 while (--i >= 0)
313 png_uint_16 temp = (png_uint_16)(carry | (inout[i] >> right_shift));
315 /* Bottom bits to top bits of carry */
316 carry = (png_uint_16)((inout[i] << (16-right_shift)) & 0xffff);
318 inout[i] = temp;
320 /* The shift may reduce ndigits */
321 if (i == ndigits-1 && temp == 0)
322 ndigits = i;
325 return ndigits;
328 static int
329 uarb_cmp(uarb a, int adigits, uarb b, int bdigits)
330 /* Return -1/0/+1 according as a<b/a==b/a>b */
332 if (adigits < bdigits)
333 return -1;
335 if (adigits > bdigits)
336 return 1;
338 while (adigits-- > 0)
339 if (a[adigits] < b[adigits])
340 return -1;
342 else if (a[adigits] > b[adigits])
343 return 1;
345 return 0;
348 #if 0 /*UNUSED*/
349 static int
350 uarb_eq32(uarb num, int digits, png_uint_32 val)
351 /* Return true if the uarb is equal to 'val' */
353 switch (digits)
355 case 0: return val == 0;
356 case 1: return val == num[0];
357 case 2: return (val & 0xffff) == num[0] && (val >> 16) == num[1];
358 default: return 0;
361 #endif
363 static void
364 uarb_printx(uarb num, int digits, FILE *out)
365 /* Print 'num' as a hexadecimal number (easier than decimal!) */
367 while (digits > 0)
368 if (num[--digits] > 0)
370 fprintf(out, "0x%x", num[digits]);
372 while (digits > 0)
373 fprintf(out, "%.4x", num[--digits]);
376 else if (digits == 0) /* the number is 0 */
377 fputs("0x0", out);
380 static void
381 uarb_print(uarb num, int digits, FILE *out)
382 /* Prints 'num' as a decimal if it will fit in an unsigned long, else as a
383 * hexadecimal number. Notice that the results vary for images over 4GByte
384 * in a system dependent way, and the hexadecimal form doesn't work very well
385 * in awk script input.
388 * TODO: write uarb_div10
391 if (digits * sizeof (udigit) > sizeof (unsigned long))
392 uarb_printx(num, digits, out);
394 else
396 unsigned long n = 0;
398 while (digits > 0)
399 n = (n << 16) + num[--digits];
401 fprintf(out, "%lu", n);
405 /* Generate random bytes. This uses a boring repeatable algorithm and it
406 * is implemented here so that it gives the same set of numbers on every
407 * architecture. It's a linear congruential generator (Knuth or Sedgewick
408 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
409 * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
410 * Generation.)
412 * (Copied from contrib/libtests/pngvalid.c)
414 static void
415 make_random_bytes(png_uint_32* seed, void* pv, size_t size)
417 png_uint_32 u0 = seed[0], u1 = seed[1];
418 png_bytep bytes = png_voidcast(png_bytep, pv);
420 /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
421 * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
423 size_t i;
424 for (i=0; i<size; ++i)
426 /* First generate 8 new bits then shift them in at the end. */
427 png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
428 u1 <<= 8;
429 u1 |= u0 >> 24;
430 u0 <<= 8;
431 u0 |= u;
432 *bytes++ = (png_byte)u;
435 seed[0] = u0;
436 seed[1] = u1;
439 /* Clear an object to a random value. */
440 static void
441 clear(void *pv, size_t size)
443 static png_uint_32 clear_seed[2] = { 0x12345678, 0x9abcdef0 };
444 make_random_bytes(clear_seed, pv, size);
447 #define CLEAR(object) clear(&(object), sizeof (object))
449 /* Copied from unreleased 1.7 code.
451 * CRC checking uses a local pre-built implementation of the Ethernet CRC32.
452 * This is to avoid a function call to the zlib DLL and to optimize the
453 * byte-by-byte case.
455 static png_uint_32 crc_table[256] =
457 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
458 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
459 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
460 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
461 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
462 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
463 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
464 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
465 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
466 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
467 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
468 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
469 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
470 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
471 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
472 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
473 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
474 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
475 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
476 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
477 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
478 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
479 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
480 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
481 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
482 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
483 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
484 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
485 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
486 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
487 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
488 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
489 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
490 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
491 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
492 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
493 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
494 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
495 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
496 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
497 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
498 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
499 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
500 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
501 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
502 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
503 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
504 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
505 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
506 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
507 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
508 0x2d02ef8d
511 /* The CRC calculated here *IS* conditioned, the corresponding value used by
512 * zlib and the result value is obtained by XORing with CRC_INIT, which is also
513 * the first value that must be passed in (for the first byte) to crc_one_byte.
515 #define CRC_INIT 0xffffffff
517 static png_uint_32
518 crc_one_byte(png_uint_32 crc, int b)
520 return crc_table[(crc ^ b) & 0xff] ^ (crc >> 8);
523 static png_uint_32
524 crc_init_4(png_uint_32 value)
526 /* This is an alternative to the algorithm used in zlib, which requires four
527 * separate tables to parallelize the four byte operations, it only works for
528 * a CRC of the first four bytes of the stream, but this is what happens in
529 * the parser below where length+chunk-name is read and chunk-name used to
530 * initialize the CRC. Notice that the calculation here avoids repeated
531 * conditioning (xor with 0xffffffff) by storing the conditioned value.
533 png_uint_32 crc = crc_table[(~value >> 24)] ^ 0xffffff;
535 crc = crc_table[(crc ^ (value >> 16)) & 0xff] ^ (crc >> 8);
536 crc = crc_table[(crc ^ (value >> 8)) & 0xff] ^ (crc >> 8);
537 return crc_table[(crc ^ value) & 0xff] ^ (crc >> 8);
540 static int
541 chunk_type_valid(png_uint_32 c)
542 /* Bit whacking approach to chunk name validation that is intended to avoid
543 * branches. The cost is that it uses a lot of 32-bit constants, which might
544 * be bad on some architectures.
547 png_uint_32 t;
549 /* Remove bit 5 from all but the reserved byte; this means every
550 * 8-bit unit must be in the range 65-90 to be valid. So bit 5
551 * must be zero, bit 6 must be set and bit 7 zero.
553 c &= ~PNG_U32(32,32,0,32);
554 t = (c & ~0x1f1f1f1f) ^ 0x40404040;
556 /* Subtract 65 for each 8 bit quantity, this must not overflow
557 * and each byte must then be in the range 0-25.
559 c -= PNG_U32(65,65,65,65);
560 t |=c ;
562 /* Subtract 26, handling the overflow which should set the top
563 * three bits of each byte.
565 c -= PNG_U32(25,25,25,26);
566 t |= ~c;
568 return (t & 0xe0e0e0e0) == 0;
571 /**************************** CONTROL INFORMATION *****************************/
573 /* Information about a sequence of IDAT chunks, the chunks have been re-synced
574 * using sync_stream below and the new lengths are recorded here. Because the
575 * number of chunks is unlimited this is handled using a linked list of these
576 * structures.
578 struct IDAT_list
580 struct IDAT_list *next; /* Linked list */
581 unsigned int length; /* Actual length of the array below */
582 unsigned int count; /* Number of entries that are valid */
583 # define IDAT_INIT_LENGTH 16
584 png_uint_32 lengths[IDAT_INIT_LENGTH];
587 static void
588 IDAT_list_init(struct IDAT_list *list)
590 CLEAR(*list);
592 list->next = NULL;
593 list->length = IDAT_INIT_LENGTH;
596 static size_t
597 IDAT_list_size(struct IDAT_list *list, unsigned int length)
598 /* Return the size in bytes of an IDAT_list of the given length. */
600 if (list != NULL)
601 length = list->length;
603 return sizeof *list - sizeof list->lengths +
604 length * sizeof list->lengths[0];
607 static void
608 IDAT_list_end(struct IDAT_list *IDAT_list)
610 struct IDAT_list *list = IDAT_list->next;
612 CLEAR(*IDAT_list);
614 while (list != NULL)
616 struct IDAT_list *next = list->next;
618 clear(list, IDAT_list_size(list, 0));
619 free(list);
620 list = next;
624 static struct IDAT_list *
625 IDAT_list_extend(struct IDAT_list *tail)
627 /* Use the previous cached value if available. */
628 struct IDAT_list *next = tail->next;
630 if (next == NULL)
632 /* Insert a new, malloc'ed, block of IDAT information buffers, this
633 * one twice as large as the previous one:
635 unsigned int length = 2 * tail->length;
637 if (length < tail->length) /* arithmetic overflow */
638 length = tail->length;
640 next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
641 CLEAR(*next);
643 /* The caller must handle this: */
644 if (next == NULL)
645 return NULL;
647 next->next = NULL;
648 next->length = length;
649 tail->next = next;
652 return next;
655 /* GLOBAL CONTROL STRUCTURE */
656 struct global
658 /* PUBLIC GLOBAL VARIABLES: OWNER INITIALIZE */
659 unsigned int errors :1; /* print file errors to stderr */
660 unsigned int warnings :1; /* print libpng warnings to stderr */
661 unsigned int optimize_zlib :1; /* Run optimization search */
662 unsigned int quiet :2; /* don't output summaries */
663 unsigned int verbose :3; /* various internal tracking */
664 unsigned int skip :3; /* Non-critical chunks to skip */
665 # define SKIP_NONE 0
666 # define SKIP_BAD_CRC 1 /* Chunks with a bad CRC */
667 # define SKIP_UNSAFE 2 /* Chunks not safe to copy */
668 # define SKIP_UNUSED 3 /* Chunks not used by libpng */
669 # define SKIP_TRANSFORM 4 /* Chunks only used in transforms */
670 # define SKIP_COLOR 5 /* Everything but tRNS, sBIT, gAMA and sRGB */
671 # define SKIP_ALL 6 /* Everything but tRNS and sBIT */
673 png_uint_32 idat_max; /* 0 to perform no re-chunking */
675 int status_code; /* Accumulated status code */
676 # define TOO_FAR_BACK 0x01 /* found a too-far-back error */
677 # define CRC_ERROR 0x02 /* fixed an invalid CRC */
678 # define STREAM_ERROR 0x04 /* damaged PNG stream (may be fixable) */
679 # define TRUNCATED 0x08 /* truncated but still readable */
680 # define FILE_ERROR 0x10 /* could not read the file */
681 # define WRITE_ERROR 0x20 /* write error (this terminates the read) */
682 # define INTERNAL_ERROR 0x40 /* internal limits/errors encountered */
684 /* PUBLIC GLOBAL VARIABLES: USED INTERNALLY BY IDAT READ CODE */
685 struct IDAT_list idat_cache; /* Cache of file IDAT information buffers */
686 /* The structure is shared across all uses of this global control
687 * structure to avoid reallocation between IDAT streams.
691 static int
692 global_end(struct global *global)
695 int rc;
697 IDAT_list_end(&global->idat_cache);
698 rc = global->status_code;
699 CLEAR(*global);
700 return rc;
703 static void
704 global_init(struct global *global)
705 /* Call this once (and only once) to initialize the control */
707 CLEAR(*global);
709 /* Globals */
710 global->errors = 0;
711 global->warnings = 0;
712 global->quiet = 0;
713 global->verbose = 0;
714 global->idat_max = 0; /* no re-chunking of IDAT */
715 global->optimize_zlib = 0;
716 global->skip = SKIP_NONE;
717 global->status_code = 0;
719 IDAT_list_init(&global->idat_cache);
722 static int
723 skip_chunk_type(const struct global *global, png_uint_32 type)
724 /* Return true if this chunk is to be skipped according to the --strip
725 * option. This code needs to recognize all known ancillary chunks in order
726 * to handle the --strip=unsafe option.
729 /* Never strip critical chunks: */
730 if (CRITICAL(type))
731 return 0;
733 switch (type)
735 /* Chunks that are treated as, effectively, critical because they affect
736 * correct interpretation of the pixel values:
738 case png_tRNS: case png_sBIT:
739 return 0;
741 /* Chunks that specify gamma encoding which should therefore only be
742 * removed the the user insists:
744 case png_gAMA: case png_sRGB:
745 if (global->skip >= SKIP_ALL)
746 return 1;
747 return 0;
749 /* Chunks that affect color interpretation - not used by libpng and rarely
750 * used by applications, but technically still required for correct
751 * interpretation of the image data:
753 case png_cHRM: case png_iCCP:
754 if (global->skip >= SKIP_COLOR)
755 return 1;
756 return 0;
758 /* Other chunks that are used by libpng in image transformations (as
759 * opposed to known chunks that have get/set APIs but are not otherwise
760 * used.)
762 case png_bKGD:
763 if (global->skip >= SKIP_TRANSFORM)
764 return 1;
765 return 0;
767 /* All other chunks that libpng knows about and affect neither image
768 * interpretation nor libpng transforms - chunks that are effectively
769 * unused by libpng even though libpng might recognize and store them.
771 case png_fRAc: case png_gIFg: case png_gIFt: case png_gIFx: case png_hIST:
772 case png_iTXt: case png_oFFs: case png_pCAL: case png_pHYs: case png_sCAL:
773 case png_sPLT: case png_sTER: case png_tEXt: case png_tIME: case png_zTXt:
774 if (global->skip >= SKIP_UNUSED)
775 return 1;
776 return 0;
778 /* Chunks that libpng does not know about (notice that this depends on the
779 * list above including all known chunks!) The decision here depends on
780 * whether the safe-to-copy bit is set in the chunk type.
782 default:
783 if (SAFE_TO_COPY(type))
785 if (global->skip >= SKIP_UNUSED) /* as above */
786 return 1;
789 else if (global->skip >= SKIP_UNSAFE)
790 return 1;
792 return 0;
796 /* PER-FILE CONTROL STRUCTURE */
797 struct chunk;
798 struct IDAT;
799 struct file
801 /* ANCESTORS */
802 struct global *global;
804 /* PUBLIC PER-FILE VARIABLES: CALLER INITIALIZE */
805 const char * file_name;
806 const char * out_name; /* Name of output file (if required) */
808 /* PUBLIC PER-FILE VARIABLES: SET BY PNG READ CODE */
809 /* File specific result codes */
810 int status_code; /* Set to a bit mask of the following: */
811 int read_errno; /* Records a read error errno */
812 int write_errno; /* Records a write error errno */
814 /* IHDR information */
815 png_uint_32 width;
816 png_uint_32 height;
817 png_byte bit_depth;
818 png_byte color_type;
819 png_byte compression_method;
820 png_byte filter_method;
821 png_byte interlace_method;
823 udigit image_bytes[5];
824 int image_digits;
826 /* PROTECTED PER-FILE VARIABLES: USED BY THE READ CODE */
827 FILE * file; /* Original PNG file */
828 FILE * out; /* If a new one is being written */
829 jmp_buf jmpbuf; /* Set while reading a PNG */
831 /* PROTECTED CHUNK SPECIFIC VARIABLES: USED BY CHUNK CODE */
832 /* The following variables are used during reading to record the length, type
833 * and data position of the *next* chunk or, right at the start, the
834 * signature (in length,type).
836 * When a chunk control structure is instantiated these values are copied
837 * into the structure and can then be overritten with the data for the next
838 * chunk.
840 fpos_t data_pos; /* Position of first byte of chunk data */
841 png_uint_32 length; /* First word (length or signature start) */
842 png_uint_32 type; /* Second word (type or signature end) */
843 png_uint_32 crc; /* Running chunk CRC (used by read_chunk) */
845 /* These counts are maintained by the read and write routines below and are
846 * reset by the chunk handling code. They record the total number of bytes
847 * read or written for the chunk, including the header (length,type) bytes.
849 png_uint_32 read_count; /* Count of bytes read (in the chunk) */
850 png_uint_32 write_count; /* Count of bytes written (in the chunk) */
851 int state; /* As defined here: */
852 # define STATE_SIGNATURE 0 /* The signature is being written */
853 # define STATE_CHUNKS 1 /* Non-IDAT chunks are being written */
854 # define STATE_IDAT 2 /* An IDAT stream is being written */
856 /* Two pointers used to enable clean-up in the event of fatal errors and to
857 * hold state about the parser process (only one of each at present.)
859 struct chunk * chunk;
860 struct IDAT * idat;
862 /* Interface to allocate a new chunk or IDAT control structure. The result
863 * is returned by setting one or other of the above variables. Note that the
864 * relevant initializer is called by the allocator function. The alloc_ptr
865 * is used only by the implementation of the allocate function.
867 void * alloc_ptr;
868 void (*alloc)(struct file*,int idat);
869 /* idat: allocate IDAT not chunk */
872 /* Valid longjmp (stop) codes are: */
873 #define LIBPNG_WARNING_CODE 1 /* generic png_error */
874 #define LIBPNG_ERROR_CODE 2 /* generic png_error */
875 #define ZLIB_ERROR_CODE 3 /* generic zlib error */
876 #define INVALID_ERROR_CODE 4 /* detected an invalid PNG */
877 #define READ_ERROR_CODE 5 /* read failed */
878 #define WRITE_ERROR_CODE 6 /* error in write */
879 #define UNEXPECTED_ERROR_CODE 7 /* unexpected (internal?) error */
881 static void
882 emit_string(const char *str, FILE *out)
883 /* Print a string with spaces replaced by '_' and non-printing characters by
884 * an octal escape.
887 for (; *str; ++str)
888 if (isgraph(*str))
889 putc(*str, out);
891 else if (isspace(*str))
892 putc('_', out);
894 else
895 fprintf(out, "\\%.3o", *str);
898 static const char *
899 strcode(int code)
901 switch (code)
903 case LIBPNG_WARNING_CODE: return "warning";
904 case LIBPNG_ERROR_CODE: return "libpng";
905 case ZLIB_ERROR_CODE: return "zlib";
906 case INVALID_ERROR_CODE: return "invalid";
907 case READ_ERROR_CODE: return "read";
908 case WRITE_ERROR_CODE: return "write";
909 case UNEXPECTED_ERROR_CODE: return "unexpected";
910 default: return "INVALID";
914 static void
915 emit_error(struct file *file, int code, const char *what)
916 /* Generic error message routine, takes a 'stop' code but can be used
917 * elsewhere. Always outputs a message.
920 const char *reason;
921 int err = 0;
923 switch (code)
925 case LIBPNG_WARNING_CODE: reason = "libpng warning:"; break;
926 case LIBPNG_ERROR_CODE: reason = "libpng error:"; break;
927 case ZLIB_ERROR_CODE: reason = "zlib error:"; break;
928 case INVALID_ERROR_CODE: reason = "invalid"; break;
929 case READ_ERROR_CODE: reason = "read failure:";
930 err = file->read_errno;
931 break;
932 case WRITE_ERROR_CODE: reason = "write error";
933 err = file->write_errno;
934 break;
935 case UNEXPECTED_ERROR_CODE: reason = "unexpected error:";
936 err = file->read_errno;
937 if (err == 0)
938 err = file->write_errno;
939 break;
940 default: reason = "INVALID (internal error):"; break;
943 if (err != 0)
944 fprintf(stderr, "%s: %s %s [%s]\n", file->file_name, reason, what,
945 strerror(err));
947 else
948 fprintf(stderr, "%s: %s %s\n", file->file_name, reason, what);
951 static void chunk_end(struct chunk **);
952 static void IDAT_end(struct IDAT **);
954 static int
955 file_end(struct file *file)
957 int rc;
959 /* If either of the chunk pointers are set end them here, the IDAT structure
960 * must be deallocated first as it may deallocate the chunk structure.
962 if (file->idat != NULL)
963 IDAT_end(&file->idat);
965 if (file->chunk != NULL)
966 chunk_end(&file->chunk);
968 rc = file->status_code;
970 if (file->file != NULL)
971 (void)fclose(file->file);
973 if (file->out != NULL)
975 /* NOTE: this is bitwise |, all the following functions must execute and
976 * must succeed.
978 if (ferror(file->out) | fflush(file->out) | fclose(file->out))
980 perror(file->out_name);
981 emit_error(file, READ_ERROR_CODE, "output write error");
982 rc |= WRITE_ERROR;
986 /* Accumulate the result codes */
987 file->global->status_code |= rc;
989 CLEAR(*file);
991 return rc; /* status code: non-zero on read or write error */
994 static int
995 file_init(struct file *file, struct global *global, const char *file_name,
996 const char *out_name, void *alloc_ptr, void (*alloc)(struct file*,int))
997 /* Initialize a file control structure. This will open the given files as
998 * well. The status code returned is 0 on success, non zero (using the flags
999 * above) on a file open error.
1002 CLEAR(*file);
1003 file->global = global;
1005 file->file_name = file_name;
1006 file->out_name = out_name;
1007 file->status_code = 0;
1008 file->read_errno = 0;
1009 file->write_errno = 0;
1011 file->file = NULL;
1012 file->out = NULL;
1013 /* jmpbuf is garbage: must be set by read_png */
1015 file->read_count = 0;
1016 file->state = STATE_SIGNATURE;
1018 file->chunk = NULL;
1019 file->idat = NULL;
1021 file->alloc_ptr = alloc_ptr;
1022 file->alloc = alloc;
1024 /* Open the files: */
1025 assert(file_name != NULL);
1026 file->file = fopen(file_name, "rb");
1028 if (file->file == NULL)
1030 file->read_errno = errno;
1031 file->status_code |= FILE_ERROR;
1032 /* Always output: please give a readable file! */
1033 perror(file_name);
1034 return FILE_ERROR;
1037 if (out_name != NULL)
1039 file->out = fopen(out_name, "wb");
1041 if (file->out == NULL)
1043 file->write_errno = errno;
1044 file->status_code |= WRITE_ERROR;
1045 perror(out_name);
1046 return WRITE_ERROR;
1050 return 0;
1053 static void
1054 log_error(struct file *file, int code, const char *what)
1055 /* Like emit_error but checks the global 'errors' flag */
1057 if (file->global->errors)
1058 emit_error(file, code, what);
1061 static char
1062 type_char(png_uint_32 v)
1064 /* In fact because chunk::chunk_type is validated prior to any call to this
1065 * function it will always return a-zA-Z, but the extra codes are just there
1066 * to help in finding internal (programming) errors. Note that the code only
1067 * ever considers the low 7 bits of the value (so it is not necessary for the
1068 * type_name function to mask of the byte.)
1070 if (v & 32)
1071 return "!abcdefghijklmnopqrstuvwxyz56789"[(v-96)&31];
1073 else
1074 return "@ABCDEFGHIJKLMNOPQRSTUVWXYZ01234"[(v-64)&31];
1077 static void
1078 type_name(png_uint_32 type, FILE *out)
1080 putc(type_char(type >> 24), out);
1081 putc(type_char(type >> 16), out);
1082 putc(type_char(type >> 8), out);
1083 putc(type_char(type ), out);
1086 static void
1087 type_sep(FILE *out)
1089 putc(':', out);
1090 putc(' ', out);
1093 static png_uint_32 current_type(struct file *file, int code);
1095 PNG_NORETURN static void
1096 stop(struct file *file, int code, const char *what)
1097 /* Return control when a PNG file cannot be read. This outputs an 'ERR'
1098 * summary line too.
1101 log_error(file, code, what);
1103 /* The chunk being read is typically identified by file->chunk or, if this is
1104 * NULL, by file->type. This may be wrong if libpng reads ahead, but this
1105 * only happens with IDAT where libpng reads the header then jumps around
1106 * finding errors in the previous chunks. We know that is happening because
1107 * we are at the start of the IDAT (i.e. no IDAT data has yet been written.)
1109 * SUMMARY FORMAT (stop):
1111 * IDAT ERR status code read-errno write-errno message file
1113 * 'uncompressed' will be 0 if there was a problem in the IHDR. The errno
1114 * values are emit_string(strerror(errno)).
1116 if (file->global->quiet < 2) /* need two quiets to stop this. */
1118 png_uint_32 type;
1120 if (file->chunk != NULL)
1121 type = current_type(file, code); /* Gropes in struct chunk and IDAT */
1123 else
1124 type = file->type;
1126 if (type)
1127 type_name(type, stdout);
1129 else /* magic: an IDAT header, produces bogons for too many IDATs */
1130 fputs("HEAD", stdout); /* not a registered chunk! */
1132 printf(" ERR %.2x %s ", file->status_code, strcode(code));
1133 /* This only works one strerror at a time, because of the way strerror is
1134 * implemented.
1136 emit_string(strerror(file->read_errno), stdout);
1137 putc(' ', stdout);
1138 emit_string(strerror(file->write_errno), stdout);
1139 putc(' ', stdout);
1140 emit_string(what, stdout);
1141 putc(' ', stdout);
1142 fputs(file->file_name, stdout);
1143 putc('\n', stdout);
1146 file->status_code |= FILE_ERROR;
1147 longjmp(file->jmpbuf, code);
1150 PNG_NORETURN static void
1151 stop_invalid(struct file *file, const char *what)
1153 stop(file, INVALID_ERROR_CODE, what);
1156 static void
1157 type_message(struct file *file, png_uint_32 type, const char *what)
1158 /* Error message for a chunk; the chunk name comes from 'type' */
1160 if (file->global->errors)
1162 fputs(file->file_name, stderr);
1163 type_sep(stderr);
1164 type_name(type, stderr);
1165 type_sep(stderr);
1166 fputs(what, stderr);
1167 putc('\n', stderr);
1171 /* Input file positioning - we jump around in the input file while reading
1172 * stuff, these wrappers deal with the error handling.
1174 static void
1175 file_getpos(struct file *file, fpos_t *pos)
1177 if (fgetpos(file->file, pos))
1179 /* This is unexpected, so perror it */
1180 perror(file->file_name);
1181 stop(file, READ_ERROR_CODE, "fgetpos");
1185 static void
1186 file_setpos(struct file *file, const fpos_t *pos)
1188 if (fsetpos(file->file, pos))
1190 perror(file->file_name);
1191 stop(file, READ_ERROR_CODE, "fsetpos");
1195 static void
1196 getpos(struct file *file)
1197 /* Get the current position and store it in 'data_pos'. The corresponding
1198 * setpos() function is chunk specific because it uses the copy of the
1199 * position for the specific chunk.
1202 file_getpos(file, &file->data_pos);
1206 /* Read utility - read a single byte, returns a value in the range 0..255 or EOF
1207 * on a read error. In the latter case status_code and read_errno are updated
1208 * appropriately.
1210 static int
1211 read_byte(struct file *file)
1213 int ch = getc(file->file);
1215 if (ch >= 0 && ch <= 255)
1217 ++(file->read_count);
1218 return ch;
1221 else if (ch != EOF)
1223 file->status_code |= INTERNAL_ERROR;
1224 file->read_errno = ERANGE; /* out of range character */
1226 /* This is very unexpected; an error message is always output: */
1227 emit_error(file, UNEXPECTED_ERROR_CODE, "file read");
1230 # ifdef EINTR
1231 else if (errno == EINTR) /* Interrupted, try again */
1233 errno = 0;
1234 return read_byte(file);
1236 # endif
1238 else
1240 /* An error, it doesn't really matter what the error is but it gets
1241 * recorded anyway.
1243 if (ferror(file->file))
1244 file->read_errno = errno;
1246 else if (feof(file->file))
1247 file->read_errno = 0; /* I.e. a regular EOF, no error */
1249 else /* unexpected */
1250 file->read_errno = EDOM;
1253 /* 'TRUNCATED' is used for all cases of failure to read a byte, because of
1254 * the way libpng works a byte read is never attempted unless the byte is
1255 * expected to be there, so EOF should not occur.
1257 file->status_code |= TRUNCATED;
1258 return EOF;
1261 static png_byte
1262 reread_byte(struct file *file)
1263 /* Read a byte when an error is not expected to happen because the byte has
1264 * been read before without error.
1267 int ch = getc(file->file);
1269 if (errno != 0)
1270 file->read_errno = errno;
1272 if (ch < 0 || ch > 255)
1273 stop(file, UNEXPECTED_ERROR_CODE, "reread");
1275 return (png_byte)ch;
1278 static png_uint_32
1279 reread_4(struct file *file)
1280 /* The same but for a four byte quantity */
1282 png_uint_32 result = 0;
1283 int i = 0;
1285 while (++i <= 4)
1286 result = (result << 8) + reread_byte(file);
1288 return result;
1291 static void
1292 skip_12(struct file *file)
1293 /* Skip exactly 12 bytes in the input stream - used to skip a CRC and chunk
1294 * header that has been read before.
1297 /* Since the chunks were read before this shouldn't fail: */
1298 if (fseek(file->file, 12, SEEK_CUR) != 0)
1300 if (errno != 0)
1301 file->read_errno = errno;
1303 stop(file, UNEXPECTED_ERROR_CODE, "reskip");
1307 static void
1308 write_byte(struct file *file, int b)
1309 /* Write one byte to the output - this causes a fatal error if the write
1310 * fails and the read of this PNG file immediately terminates. Just
1311 * increments the write count if there is no output file.
1314 if (file->out != NULL)
1316 if (putc(b, file->out) != b)
1318 file->write_errno = errno;
1319 file->status_code |= WRITE_ERROR;
1320 stop(file, WRITE_ERROR_CODE, "write byte");
1324 ++(file->write_count);
1327 /* Derivatives of the read/write functions. */
1328 static unsigned int
1329 read_4(struct file *file, png_uint_32 *pu)
1330 /* Read four bytes, returns the number of bytes read successfully and, if all
1331 * four bytes are read, assigns the result to *pu.
1334 unsigned int i = 0;
1335 png_uint_32 val = 0;
1339 int ch = read_byte(file);
1341 if (ch == EOF)
1342 return i;
1344 val = (val << 8) + ch;
1345 } while (++i < 4);
1347 *pu = val;
1348 return i;
1351 /* CRC handling - read but calculate the CRC while doing so. */
1352 static int
1353 crc_read_many(struct file *file, png_uint_32 length)
1354 /* Reads 'length' bytes and updates the CRC, returns true on success, false
1355 * if the input is truncated.
1358 if (length > 0)
1360 png_uint_32 crc = file->crc;
1364 int ch = read_byte(file);
1366 if (ch == EOF)
1367 return 0; /* Truncated */
1369 crc = crc_one_byte(crc, ch);
1371 while (--length > 0);
1373 file->crc = crc;
1376 return 1; /* OK */
1379 static int
1380 calc_image_size(struct file *file)
1381 /* Fill in the image_bytes field given the IHDR information, calls stop on
1382 * error.
1385 png_uint_16 pd = file->bit_depth;
1387 switch (file->color_type)
1389 default:
1390 stop_invalid(file, "IHDR: colour type");
1392 invalid_bit_depth:
1393 stop_invalid(file, "IHDR: bit depth");
1395 case 0: /* g */
1396 if (pd != 1 && pd != 2 && pd != 4 && pd != 8 && pd != 16)
1397 goto invalid_bit_depth;
1398 break;
1400 case 3:
1401 if (pd != 1 && pd != 2 && pd != 4 && pd != 8)
1402 goto invalid_bit_depth;
1403 break;
1405 case 2: /* rgb */
1406 if (pd != 8 && pd != 16)
1407 goto invalid_bit_depth;
1409 pd = (png_uint_16)(pd * 3);
1410 break;
1412 case 4: /* ga */
1413 if (pd != 8 && pd != 16)
1414 goto invalid_bit_depth;
1416 pd = (png_uint_16)(pd * 2);
1417 break;
1419 case 6: /* rgba */
1420 if (pd != 8 && pd != 16)
1421 goto invalid_bit_depth;
1423 pd = (png_uint_16)(pd * 4);
1424 break;
1427 if (file->width < 1 || file->width > 0x7fffffff)
1428 stop_invalid(file, "IHDR: width");
1430 else if (file->height < 1 || file->height > 0x7fffffff)
1431 stop_invalid(file, "IHDR: height");
1433 else if (file->compression_method != 0)
1434 stop_invalid(file, "IHDR: compression method");
1436 else if (file->filter_method != 0)
1437 stop_invalid(file, "IHDR: filter method");
1439 else switch (file->interlace_method)
1441 case PNG_INTERLACE_ADAM7:
1442 /* Interlacing makes the image larger because of the replication of
1443 * both the filter byte and the padding to a byte boundary.
1446 int pass;
1447 int image_digits = 0;
1448 udigit row_width[2], row_bytes[3];
1450 for (pass=0; pass<=6; ++pass)
1452 png_uint_32 pw = PNG_PASS_COLS(file->width, pass);
1454 if (pw > 0)
1456 int digits;
1458 /* calculate 1+((pw*pd+7)>>3) in row_bytes */
1459 digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1460 row_width, uarb_set(row_width, pw), pd);
1461 digits = uarb_shift(row_bytes, digits, 3);
1462 digits = uarb_inc(row_bytes, digits, 1);
1464 /* Add row_bytes * pass-height to the file image_bytes field
1466 image_digits = uarb_mult32(file->image_bytes, image_digits,
1467 row_bytes, digits,
1468 PNG_PASS_ROWS(file->height, pass));
1472 file->image_digits = image_digits;
1474 break;
1476 case PNG_INTERLACE_NONE:
1478 int digits;
1479 udigit row_width[2], row_bytes[3];
1481 /* As above, but use image_width in place of the pass width: */
1482 digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1483 row_width, uarb_set(row_width, file->width), pd);
1484 digits = uarb_shift(row_bytes, digits, 3);
1485 digits = uarb_inc(row_bytes, digits, 1);
1487 /* Set row_bytes * image-height to the file image_bytes field */
1488 file->image_digits = uarb_mult32(file->image_bytes, 0,
1489 row_bytes, digits, file->height);
1491 break;
1493 default:
1494 stop_invalid(file, "IHDR: interlace method");
1497 assert(file->image_digits >= 1 && file->image_digits <= 5);
1498 return 1;
1501 /* PER-CHUNK CONTROL STRUCTURE
1502 * This structure is instantiated for each chunk, except for the IDAT chunks
1503 * where one chunk control structure is used for the whole of a single stream of
1504 * IDAT chunks (see the IDAT control structure below).
1506 struct chunk
1508 /* ANCESTORS */
1509 struct file * file;
1510 struct global * global;
1512 /* PUBLIC IDAT INFORMATION: SET BY THE ZLIB CODE */
1513 udigit uncompressed_bytes[5];
1514 int uncompressed_digits;
1515 udigit compressed_bytes[5];
1516 int compressed_digits;
1518 /* PUBLIC PER-CHUNK INFORMATION: USED BY CHUNK READ CODE */
1519 /* This information is filled in by chunk_init from the data in the file
1520 * control structure, but chunk_length may be changed later.
1522 fpos_t chunk_data_pos; /* Position of first byte of chunk data */
1523 png_uint_32 chunk_length; /* From header (or modified below) */
1524 png_uint_32 chunk_type; /* From header */
1526 /* PUBLIC PER-CHUNK INFORMATION: FOR THE CHUNK WRITE CODE */
1527 png_uint_32 write_crc; /* Output CRC (may differ from read_crc) */
1528 png_uint_32 rewrite_offset; /* Count of bytes before rewrite. */
1529 int rewrite_length; /* Number of bytes left to change */
1530 png_byte rewrite_buffer[2]; /* Buffer of new byte values */
1533 static void
1534 chunk_message(struct chunk *chunk, const char *message)
1536 type_message(chunk->file, chunk->chunk_type, message);
1539 static void
1540 chunk_end(struct chunk **chunk_var)
1542 struct chunk *chunk = *chunk_var;
1544 *chunk_var = NULL;
1545 CLEAR(*chunk);
1548 static void
1549 chunk_init(struct chunk *chunk, struct file *file)
1550 /* When a chunk is initialized the file length/type/pos are copied into the
1551 * corresponding chunk fields and the new chunk is registered in the file
1552 * structure. There can only be one chunk at a time.
1554 * NOTE: this routine must onely be called from the file alloc routine!
1557 assert(file->chunk == NULL);
1559 CLEAR(*chunk);
1561 chunk->file = file;
1562 chunk->global = file->global;
1564 chunk->chunk_data_pos = file->data_pos;
1565 chunk->chunk_length = file->length;
1566 chunk->chunk_type = file->type;
1568 /* Compresssed/uncompressed size information (from the zlib control structure
1569 * that is used to check the compressed data in a chunk.)
1571 chunk->uncompressed_digits = 0;
1572 chunk->compressed_digits = 0;
1574 file->chunk = chunk;
1577 static png_uint_32
1578 current_type(struct file *file, int code)
1579 /* Guess the actual chunk type that causes a stop() */
1581 /* This may return png_IDAT for errors detected (late) in the header; that
1582 * includes any inter-chunk consistency check that libpng performs. Assume
1583 * that if the chunk_type is png_IDAT and the file write count is 8 this is
1584 * what is happening.
1586 if (file->chunk != NULL)
1588 png_uint_32 type = file->chunk->chunk_type;
1590 /* This is probably wrong for the excess IDATs case, because then libpng
1591 * whines about too many of them (apparently in some cases erroneously)
1592 * when the header is read.
1594 if (code <= LIBPNG_ERROR_CODE && type == png_IDAT &&
1595 file->write_count == 8)
1596 type = 0; /* magic */
1598 return type;
1601 else
1602 return file->type;
1605 static void
1606 setpos(struct chunk *chunk)
1607 /* Reset the position to 'chunk_data_pos' - the start of the data for this
1608 * chunk. As a side effect the read_count in the file is reset to 8, just
1609 * after the length/type header.
1612 chunk->file->read_count = 8;
1613 file_setpos(chunk->file, &chunk->chunk_data_pos);
1616 /* Specific chunk handling - called for each chunk header, all special chunk
1617 * processing is initiated in these functions.
1619 /* The next functions handle special processing for those chunks with LZ data,
1620 * the data is identified and checked for validity. If there are problems which
1621 * cannot be corrected the routines return false, otherwise true (although
1622 * modification to the zlib header may be required.)
1624 * The compressed data is in zlib format (RFC1950) and consequently has a
1625 * minimum length of 7 bytes.
1627 static int zlib_check(struct file *file, png_uint_32 offset);
1629 static int
1630 process_zTXt_iCCP(struct file *file)
1631 /* zTXt and iCCP have exactly the same form - keyword, null, compression
1632 * method then compressed data.
1635 struct chunk *chunk = file->chunk;
1636 png_uint_32 length;
1637 png_uint_32 index = 0;
1639 assert(chunk != NULL && file->idat == NULL);
1640 length = chunk->chunk_length;
1641 setpos(chunk);
1643 while (length >= 9)
1645 --length;
1646 ++index;
1647 if (reread_byte(file) == 0) /* keyword null terminator */
1649 --length;
1650 ++index;
1651 (void)reread_byte(file); /* compression method */
1652 return zlib_check(file, index);
1656 chunk_message(chunk, "too short");
1657 return 0; /* skip */
1660 static int
1661 process_iTXt(struct file *file)
1663 /* Like zTXt but more fields. */
1664 struct chunk *chunk = file->chunk;
1665 png_uint_32 length;
1666 png_uint_32 index = 0;
1668 assert(chunk != NULL && file->idat == NULL);
1669 length = chunk->chunk_length;
1670 setpos(chunk);
1672 while (length >= 5)
1674 --length;
1675 ++index;
1676 if (reread_byte(file) == 0) /* keyword null terminator */
1678 --length;
1679 ++index;
1680 if (reread_byte(file) == 0) /* uncompressed text */
1681 return 1; /* nothing to check */
1683 --length;
1684 ++index;
1685 (void)reread_byte(file); /* compression method */
1687 /* Skip the language tag (null terminated). */
1688 while (length >= 9)
1690 --length;
1691 ++index;
1692 if (reread_byte(file) == 0) /* terminator */
1694 /* Skip the translated keyword */
1695 while (length >= 8)
1697 --length;
1698 ++index;
1699 if (reread_byte(file) == 0) /* terminator */
1700 return zlib_check(file, index);
1705 /* Ran out of bytes in the compressed case. */
1706 break;
1710 log_error(file, INVALID_ERROR_CODE, "iTXt chunk length");
1712 return 0; /* skip */
1715 /* IDAT READ/WRITE CONTROL STRUCTURE */
1716 struct IDAT
1718 /* ANCESTORS */
1719 struct file * file;
1720 struct global * global;
1722 /* PROTECTED IDAT INFORMATION: SET BY THE IDAT READ CODE */
1723 struct IDAT_list *idat_list_head; /* START of the list of IDAT information */
1724 struct IDAT_list *idat_list_tail; /* *END* of the list of IDAT information */
1726 /* PROTECTED IDAT INFORMATION: USED BY THE IDAT WRITE CODE */
1727 struct IDAT_list *idat_cur; /* Current list entry */
1728 unsigned int idat_count; /* And the *current* index into the list */
1729 png_uint_32 idat_index; /* Index of *next* input byte to write */
1730 png_uint_32 idat_length; /* Cache of current chunk length */
1733 /* NOTE: there is currently no IDAT_reset, so a stream cannot contain more than
1734 * one IDAT sequence (i.e. MNG is not supported).
1737 static void
1738 IDAT_end(struct IDAT **idat_var)
1740 struct IDAT *idat = *idat_var;
1741 struct file *file = idat->file;
1743 *idat_var = NULL;
1745 CLEAR(*idat);
1747 assert(file->chunk != NULL);
1748 chunk_end(&file->chunk);
1750 /* Regardless of why the IDAT was killed set the state back to CHUNKS (it may
1751 * already be CHUNKS because the state isn't changed until process_IDAT
1752 * returns; a stop will cause IDAT_end to be entered in state CHUNKS!)
1754 file->state = STATE_CHUNKS;
1757 static void
1758 IDAT_init(struct IDAT *idat, struct file *file)
1759 /* When the chunk is png_IDAT instantiate an IDAT control structure in place
1760 * of a chunk control structure. The IDAT will instantiate a chunk control
1761 * structure using the file alloc routine.
1763 * NOTE: this routine must only be called from the file alloc routine!
1766 assert(file->chunk == NULL);
1767 assert(file->idat == NULL);
1769 CLEAR(*idat);
1771 idat->file = file;
1772 idat->global = file->global;
1774 /* Initialize the tail to the pre-allocated buffer and set the count to 0
1775 * (empty.)
1777 idat->global->idat_cache.count = 0;
1778 idat->idat_list_head = idat->idat_list_tail = &idat->global->idat_cache;
1780 /* Now the chunk. The allocator calls the initializer of the new chunk and
1781 * stores the result in file->chunk:
1783 file->alloc(file, 0/*chunk*/);
1784 assert(file->chunk != NULL);
1786 /* And store this for cleanup (and to check for double alloc or failure to
1787 * free.)
1789 file->idat = idat;
1792 static png_uint_32
1793 rechunk_length(struct IDAT *idat)
1794 /* Return the length for the next IDAT chunk, taking into account
1795 * rechunking.
1798 png_uint_32 len = idat->global->idat_max;
1800 if (len == 0) /* use original chunk lengths */
1802 const struct IDAT_list *cur;
1803 unsigned int count;
1805 if (idat->idat_index == 0) /* at the new chunk (first time) */
1806 return idat->idat_length; /* use the cache */
1808 /* Otherwise rechunk_length is called at the end of a chunk for the length
1809 * of the next one.
1811 cur = idat->idat_cur;
1812 count = idat->idat_count;
1814 assert(idat->idat_index == idat->idat_length &&
1815 idat->idat_length == cur->lengths[count]);
1817 /* Return length of the *next* chunk */
1818 if (++count < cur->count)
1819 return cur->lengths[count];
1821 /* End of this list */
1822 assert(cur != idat->idat_list_tail);
1823 cur = cur->next;
1824 assert(cur != NULL && cur->count > 0);
1825 return cur->lengths[0];
1828 else /* rechunking */
1830 /* The chunk size is the lesser of file->idat_max and the number
1831 * of remaining bytes.
1833 png_uint_32 have = idat->idat_length - idat->idat_index;
1835 if (len > have)
1837 struct IDAT_list *cur = idat->idat_cur;
1838 unsigned int j = idat->idat_count+1; /* the next IDAT in the list */
1842 /* Add up the remaining bytes. This can't overflow because the
1843 * individual lengths are always <= 0x7fffffff, so when we add two
1844 * of them overflow is not possible.
1846 assert(cur != NULL);
1848 for (;;)
1850 /* NOTE: IDAT_list::count here, not IDAT_list::length */
1851 for (; j < cur->count; ++j)
1853 have += cur->lengths[j];
1854 if (len <= have)
1855 return len;
1858 /* If this was the end return the count of the available bytes */
1859 if (cur == idat->idat_list_tail)
1860 return have;
1862 cur = cur->next;
1863 j = 0;
1866 while (len > have);
1869 return len;
1873 static int
1874 process_IDAT(struct file *file)
1875 /* Process the IDAT stream, this is the more complex than the preceding
1876 * cases because the compressed data is spread across multiple IDAT chunks
1877 * (typically). Rechunking of the data is not handled here; all this
1878 * function does is establish whether the zlib header needs to be modified.
1880 * Initially the function returns false, indicating that the chunk should not
1881 * be written. It does this until the last IDAT chunk is passed in, then it
1882 * checks the zlib data and returns true.
1884 * It does not return false on a fatal error; it calls stop instead.
1886 * The caller must have an instantiated (IDAT) control structure and it must
1887 * have extent over the whole read of the IDAT stream. For a PNG this means
1888 * the whole PNG read, for MNG it could have lesser extent.
1891 struct IDAT_list *list;
1893 assert(file->idat != NULL && file->chunk != NULL);
1895 /* We need to first check the entire sequence of IDAT chunks to ensure the
1896 * stream is in sync. Do this by building a list of all the chunks and
1897 * recording the length of each because the length may have been fixed up by
1898 * sync_stream below.
1900 * At the end of the list of chunks, where the type of the next chunk is not
1901 * png_IDAT, process the whole stream using the list data to check validity
1902 * then return control to the start and rewrite everything.
1904 list = file->idat->idat_list_tail;
1906 if (list->count == list->length)
1908 list = IDAT_list_extend(list);
1910 if (list == NULL)
1911 stop(file, READ_ERROR_CODE, "out of memory");
1913 /* Move to the next block */
1914 list->count = 0;
1915 file->idat->idat_list_tail = list;
1918 /* And fill in the next IDAT information buffer. */
1919 list->lengths[(list->count)++] = file->chunk->chunk_length;
1921 /* The type of the next chunk was recorded in the file control structure by
1922 * the caller, if this is png_IDAT return 'skip' to the caller.
1924 if (file->type == png_IDAT)
1925 return 0; /* skip this for the moment */
1927 /* This is the final IDAT chunk, so run the tests to check for the too far
1928 * back error and possibly optimize the window bits. This means going back
1929 * to the start of the first chunk data, which is stored in the original
1930 * chunk allocation.
1932 setpos(file->chunk);
1934 if (zlib_check(file, 0))
1936 struct IDAT *idat;
1937 int cmp;
1939 /* The IDAT stream was successfully uncompressed; see whether it
1940 * contained the correct number of bytes of image data.
1942 cmp = uarb_cmp(file->image_bytes, file->image_digits,
1943 file->chunk->uncompressed_bytes, file->chunk->uncompressed_digits);
1945 if (cmp < 0)
1946 type_message(file, png_IDAT, "extra uncompressed data");
1948 else if (cmp > 0)
1949 stop(file, LIBPNG_ERROR_CODE, "IDAT: uncompressed data too small");
1951 /* Return the stream to the start of the first IDAT chunk; the length
1952 * is set in the write case below but the input chunk variables must be
1953 * set (once) here:
1955 setpos(file->chunk);
1957 idat = file->idat;
1958 idat->idat_cur = idat->idat_list_head;
1959 idat->idat_length = idat->idat_cur->lengths[0];
1960 idat->idat_count = 0; /* Count of chunks read in current list */
1961 idat->idat_index = 0; /* Index into chunk data */
1963 /* Update the chunk length to the correct value for the IDAT chunk: */
1964 file->chunk->chunk_length = rechunk_length(idat);
1966 /* Change the state to writing IDAT chunks */
1967 file->state = STATE_IDAT;
1969 return 1;
1972 else /* Failure to decompress the IDAT stream; give up. */
1973 stop(file, ZLIB_ERROR_CODE, "could not uncompress IDAT");
1976 /* ZLIB CONTROL STRUCTURE */
1977 struct zlib
1979 /* ANCESTORS */
1980 struct IDAT * idat; /* NOTE: May be NULL */
1981 struct chunk * chunk;
1982 struct file * file;
1983 struct global *global;
1985 /* GLOBAL ZLIB INFORMATION: SET BY THE CALLER */
1986 png_uint_32 rewrite_offset;
1988 /* GLOBAL ZLIB INFORMATION: SET BY THE ZLIB READ CODE */
1989 udigit compressed_bytes[5];
1990 int compressed_digits;
1991 udigit uncompressed_bytes[5];
1992 int uncompressed_digits;
1993 int file_bits; /* window bits from the file */
1994 int ok_bits; /* Set <16 on a successful read */
1995 int cksum; /* Set on a checksum error */
1997 /* PROTECTED ZLIB INFORMATION: USED BY THE ZLIB ROUTINES */
1998 z_stream z;
1999 png_uint_32 extra_bytes; /* Count of extra compressed bytes */
2000 int state;
2001 int rc; /* Last return code */
2002 int window_bits; /* 0 if no change */
2003 png_byte header[2];
2006 static const char *
2007 zlib_flevel(struct zlib *zlib)
2009 switch (zlib->header[1] >> 6)
2011 case 0: return "supfast";
2012 case 1: return "stdfast";
2013 case 2: return "default";
2014 case 3: return "maximum";
2015 default: assert(UNREACHED);
2018 return "COMPILER BUG";
2021 static const char *
2022 zlib_rc(struct zlib *zlib)
2023 /* Return a string for the zlib return code */
2025 switch (zlib->rc)
2027 case Z_OK: return "Z_OK";
2028 case Z_STREAM_END: return "Z_STREAM_END";
2029 case Z_NEED_DICT: return "Z_NEED_DICT";
2030 case Z_ERRNO: return "Z_ERRNO";
2031 case Z_STREAM_ERROR: return "Z_STREAM_ERROR";
2032 case Z_DATA_ERROR: return "Z_DATA_ERROR";
2033 case Z_MEM_ERROR: return "Z_MEM_ERROR";
2034 case Z_BUF_ERROR: return "Z_BUF_ERROR";
2035 case Z_VERSION_ERROR: return "Z_VERSION_ERROR";
2036 default: return "Z_*INVALID_RC*";
2040 static void
2041 zlib_message(struct zlib *zlib, int unexpected)
2042 /* Output a message given a zlib rc */
2044 if (zlib->global->errors)
2046 const char *reason = zlib->z.msg;
2048 if (reason == NULL)
2049 reason = "[no message]";
2051 fputs(zlib->file->file_name, stderr);
2052 type_sep(stderr);
2053 type_name(zlib->chunk->chunk_type, stderr);
2054 fprintf(stderr, ": %szlib error: %d (%s) (%s)\n",
2055 unexpected ? "unexpected " : "", zlib->rc, zlib_rc(zlib), reason);
2059 static void
2060 zlib_end(struct zlib *zlib)
2062 /* Output the summary line now; this ensures a summary line always gets
2063 * output regardless of the manner of exit.
2065 if (!zlib->global->quiet)
2067 if (zlib->ok_bits < 16) /* stream was read ok */
2069 const char *reason;
2071 if (zlib->cksum)
2072 reason = "CHK"; /* checksum error */
2074 else if (zlib->ok_bits > zlib->file_bits)
2075 reason = "TFB"; /* fixing a too-far-back error */
2077 else if (zlib->ok_bits == zlib->file_bits)
2078 reason = "OK ";
2080 else
2081 reason = "OPT"; /* optimizing window bits */
2083 /* SUMMARY FORMAT (for a successful zlib inflate):
2085 * IDAT reason flevel file-bits ok-bits compressed uncompressed file
2087 type_name(zlib->chunk->chunk_type, stdout);
2088 printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits,
2089 zlib->ok_bits);
2090 uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2091 putc(' ', stdout);
2092 uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits,
2093 stdout);
2094 putc(' ', stdout);
2095 fputs(zlib->file->file_name, stdout);
2096 putc('\n', stdout);
2099 else
2101 /* This is a zlib read error; the chunk will be skipped. For an IDAT
2102 * stream this will also cause a fatal read error (via stop()).
2104 * SUMMARY FORMAT:
2106 * IDAT SKP flevel file-bits z-rc compressed message file
2108 * z-rc is the zlib failure code; message is the error message with
2109 * spaces replaced by '-'. The compressed byte count indicates where
2110 * in the zlib stream the error occured.
2112 type_name(zlib->chunk->chunk_type, stdout);
2113 printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits,
2114 zlib_rc(zlib));
2115 uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2116 putc(' ', stdout);
2117 emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout);
2118 putc(' ', stdout);
2119 fputs(zlib->file->file_name, stdout);
2120 putc('\n', stdout);
2124 if (zlib->state >= 0)
2126 zlib->rc = inflateEnd(&zlib->z);
2128 if (zlib->rc != Z_OK)
2129 zlib_message(zlib, 1/*unexpected*/);
2132 CLEAR(*zlib);
2135 static int
2136 zlib_reset(struct zlib *zlib, int window_bits)
2137 /* Reinitializes a zlib with a different window_bits */
2139 assert(zlib->state >= 0); /* initialized by zlib_init */
2141 zlib->z.next_in = Z_NULL;
2142 zlib->z.avail_in = 0;
2143 zlib->z.next_out = Z_NULL;
2144 zlib->z.avail_out = 0;
2146 zlib->window_bits = window_bits;
2147 zlib->compressed_digits = 0;
2148 zlib->uncompressed_digits = 0;
2150 zlib->state = 0; /* initialized, once */
2151 zlib->rc = inflateReset2(&zlib->z, 0);
2152 if (zlib->rc != Z_OK)
2154 zlib_message(zlib, 1/*unexpected*/);
2155 return 0;
2158 return 1;
2161 static int
2162 zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
2163 int window_bits, png_uint_32 offset)
2164 /* Initialize a zlib_control; the result is true/false */
2166 CLEAR(*zlib);
2168 zlib->idat = idat;
2169 zlib->chunk = chunk;
2170 zlib->file = chunk->file;
2171 zlib->global = chunk->global;
2172 zlib->rewrite_offset = offset; /* never changed for this zlib */
2174 /* *_out does not need to be set: */
2175 zlib->z.next_in = Z_NULL;
2176 zlib->z.avail_in = 0;
2177 zlib->z.zalloc = Z_NULL;
2178 zlib->z.zfree = Z_NULL;
2179 zlib->z.opaque = Z_NULL;
2181 zlib->state = -1;
2182 zlib->window_bits = window_bits;
2184 zlib->compressed_digits = 0;
2185 zlib->uncompressed_digits = 0;
2187 /* These values are sticky across reset (in addition to the stuff in the
2188 * first block, which is actually constant.)
2190 zlib->file_bits = 16;
2191 zlib->ok_bits = 16; /* unset */
2192 zlib->cksum = 0; /* set when a checksum error is detected */
2194 /* '0' means use the header; inflateInit2 should always succeed because it
2195 * does nothing apart from allocating the internal zstate.
2197 zlib->rc = inflateInit2(&zlib->z, 0);
2198 if (zlib->rc != Z_OK)
2200 zlib_message(zlib, 1/*unexpected*/);
2201 return 0;
2204 else
2206 zlib->state = 0; /* initialized */
2207 return 1;
2211 static int
2212 max_window_bits(uarbc size, int ndigits)
2213 /* Return the zlib stream window bits required for data of the given size. */
2215 png_uint_16 cb;
2217 if (ndigits > 1)
2218 return 15;
2220 cb = size[0];
2222 if (cb > 16384) return 15;
2223 if (cb > 8192) return 14;
2224 if (cb > 4096) return 13;
2225 if (cb > 2048) return 12;
2226 if (cb > 1024) return 11;
2227 if (cb > 512) return 10;
2228 if (cb > 256) return 9;
2229 return 8;
2232 static int
2233 zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
2234 /* Read nbytes compressed bytes; the stream will be initialized if required.
2235 * Bytes are always being reread and errors are fatal. The return code is as
2236 * follows:
2238 * -1: saw the "too far back" error
2239 * 0: ok, keep going
2240 * 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
2241 * 2: a zlib error that cannot be corrected (error message already
2242 * output if required.)
2244 # define ZLIB_TOO_FAR_BACK (-1)
2245 # define ZLIB_OK 0
2246 # define ZLIB_STREAM_END 1
2247 # define ZLIB_FATAL 2
2249 int state = zlib->state;
2250 int endrc = ZLIB_OK;
2251 png_uint_32 in_bytes = 0;
2252 struct file *file = zlib->file;
2254 assert(state >= 0);
2256 while (in_bytes < nbytes && endrc == ZLIB_OK)
2258 png_uint_32 out_bytes;
2259 int flush;
2260 png_byte bIn = reread_byte(file);
2261 png_byte bOut;
2263 switch (state)
2265 case 0: /* first header byte */
2267 int file_bits = 8+(bIn >> 4);
2268 int new_bits = zlib->window_bits;
2270 zlib->file_bits = file_bits;
2272 /* Check against the existing value - it may not need to be
2273 * changed.
2275 if (new_bits == 0) /* no change */
2276 zlib->window_bits = file_bits;
2278 else if (new_bits != file_bits) /* rewrite required */
2279 bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
2282 zlib->header[0] = bIn;
2283 zlib->state = state = 1;
2284 break;
2286 case 1: /* second header byte */
2288 int b2 = bIn & 0xe0; /* top 3 bits */
2290 /* The checksum calculation, on the first 11 bits: */
2291 b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
2293 /* Update the checksum byte if required: */
2294 if (bIn != b2)
2296 /* If the first byte wasn't changed this indicates an error in
2297 * the checksum calculation; signal this by setting file_bits
2298 * (not window_bits) to 0.
2300 if (zlib->file_bits == zlib->window_bits)
2301 zlib->cksum = 1;
2303 bIn = (png_byte)b2;
2307 zlib->header[1] = bIn;
2308 zlib->state = state = 2;
2309 break;
2311 default: /* After the header bytes */
2312 break;
2315 /* For some streams, perhaps only those compressed with 'superfast
2316 * compression' (which results in a lot of copying) Z_BUF_ERROR can happen
2317 * immediately after all output has been flushed on the next input byte.
2318 * This is handled below when Z_BUF_ERROR is detected by adding an output
2319 * byte.
2321 zlib->z.next_in = &bIn;
2322 zlib->z.avail_in = 1;
2323 zlib->z.next_out = &bOut;
2324 zlib->z.avail_out = 0; /* Initially */
2326 /* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
2327 * byte without confusing what is going on with output.
2329 flush = Z_NO_FLUSH;
2330 out_bytes = 0;
2332 /* NOTE: expression 3 is only evaluted on 'continue', because of the
2333 * 'break' at the end of this loop below.
2335 for (;endrc == ZLIB_OK;
2336 flush = Z_SYNC_FLUSH,
2337 zlib->z.next_out = &bOut,
2338 zlib->z.avail_out = 1,
2339 ++out_bytes)
2341 zlib->rc = inflate(&zlib->z, flush);
2342 out_bytes -= zlib->z.avail_out;
2344 switch (zlib->rc)
2346 case Z_BUF_ERROR:
2347 if (zlib->z.avail_out == 0)
2348 continue; /* Try another output byte. */
2350 if (zlib->z.avail_in == 0)
2351 break; /* Try another input byte */
2353 /* Both avail_out and avail_in are 1 yet zlib returned a code
2354 * indicating no progress was possible. This is unexpected.
2356 zlib_message(zlib, 1/*unexpected*/);
2357 endrc = ZLIB_FATAL; /* stop processing */
2358 break;
2360 case Z_OK:
2361 /* Zlib is supposed to have made progress: */
2362 assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
2363 continue;
2365 case Z_STREAM_END:
2366 /* This is the successful end. */
2367 zlib->state = 3; /* end of stream */
2368 endrc = ZLIB_STREAM_END;
2369 break;
2371 case Z_NEED_DICT:
2372 zlib_message(zlib, 0/*stream error*/);
2373 endrc = ZLIB_FATAL;
2374 break;
2376 case Z_DATA_ERROR:
2377 /* The too far back error can be corrected, others cannot: */
2378 if (zlib->z.msg != NULL &&
2379 strcmp(zlib->z.msg, "invalid distance too far back") == 0)
2381 endrc = ZLIB_TOO_FAR_BACK;
2382 break;
2384 /* FALL THROUGH */
2386 default:
2387 zlib_message(zlib, 0/*stream error*/);
2388 endrc = ZLIB_FATAL;
2389 break;
2390 } /* switch (inflate rc) */
2392 /* Control gets here when further output is not possible; endrc may
2393 * still be ZLIB_OK if more input is required.
2395 break;
2396 } /* for (output bytes) */
2398 /* Keep a running count of output byte produced: */
2399 zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
2400 zlib->uncompressed_digits, out_bytes);
2402 /* Keep going, the loop will terminate when endrc is no longer set to
2403 * ZLIB_OK or all the input bytes have been consumed; meanwhile keep
2404 * adding input bytes.
2406 assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
2408 in_bytes += 1 - zlib->z.avail_in;
2409 } /* while (input bytes) */
2411 assert(in_bytes == nbytes || endrc != ZLIB_OK);
2413 /* Update the running total of input bytes consumed */
2414 zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
2415 zlib->compressed_digits, in_bytes - zlib->z.avail_in);
2417 /* At the end of the stream update the chunk with the accumulated
2418 * information if it is an improvement:
2420 if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
2422 struct chunk *chunk = zlib->chunk;
2424 chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
2425 zlib->uncompressed_bytes, zlib->uncompressed_digits);
2426 chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
2427 zlib->compressed_bytes, zlib->compressed_digits);
2428 chunk->rewrite_buffer[0] = zlib->header[0];
2429 chunk->rewrite_buffer[1] = zlib->header[1];
2431 if (zlib->window_bits != zlib->file_bits || zlib->cksum)
2433 /* A rewrite is required */
2434 chunk->rewrite_offset = zlib->rewrite_offset;
2435 chunk->rewrite_length = 2;
2438 else
2440 chunk->rewrite_offset = 0;
2441 chunk->rewrite_length = 0;
2444 if (in_bytes < nbytes)
2445 chunk_message(chunk, "extra compressed data");
2447 zlib->extra_bytes = nbytes - in_bytes;
2448 zlib->ok_bits = zlib->window_bits;
2451 return endrc;
2454 static int
2455 zlib_run(struct zlib *zlib)
2456 /* Like zlib_advance but also handles a stream of IDAT chunks. */
2458 /* The 'extra_bytes' field is set by zlib_advance if there is extra
2459 * compressed data in the chunk it handles (if it sees Z_STREAM_END before
2460 * all the input data has been used.) This function uses the value to update
2461 * the correct chunk length, so the problem should only ever be detected once
2462 * for each chunk. zlib_advance outputs the error message, though see the
2463 * IDAT specific check below.
2465 zlib->extra_bytes = 0;
2467 if (zlib->idat != NULL)
2469 struct IDAT_list *list = zlib->idat->idat_list_head;
2470 struct IDAT_list *last = zlib->idat->idat_list_tail;
2471 int skip = 0;
2473 /* 'rewrite_offset' is the offset of the LZ data within the chunk, for
2474 * IDAT it should be 0:
2476 assert(zlib->rewrite_offset == 0);
2478 /* Process each IDAT_list in turn; the caller has left the stream
2479 * positioned at the start of the first IDAT chunk data.
2481 for (;;)
2483 const unsigned int count = list->count;
2484 unsigned int i;
2486 for (i = 0; i<count; ++i)
2488 int rc;
2490 if (skip > 0) /* Skip CRC and next IDAT header */
2491 skip_12(zlib->file);
2493 skip = 12; /* for the next time */
2495 rc = zlib_advance(zlib, list->lengths[i]);
2497 switch (rc)
2499 case ZLIB_OK: /* keep going */
2500 break;
2502 case ZLIB_STREAM_END: /* stop */
2503 /* There may be extra chunks; if there are and one of them is
2504 * not zero length output the 'extra data' message. Only do
2505 * this check if errors are being output.
2507 if (zlib->global->errors && zlib->extra_bytes == 0)
2509 struct IDAT_list *check = list;
2510 int j = i+1, jcount = count;
2512 for (;;)
2514 for (; j<jcount; ++j)
2515 if (check->lengths[j] > 0)
2517 chunk_message(zlib->chunk,
2518 "extra compressed data");
2519 goto end_check;
2522 if (check == last)
2523 break;
2525 check = check->next;
2526 jcount = check->count;
2527 j = 0;
2531 end_check:
2532 /* Terminate the list at the current position, reducing the
2533 * length of the last IDAT too if required.
2535 list->lengths[i] -= zlib->extra_bytes;
2536 list->count = i+1;
2537 zlib->idat->idat_list_tail = list;
2538 /* FALL THROUGH */
2540 default:
2541 return rc;
2545 /* At the end of the compressed data and Z_STREAM_END was not seen. */
2546 if (list == last)
2547 return ZLIB_OK;
2549 list = list->next;
2553 else
2555 struct chunk *chunk = zlib->chunk;
2556 int rc;
2558 assert(zlib->rewrite_offset < chunk->chunk_length);
2560 rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
2562 /* The extra bytes in the chunk are handled now by adjusting the chunk
2563 * length to exclude them; the zlib data is always stored at the end of
2564 * the PNG chunk (although clearly this is not necessary.) zlib_advance
2565 * has already output a warning message.
2567 chunk->chunk_length -= zlib->extra_bytes;
2568 return rc;
2572 static int /* global function; not a member function */
2573 zlib_check(struct file *file, png_uint_32 offset)
2574 /* Check the stream of zlib compressed data in either idat (if given) or (if
2575 * not) chunk. In fact it is zlib_run that handles the difference in reading
2576 * a single chunk and a list of IDAT chunks.
2578 * In either case the input file must be positioned at the first byte of zlib
2579 * compressed data (the first header byte).
2581 * The return value is true on success, including the case where the zlib
2582 * header may need to be rewritten, and false on an unrecoverable error.
2584 * In the case of IDAT chunks 'offset' should be 0.
2587 fpos_t start_pos;
2588 struct zlib zlib;
2590 /* Record the start of the LZ data to allow a re-read. */
2591 file_getpos(file, &start_pos);
2593 /* First test the existing (file) window bits: */
2594 if (zlib_init(&zlib, file->idat, file->chunk, 0/*window bits*/, offset))
2596 int min_bits, max_bits, rc;
2598 /* The first run using the existing window bits. */
2599 rc = zlib_run(&zlib);
2601 switch (rc)
2603 case ZLIB_TOO_FAR_BACK:
2604 /* too far back error */
2605 file->status_code |= TOO_FAR_BACK;
2606 min_bits = zlib.window_bits + 1;
2607 max_bits = 15;
2608 break;
2610 case ZLIB_STREAM_END:
2611 if (!zlib.global->optimize_zlib &&
2612 zlib.window_bits == zlib.file_bits && !zlib.cksum)
2614 /* The trivial case where the stream is ok and optimization was
2615 * not requested.
2617 zlib_end(&zlib);
2618 return 1;
2621 max_bits = max_window_bits(zlib.uncompressed_bytes,
2622 zlib.uncompressed_digits);
2623 if (zlib.ok_bits < max_bits)
2624 max_bits = zlib.ok_bits;
2625 min_bits = 8;
2627 /* cksum is set if there is an error in the zlib header checksum
2628 * calculation in the original file (and this may be the only reason
2629 * a rewrite is required). We can't rely on the file window bits in
2630 * this case, so do the optimization anyway.
2632 if (zlib.cksum)
2633 chunk_message(zlib.chunk, "zlib checkum");
2634 break;
2637 case ZLIB_OK:
2638 /* Truncated stream; unrecoverable, gets converted to ZLIB_FATAL */
2639 zlib.z.msg = png_constcast(char*, "[truncated]");
2640 zlib_message(&zlib, 0/*expected*/);
2641 /* FALL THROUGH */
2643 default:
2644 /* Unrecoverable error; skip the chunk; a zlib_message has already
2645 * been output.
2647 zlib_end(&zlib);
2648 return 0;
2651 /* Optimize window bits or fix a too-far-back error. min_bits and
2652 * max_bits have been set appropriately, ok_bits records the bit value
2653 * known to work.
2655 while (min_bits < max_bits || max_bits < zlib.ok_bits/*if 16*/)
2657 int test_bits = (min_bits + max_bits) >> 1;
2659 if (zlib_reset(&zlib, test_bits))
2661 file_setpos(file, &start_pos);
2662 rc = zlib_run(&zlib);
2664 switch (rc)
2666 case ZLIB_TOO_FAR_BACK:
2667 min_bits = test_bits+1;
2668 if (min_bits > max_bits)
2670 /* This happens when the stream really is damaged and it
2671 * contains a distance code that addresses bytes before
2672 * the start of the uncompressed data.
2674 assert(test_bits == 15);
2676 /* Output the error that wasn't output before: */
2677 if (zlib.z.msg == NULL)
2678 zlib.z.msg = png_constcast(char*,
2679 "invalid distance too far back");
2680 zlib_message(&zlib, 0/*stream error*/);
2681 zlib_end(&zlib);
2682 return 0;
2684 break;
2686 case ZLIB_STREAM_END: /* success */
2687 max_bits = test_bits;
2688 break;
2690 default:
2691 /* A fatal error; this happens if a too-far-back error was
2692 * hiding a more serious error, zlib_advance has already
2693 * output a zlib_message.
2695 zlib_end(&zlib);
2696 return 0;
2700 else /* inflateReset2 failed */
2702 zlib_end(&zlib);
2703 return 0;
2707 /* The loop guarantees this */
2708 assert(zlib.ok_bits == max_bits);
2709 zlib_end(&zlib);
2710 return 1;
2713 else /* zlib initialization failed - skip the chunk */
2715 zlib_end(&zlib);
2716 return 0;
2720 /***************************** LIBPNG CALLBACKS *******************************/
2721 /* The strategy here is to run a regular libpng PNG file read but examine the
2722 * input data (from the file) before passing it to libpng so as to be aware of
2723 * the state we expect libpng to be in. Warning and error callbacks are also
2724 * intercepted so that they can be quieted and interpreted. Interpretation
2725 * depends on a somewhat risky string match for known error messages; let us
2726 * hope that this can be fixed in the next version of libpng.
2728 * The control structure is pointed to by the libpng error pointer. It contains
2729 * that set of structures which must persist across multiple read callbacks,
2730 * which is pretty much everything except the 'zlib' control structure.
2732 * The file structure is instantiated in the caller of the per-file routine, but
2733 * the per-file routine contains the chunk and IDAT control structures.
2735 /* The three routines read_chunk, process_chunk and sync_stream can only be
2736 * called via a call to read_chunk and only exit at a return from process_chunk.
2737 * These routines could have been written as one confusing large routine,
2738 * instead this code relies on the compiler to do tail call elimination. The
2739 * possible calls are as follows:
2741 * read_chunk
2742 * -> sync_stream
2743 * -> process_chunk
2744 * -> process_chunk
2745 * -> read_chunk
2746 * returns
2748 static void read_chunk(struct file *file);
2749 static void
2750 process_chunk(struct file *file, png_uint_32 file_crc, png_uint_32 next_length,
2751 png_uint_32 next_type)
2752 /* Called when the chunk data has been read, next_length and next_type
2753 * will be set for the next chunk (or 0 if this is IEND).
2755 * When this routine returns, chunk_length and chunk_type will be set for the
2756 * next chunk to write because if a chunk is skipped this return calls back
2757 * to read_chunk.
2760 const png_uint_32 type = file->type;
2762 if (file->global->verbose > 1)
2764 fputs(" ", stderr);
2765 type_name(file->type, stderr);
2766 fprintf(stderr, " %lu 0x%.8x 0x%.8x\n", (unsigned long)file->length,
2767 file->crc ^ 0xffffffff, file_crc);
2770 /* The basic structure seems correct but the CRC may not match, in this
2771 * case assume that it is simply a bad CRC, either wrongly calculated or
2772 * because of damaged stream data.
2774 if ((file->crc ^ 0xffffffff) != file_crc)
2776 /* The behavior is set by the 'skip' setting; if it is anything other
2777 * than SKIP_BAD_CRC ignore the bad CRC and return the chunk, with a
2778 * corrected CRC and possibly processed, to libpng. Otherwise skip the
2779 * chunk, which will result in a fatal error if the chunk is critical.
2781 file->status_code |= CRC_ERROR;
2783 /* Ignore the bad CRC */
2784 if (file->global->skip != SKIP_BAD_CRC)
2785 type_message(file, type, "bad CRC");
2787 /* This will cause an IEND with a bad CRC to stop */
2788 else if (CRITICAL(type))
2789 stop(file, READ_ERROR_CODE, "bad CRC in critical chunk");
2791 else
2793 type_message(file, type, "skipped: bad CRC");
2795 /* NOTE: this cannot be reached for IEND because it is critical. */
2796 goto skip_chunk;
2800 /* Check for other 'skip' cases and handle these; these only apply to
2801 * ancillary chunks (and not tRNS, which should probably have been a critical
2802 * chunk.)
2804 if (skip_chunk_type(file->global, type))
2805 goto skip_chunk;
2807 /* The chunk may still be skipped if problems are detected in the LZ data,
2808 * however the LZ data check requires a chunk. Handle this by instantiating
2809 * a chunk unless an IDAT is already instantiated (IDAT control structures
2810 * instantiate their own chunk.)
2812 if (type != png_IDAT)
2813 file->alloc(file, 0/*chunk*/);
2815 else if (file->idat == NULL)
2816 file->alloc(file, 1/*IDAT*/);
2818 else
2820 /* The chunk length must be updated for process_IDAT */
2821 assert(file->chunk != NULL);
2822 assert(file->chunk->chunk_type == png_IDAT);
2823 file->chunk->chunk_length = file->length;
2826 /* Record the 'next' information too, now that the original values for
2827 * this chunk have been copied. Notice that the IDAT chunks only make a
2828 * copy of the position of the first chunk, this is fine - process_IDAT does
2829 * not need the position of this chunk.
2831 file->length = next_length;
2832 file->type = next_type;
2833 getpos(file);
2835 /* Do per-type processing, note that if this code does not return from the
2836 * function the chunk will be skipped. The rewrite is cancelled here so that
2837 * it can be set in the per-chunk processing.
2839 file->chunk->rewrite_length = 0;
2840 file->chunk->rewrite_offset = 0;
2841 switch (type)
2843 default:
2844 return;
2846 case png_IHDR:
2847 /* Read this now and update the control structure with the information
2848 * it contains. The header is validated completely to ensure this is a
2849 * PNG.
2852 struct chunk *chunk = file->chunk;
2854 if (chunk->chunk_length != 13)
2855 stop_invalid(file, "IHDR length");
2857 /* Read all the IHDR information and validate it. */
2858 setpos(chunk);
2859 file->width = reread_4(file);
2860 file->height = reread_4(file);
2861 file->bit_depth = reread_byte(file);
2862 file->color_type = reread_byte(file);
2863 file->compression_method = reread_byte(file);
2864 file->filter_method = reread_byte(file);
2865 file->interlace_method = reread_byte(file);
2867 /* This validates all the fields, and calls stop_invalid if
2868 * there is a problem.
2870 calc_image_size(file);
2872 return;
2874 /* Ancillary chunks that require further processing: */
2875 case png_zTXt: case png_iCCP:
2876 if (process_zTXt_iCCP(file))
2877 return;
2878 chunk_end(&file->chunk);
2879 file_setpos(file, &file->data_pos);
2880 break;
2882 case png_iTXt:
2883 if (process_iTXt(file))
2884 return;
2885 chunk_end(&file->chunk);
2886 file_setpos(file, &file->data_pos);
2887 break;
2889 case png_IDAT:
2890 if (process_IDAT(file))
2891 return;
2892 /* First pass: */
2893 assert(next_type == png_IDAT);
2894 break;
2897 /* Control reaches this point if the chunk must be skipped. For chunks other
2898 * than IDAT this means that the zlib compressed data is fatally damanged and
2899 * the chunk will not be passed to libpng. For IDAT it means that the end of
2900 * the IDAT stream has not yet been reached and we must handle the next
2901 * (IDAT) chunk. If the LZ data in an IDAT stream cannot be read 'stop' must
2902 * be used to halt parsing of the PNG.
2904 read_chunk(file);
2905 return;
2907 /* This is the generic code to skip the current chunk; simply jump to the
2908 * next one.
2910 skip_chunk:
2911 file->length = next_length;
2912 file->type = next_type;
2913 getpos(file);
2914 read_chunk(file);
2917 static png_uint_32
2918 get32(png_bytep buffer, int offset)
2919 /* Read a 32-bit value from an 8-byte circular buffer (used only below).
2922 return
2923 (buffer[ offset & 7] << 24) +
2924 (buffer[(offset+1) & 7] << 16) +
2925 (buffer[(offset+2) & 7] << 8) +
2926 (buffer[(offset+3) & 7] );
2929 static void
2930 sync_stream(struct file *file)
2931 /* The stream seems to be messed up, attempt to resync from the current chunk
2932 * header. Executes stop on a fatal error, otherwise calls process_chunk.
2935 png_uint_32 file_crc;
2937 file->status_code |= STREAM_ERROR;
2939 if (file->global->verbose)
2941 fputs(" SYNC ", stderr);
2942 type_name(file->type, stderr);
2943 putc('\n', stderr);
2946 /* Return to the start of the chunk data */
2947 file_setpos(file, &file->data_pos);
2948 file->read_count = 8;
2950 if (read_4(file, &file_crc) == 4) /* else completely truncated */
2952 /* Ignore the recorded chunk length, proceed through the data looking for
2953 * a leading sequence of bytes that match the CRC in the following four
2954 * bytes. Each time a match is found check the next 8 bytes for a valid
2955 * length, chunk-type pair.
2957 png_uint_32 length;
2958 png_uint_32 type = file->type;
2959 png_uint_32 crc = crc_init_4(type);
2960 png_byte buffer[8];
2961 unsigned int nread = 0, nused = 0;
2963 for (length=0; length <= 0x7fffffff; ++length)
2965 int ch;
2967 if ((crc ^ 0xffffffff) == file_crc)
2969 /* A match on the CRC; for IEND this is sufficient, but for anything
2970 * else expect a following chunk header.
2972 if (type == png_IEND)
2974 file->length = length;
2975 process_chunk(file, file_crc, 0, 0);
2976 return;
2979 else
2981 /* Need 8 bytes */
2982 while (nread < 8+nused)
2984 ch = read_byte(file);
2985 if (ch == EOF)
2986 goto truncated;
2987 buffer[(nread++) & 7] = (png_byte)ch;
2990 /* Prevent overflow */
2991 nread -= nused & ~7;
2992 nused -= nused & ~7; /* or, nused &= 7 ;-) */
2994 /* Examine the 8 bytes for a valid chunk header. */
2996 png_uint_32 next_length = get32(buffer, nused);
2998 if (next_length < 0x7fffffff)
3000 png_uint_32 next_type = get32(buffer, nused+4);
3002 if (chunk_type_valid(next_type))
3004 file->read_count -= 8;
3005 process_chunk(file, file_crc, next_length, next_type);
3006 return;
3010 /* Not valid, keep going. */
3015 /* This catches up with the circular buffer which gets filled above
3016 * while checking a chunk header. This code is slightly tricky - if
3017 * the chunk_type is IEND the buffer will never be used, if it is not
3018 * the code will always read ahead exactly 8 bytes and pass this on to
3019 * process_chunk. So the invariant that IEND leaves the file position
3020 * after the IEND CRC and other chunk leave it after the *next* chunk
3021 * header is not broken.
3023 if (nread <= nused)
3025 ch = read_byte(file);
3027 if (ch == EOF)
3028 goto truncated;
3031 else
3032 ch = buffer[(++nused) & 7];
3034 crc = crc_one_byte(crc, file_crc >> 24);
3035 file_crc = (file_crc << 8) + ch;
3038 /* Control gets to here if when 0x7fffffff bytes (plus 8) have been read,
3039 * ok, treat this as a damaged stream too:
3043 truncated:
3044 stop(file, READ_ERROR_CODE, "damaged PNG stream");
3047 static void
3048 read_chunk(struct file *file)
3049 /* On entry file::data_pos must be set to the position of the first byte
3050 * of the chunk data *and* the input file must be at this position. This
3051 * routine (via process_chunk) instantiates a chunk or IDAT control structure
3052 * based on file::length and file::type and also resets these fields and
3053 * file::data_pos for the chunk after this one. For an IDAT chunk the whole
3054 * stream of IDATs will be read, until something other than an IDAT is
3055 * encountered, and the file fields will be set for the chunk after the end
3056 * of the stream of IDATs.
3058 * For IEND the file::type field will be set to 0, and nothing beyond the end
3059 * of the IEND chunk will have been read.
3062 png_uint_32 length = file->length;
3063 png_uint_32 type = file->type;
3065 /* After IEND file::type is set to 0, if libpng attempts to read
3066 * more data at this point this is a bug in libpng.
3068 if (type == 0)
3069 stop(file, UNEXPECTED_ERROR_CODE, "read beyond IEND");
3071 if (file->global->verbose > 2)
3073 fputs(" ", stderr);
3074 type_name(type, stderr);
3075 fprintf(stderr, " %lu\n", (unsigned long)length);
3078 /* Start the read_crc calculation with the chunk type, then read to the end
3079 * of the chunk data (without processing it in any way) to check that it is
3080 * all there and calculate the CRC.
3082 file->crc = crc_init_4(type);
3083 if (crc_read_many(file, length)) /* else it was truncated */
3085 png_uint_32 file_crc; /* CRC read from file */
3086 unsigned int nread = read_4(file, &file_crc);
3088 if (nread == 4)
3090 if (type != png_IEND) /* do not read beyond IEND */
3092 png_uint_32 next_length;
3094 nread += read_4(file, &next_length);
3095 if (nread == 8 && next_length <= 0x7fffffff)
3097 png_uint_32 next_type;
3099 nread += read_4(file, &next_type);
3101 if (nread == 12 && chunk_type_valid(next_type))
3103 /* Adjust the read count back to the correct value for this
3104 * chunk.
3106 file->read_count -= 8;
3107 process_chunk(file, file_crc, next_length, next_type);
3108 return;
3113 else /* IEND */
3115 process_chunk(file, file_crc, 0, 0);
3116 return;
3121 /* Control gets to here if the the stream seems invalid or damaged in some
3122 * way. Either there was a problem reading all the expected data (this
3123 * chunk's data, its CRC and the length and type of the next chunk) or the
3124 * next chunk length/type are invalid. Notice that the cases that end up
3125 * here all correspond to cases that would otherwise terminate the read of
3126 * the PNG file.
3128 sync_stream(file);
3131 /* This returns a file* from a png_struct in an implementation specific way. */
3132 static struct file *get_control(png_const_structrp png_ptr);
3134 static void
3135 error_handler(png_structp png_ptr, png_const_charp message)
3137 stop(get_control(png_ptr), LIBPNG_ERROR_CODE, message);
3140 static void
3141 warning_handler(png_structp png_ptr, png_const_charp message)
3143 struct file *file = get_control(png_ptr);
3145 if (file->global->warnings)
3146 emit_error(file, LIBPNG_WARNING_CODE, message);
3149 /* Read callback - this is where the work gets done to check the stream before
3150 * passing it to libpng
3152 static void
3153 read_callback(png_structp png_ptr, png_bytep buffer, size_t count)
3154 /* Return 'count' bytes to libpng in 'buffer' */
3156 struct file *file = get_control(png_ptr);
3157 png_uint_32 type, length; /* For the chunk be *WRITTEN* */
3158 struct chunk *chunk;
3160 /* libpng should always ask for at least one byte */
3161 if (count == 0)
3162 stop(file, UNEXPECTED_ERROR_CODE, "read callback for 0 bytes");
3164 /* The callback always reads ahead by 8 bytes - the signature or chunk header
3165 * - these bytes are stored in chunk_length and chunk_type. This block is
3166 * executed once for the signature and once for the first chunk right at the
3167 * start.
3169 if (file->read_count < 8)
3171 assert(file->read_count == 0);
3172 assert((file->status_code & TRUNCATED) == 0);
3174 (void)read_4(file, &file->length);
3176 if (file->read_count == 4)
3177 (void)read_4(file, &file->type);
3179 if (file->read_count < 8)
3181 assert((file->status_code & TRUNCATED) != 0);
3182 stop(file, READ_ERROR_CODE, "not a PNG (too short)");
3185 if (file->state == STATE_SIGNATURE)
3187 if (file->length != sig1 || file->type != sig2)
3188 stop(file, LIBPNG_ERROR_CODE, "not a PNG (signature)");
3190 /* Else write it (this is the initialization of write_count, prior to
3191 * this it contains CLEAR garbage.)
3193 file->write_count = 0;
3196 else
3198 assert(file->state == STATE_CHUNKS);
3200 /* The first chunk must be a well formed IHDR (this could be relaxed to
3201 * use the checks in process_chunk, but that seems unnecessary.)
3203 if (file->length != 13 || file->type != png_IHDR)
3204 stop(file, LIBPNG_ERROR_CODE, "not a PNG (IHDR)");
3206 /* The position of the data must be stored too */
3207 getpos(file);
3211 /* Retrieve previous state (because the read callbacks are made pretty much
3212 * byte-by-byte in the sequential reader prior to 1.7).
3214 chunk = file->chunk;
3216 if (chunk != NULL)
3218 length = chunk->chunk_length;
3219 type = chunk->chunk_type;
3222 else
3224 /* This is the signature case; for IDAT and other chunks these values will
3225 * be overwritten when read_chunk is called below.
3227 length = file->length;
3228 type = file->type;
3233 png_uint_32 b;
3235 /* Complete the read of a chunk; as a side effect this also instantiates
3236 * a chunk control structure and sets the file length/type/data_pos fields
3237 * for the *NEXT* chunk header.
3239 * NOTE: at an IDAT any following IDAT chunks will also be read and the
3240 * next_ fields will refer to the chunk after the last IDAT.
3242 * NOTE: read_chunk only returns when it has read a chunk that must now be
3243 * written.
3245 if (file->state != STATE_SIGNATURE && chunk == NULL)
3247 assert(file->read_count == 8);
3248 assert(file->idat == NULL);
3249 read_chunk(file);
3250 chunk = file->chunk;
3251 assert(chunk != NULL);
3253 /* Do the initialization that was not done before. */
3254 length = chunk->chunk_length;
3255 type = chunk->chunk_type;
3257 /* And start writing the new chunk. */
3258 file->write_count = 0;
3261 /* The chunk_ fields describe a chunk that must be written, or hold the
3262 * signature. Write the header first. In the signature case this
3263 * rewrites the signature.
3265 switch (file->write_count)
3267 case 0: b = length >> 24; break;
3268 case 1: b = length >> 16; break;
3269 case 2: b = length >> 8; break;
3270 case 3: b = length ; break;
3272 case 4: b = type >> 24; break;
3273 case 5: b = type >> 16; break;
3274 case 6: b = type >> 8; break;
3275 case 7: b = type ; break;
3277 case 8:
3278 /* The header has been written. If this is really the signature
3279 * that's all that is required and we can go to normal chunk
3280 * processing.
3282 if (file->state == STATE_SIGNATURE)
3284 /* The signature has been written, the tail call to read_callback
3285 * below (it's just a goto to the start with a decent compiler)
3286 * will read the IHDR header ahead and validate it.
3288 assert(length == sig1 && type == sig2);
3289 file->read_count = 0; /* Forces a header read */
3290 file->state = STATE_CHUNKS; /* IHDR: checked above */
3291 read_callback(png_ptr, buffer, count);
3292 return;
3295 else
3297 /* Set up for write, notice that repositioning the input stream
3298 * is only necessary if something is to be read from it. Also
3299 * notice that for the IDAT stream this must only happen once -
3300 * on the first IDAT - to get back to the start of the list and
3301 * this is done inside process_IDAT:
3303 chunk->write_crc = crc_init_4(type);
3304 if (file->state != STATE_IDAT && length > 0)
3305 setpos(chunk);
3307 /* FALL THROUGH */
3309 default:
3310 /* NOTE: the arithmetic below overflows and gives a large positive
3311 * png_uint_32 value until the whole chunk data has been written.
3313 switch (file->write_count - length)
3315 /* Write the chunk data, normally this just comes from
3316 * the file. The only exception is for that part of a
3317 * chunk which is zlib data and which must be rewritten,
3318 * and IDAT chunks which can be completely
3319 * reconstructed.
3321 default:
3322 if (file->state == STATE_IDAT)
3324 struct IDAT *idat = file->idat;
3326 assert(idat != NULL);
3328 /* Read an IDAT byte from the input stream of IDAT chunks.
3329 * Because the IDAT stream can be re-chunked this stream is
3330 * held in the struct IDAT members. The chunk members, in
3331 * particular chunk_length (and therefore the length local)
3332 * refer to the output chunk.
3334 while (idat->idat_index >= idat->idat_length)
3336 /* Advance one chunk */
3337 struct IDAT_list *cur = idat->idat_cur;
3339 assert(idat->idat_index == idat->idat_length);
3340 assert(cur != NULL && cur->count > 0);
3342 /* NOTE: IDAT_list::count here, not IDAT_list::length */
3343 if (++(idat->idat_count) >= cur->count)
3345 assert(idat->idat_count == cur->count);
3347 /* Move on to the next IDAT_list: */
3348 cur = cur->next;
3350 /* This is an internal error - read beyond the end of
3351 * the pre-calculated stream.
3353 if (cur == NULL || cur->count == 0)
3354 stop(file, UNEXPECTED_ERROR_CODE,
3355 "read beyond end of IDAT");
3357 idat->idat_count = 0;
3358 idat->idat_cur = cur;
3361 idat->idat_index = 0;
3362 /* Zero length IDAT chunks are permitted, so the length
3363 * here may be 0.
3365 idat->idat_length = cur->lengths[idat->idat_count];
3367 /* And skip 12 bytes to the next chunk data */
3368 skip_12(file);
3371 /* The index is always that of the next byte, the rest of
3372 * the information is always the current IDAT chunk and the
3373 * current list.
3375 ++(idat->idat_index);
3378 /* Read the byte from the stream. */
3379 b = reread_byte(file);
3381 /* If the byte must be rewritten handle that here */
3382 if (chunk->rewrite_length > 0)
3384 if (chunk->rewrite_offset > 0)
3385 --(chunk->rewrite_offset);
3387 else
3389 b = chunk->rewrite_buffer[0];
3390 memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,
3391 (sizeof chunk->rewrite_buffer)-
3392 (sizeof chunk->rewrite_buffer[0]));
3394 --(chunk->rewrite_length);
3398 chunk->write_crc = crc_one_byte(chunk->write_crc, b);
3399 break;
3401 /* The CRC is written at:
3403 * chunk_write == chunk_length+8..chunk_length+11
3405 * so 8 to 11. The CRC is not (yet) conditioned.
3407 case 8: b = chunk->write_crc >> 24; goto write_crc;
3408 case 9: b = chunk->write_crc >> 16; goto write_crc;
3409 case 10: b = chunk->write_crc >> 8; goto write_crc;
3410 case 11:
3411 /* This must happen before the chunk_end below: */
3412 b = chunk->write_crc;
3414 if (file->global->verbose > 2)
3416 fputs(" ", stderr);
3417 type_name(type, stderr);
3418 fprintf(stderr, " %lu 0x%.8x\n", (unsigned long)length,
3419 chunk->write_crc ^ 0xffffffff);
3422 /* The IDAT stream is written without a call to read_chunk
3423 * until the end is reached. rechunk_length() calculates the
3424 * length of the output chunks. Control gets to this point at
3425 * the end of an *output* chunk - the length calculated by
3426 * rechunk_length. If this corresponds to the end of the
3427 * input stream stop writing IDAT chunks, otherwise continue.
3429 if (file->state == STATE_IDAT &&
3430 (file->idat->idat_index < file->idat->idat_length ||
3431 1+file->idat->idat_count < file->idat->idat_cur->count ||
3432 file->idat->idat_cur != file->idat->idat_list_tail))
3434 /* Write another IDAT chunk. Call rechunk_length to
3435 * calculate the length required.
3437 length = chunk->chunk_length = rechunk_length(file->idat);
3438 assert(type == png_IDAT);
3439 file->write_count = 0; /* for the new chunk */
3440 --(file->write_count); /* fake out the increment below */
3443 else
3445 /* Entered at the end of a non-IDAT chunk and at the end of
3446 * the IDAT stream. The rewrite should have been cleared.
3448 if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)
3449 stop(file, UNEXPECTED_ERROR_CODE, "pending rewrite");
3451 /* This is the last byte so reset chunk_read for the next
3452 * chunk and move the input file to the position after the
3453 * *next* chunk header if required.
3455 file->read_count = 8;
3456 file_setpos(file, &file->data_pos);
3458 if (file->idat == NULL)
3459 chunk_end(&file->chunk);
3461 else
3462 IDAT_end(&file->idat);
3465 write_crc:
3466 b ^= 0xff; /* conditioning */
3467 break;
3469 break;
3472 /* Write one byte */
3473 b &= 0xff;
3474 *buffer++ = (png_byte)b;
3475 --count;
3476 write_byte(file, (png_byte)b); /* increments chunk_write */
3478 while (count > 0);
3481 /* Bundle the file and an uninitialized chunk and IDAT control structure
3482 * together to allow implementation of the chunk/IDAT allocate routine.
3484 struct control
3486 struct file file;
3487 struct chunk chunk;
3488 struct IDAT idat;
3491 static int
3492 control_end(struct control *control)
3494 return file_end(&control->file);
3497 static struct file *
3498 get_control(png_const_structrp png_ptr)
3500 /* This just returns the (file*). The chunk and idat control structures
3501 * don't always exist.
3503 struct control *control = png_voidcast(struct control*,
3504 png_get_error_ptr(png_ptr));
3505 return &control->file;
3508 static void
3509 allocate(struct file *file, int allocate_idat)
3511 struct control *control = png_voidcast(struct control*, file->alloc_ptr);
3513 if (allocate_idat)
3515 struct IDAT *idat;
3517 assert(file->idat == NULL);
3518 idat = &control->idat;
3519 IDAT_init(idat, file);
3520 file->idat = idat;
3523 else /* chunk */
3525 struct chunk *chunk;
3527 assert(file->chunk == NULL);
3528 chunk = &control->chunk;
3529 chunk_init(chunk, file);
3530 file->chunk = chunk;
3534 static int
3535 control_init(struct control *control, struct global *global,
3536 const char *file_name, const char *out_name)
3537 /* This wraps file_init(&control::file) and simply returns the result from
3538 * file_init.
3541 return file_init(&control->file, global, file_name, out_name, control,
3542 allocate);
3545 static int
3546 read_png(struct control *control)
3547 /* Read a PNG, return 0 on success else an error (status) code; a bit mask as
3548 * defined for file::status_code as above.
3551 png_structp png_ptr;
3552 png_infop info_ptr = NULL;
3553 volatile png_bytep row = NULL, display = NULL;
3554 volatile int rc;
3556 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
3557 error_handler, warning_handler);
3559 if (png_ptr == NULL)
3561 /* This is not really expected. */
3562 log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
3563 control->file.status_code |= INTERNAL_ERROR;
3564 return LIBPNG_ERROR_CODE;
3567 rc = setjmp(control->file.jmpbuf);
3568 if (rc == 0)
3570 png_set_read_fn(png_ptr, control, read_callback);
3572 info_ptr = png_create_info_struct(png_ptr);
3573 if (info_ptr == NULL)
3574 png_error(png_ptr, "OOM allocating info structure");
3576 if (control->file.global->verbose)
3577 fprintf(stderr, " INFO\n");
3579 png_read_info(png_ptr, info_ptr);
3582 png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
3584 row = png_voidcast(png_byte*, malloc(rowbytes));
3585 display = png_voidcast(png_byte*, malloc(rowbytes));
3587 if (row == NULL || display == NULL)
3588 png_error(png_ptr, "OOM allocating row buffers");
3591 png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
3592 int passes = png_set_interlace_handling(png_ptr);
3593 int pass;
3595 png_start_read_image(png_ptr);
3597 for (pass = 0; pass < passes; ++pass)
3599 png_uint_32 y = height;
3601 /* NOTE: this trashes the row each time; interlace handling won't
3602 * work, but this avoids memory thrashing for speed testing.
3604 while (y-- > 0)
3605 png_read_row(png_ptr, row, display);
3610 if (control->file.global->verbose)
3611 fprintf(stderr, " END\n");
3613 /* Make sure to read to the end of the file: */
3614 png_read_end(png_ptr, info_ptr);
3617 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
3618 if (row != NULL) free(row);
3619 if (display != NULL) free(display);
3620 return rc;
3623 static void
3624 one_file(struct global *global, const char *file_name, const char *out_name)
3626 int rc;
3627 struct control control;
3629 if (global->verbose)
3630 fprintf(stderr, "FILE %s -> %s\n", file_name,
3631 out_name ? out_name : "<none>");
3633 /* Although control_init can return a failure code the structure is always
3634 * initialized, so control_end can be used to accumulate any status codes.
3636 rc = control_init(&control, global, file_name, out_name);
3638 if (rc == 0)
3639 rc = read_png(&control);
3641 rc |= control_end(&control);
3644 static void
3645 usage(const char *prog)
3647 /* ANSI C-90 limits strings to 509 characters, so use a string array: */
3648 size_t i;
3649 static const char *usage_string[] = {
3650 " Tests, optimizes and optionally fixes the zlib header in PNG files.",
3651 " Optionally, when fixing, strips ancilliary chunks from the file.",
3653 "OPTIONS",
3654 " OPERATION",
3655 " By default files are just checked for readability with a summary of the",
3656 " of zlib issues founds for each compressed chunk and the IDAT stream in",
3657 " the file.",
3658 " --optimize (-o):",
3659 " Find the smallest deflate window size for the compressed data.",
3660 " --strip=[none|crc|unsafe|unused|transform|color|all]:",
3661 " none (default): Retain all chunks.",
3662 " crc: Remove chunks with a bad CRC.",
3663 " unsafe: Remove chunks that may be unsafe to retain if the image data",
3664 " is modified. This is set automatically if --max is given but",
3665 " may be cancelled by a later --strip=none.",
3666 " unused: Remove chunks not used by libpng when decoding an image.",
3667 " This retains any chunks that might be used by libpng image",
3668 " transformations.",
3669 " transform: unused+bKGD.",
3670 " color: transform+iCCP and cHRM.",
3671 " all: color+gAMA and sRGB.",
3672 " Only ancillary chunks are ever removed. In addition the tRNS and sBIT",
3673 " chunks are never removed as they affect exact interpretation of the",
3674 " image pixel values. The following known chunks are treated specially",
3675 " by the above options:",
3676 " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
3677 " values.",
3678 " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also",
3679 " specifies the exact encoding of a pixel value however in practice",
3680 " most programs will ignore it.",
3681 " bKGD [transform]: This is used by libpng transforms."
3682 " --max=<number>:",
3683 " Use IDAT chunks sized <number>. If no number is given the the IDAT",
3684 " chunks will be the maximum size permitted; 2^31-1 bytes. If the option",
3685 " is omitted the original chunk sizes will not be changed. When the",
3686 " option is given --strip=unsafe is set automatically, this may be",
3687 " cancelled if you know that all unknown unsafe-to-copy chunks really are",
3688 " safe to copy across an IDAT size change. This is true of all chunks",
3689 " that have ever been formally proposed as PNG extensions.",
3690 " MESSAGES",
3691 " By default the program only outputs summaries for each file.",
3692 " --quiet (-q):",
3693 " Do not output the summaries except for files which cannot be read. With",
3694 " two --quiets these are not output either.",
3695 " --errors (-e):",
3696 " Output errors from libpng and the program (except too-far-back).",
3697 " --warnings (-w):",
3698 " Output warnings from libpng.",
3699 " OUTPUT",
3700 " By default nothing is written.",
3701 " --out=<file>:",
3702 " Write the optimized/corrected version of the next PNG to <file>. This",
3703 " overrides the following two options",
3704 " --suffix=<suffix>:",
3705 " Set --out=<name><suffix> for all following files unless overridden on",
3706 " a per-file basis by explicit --out.",
3707 " --prefix=<prefix>:",
3708 " Set --out=<prefix><name> for all the following files unless overridden",
3709 " on a per-file basis by explicit --out.",
3710 " These two options can be used together to produce a suffix and prefix.",
3711 " INTERNAL OPTIONS",
3712 #if 0 /*NYI*/
3713 #ifdef PNG_MAXIMUM_INFLATE_WINDOW
3714 " --test:",
3715 " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables",
3716 " output as this would produce a broken file.",
3717 #endif
3718 #endif
3720 "EXIT CODES",
3721 " *** SUBJECT TO CHANGE ***",
3722 " The program exit code is value in the range 0..127 holding a bit mask of",
3723 " the following codes. Notice that the results for each file are combined",
3724 " together - check one file at a time to get a meaningful error code!",
3725 " 0x01: The zlib too-far-back error existed in at least one chunk.",
3726 " 0x02: At least once chunk had a CRC error.",
3727 " 0x04: A chunk length was incorrect.",
3728 " 0x08: The file was truncated.",
3729 " Errors less than 16 are potentially recoverable, for a single file if the",
3730 " exit code is less than 16 the file could be read (with corrections if a",
3731 " non-zero code is returned).",
3732 " 0x10: The file could not be read, even with corrections.",
3733 " 0x20: The output file could not be written.",
3734 " 0x40: An unexpected, potentially internal, error occured.",
3735 " If the command line arguments are incorrect the program exits with exit",
3736 " 255. Some older operating systems only support 7-bit exit codes, on those",
3737 " systems it is suggested that this program is first tested by supplying",
3738 " invalid arguments.",
3740 "DESCRIPTION",
3741 " " PROGRAM_NAME ":",
3742 " checks each PNG file on the command line for errors. By default errors are",
3743 " not output and the program just returns an exit code and prints a summary.",
3744 " With the --quiet (-q) option the summaries are suppressed too and the",
3745 " program only outputs unexpected errors (internal errors and file open",
3746 " errors).",
3747 " Various known problems in PNG files are fixed while the file is being read",
3748 " The exit code says what problems were fixed. In particular the zlib error:",
3750 " \"invalid distance too far back\"",
3752 " caused by an incorrect optimization of a zlib stream is fixed in any",
3753 " compressed chunk in which it is encountered. An integrity problem of the",
3754 " PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
3755 " is also fixed. Chunk CRC errors are automatically fixed up.",
3757 " Setting one of the \"OUTPUT\" options causes the possibly modified file to",
3758 " be written to a new file.",
3760 " Notice that some PNG files with the zlib optimization problem can still be",
3761 " read by libpng under some circumstances. This program will still detect",
3762 " and, if requested, correct the error.",
3764 " The program will reliably process all files on the command line unless",
3765 " either an invalid argument causes the usage message (this message) to be",
3766 " produced or the program crashes.",
3768 " The summary lines describe issues encountered with the zlib compressed",
3769 " stream of a chunk. They have the following format, which is SUBJECT TO",
3770 " CHANGE in the future:",
3772 " chunk reason comp-level p1 p2 p3 p4 file",
3774 " p1 through p4 vary according to the 'reason'. There are always 8 space",
3775 " separated fields. Reasons specific formats are:",
3777 " chunk ERR status code read-errno write-errno message file",
3778 " chunk SKP comp-level file-bits zlib-rc compressed message file",
3779 " chunk ??? comp-level file-bits ok-bits compressed uncompress file",
3781 " The various fields are",
3783 "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem",
3784 " is reported by libpng at the start of the IDAT stream.",
3785 "$2 reason: One of:",
3786 " CHK: A zlib header checksum was detected and fixed.",
3787 " TFB: The zlib too far back error was detected and fixed.",
3788 " OK : No errors were detected in the zlib stream and optimization",
3789 " was not requested, or was not possible.",
3790 " OPT: The zlib stream window bits value could be improved (and was).",
3791 " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
3792 " explanation 'message'",
3793 " ERR: The read of the file was aborted. The parameters explain why.",
3794 "$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above.",
3795 " This is printed as a 2 digit hexadecimal value",
3796 " comp-level: The recorded compression level (FLEVEL) of a zlib stream",
3797 " expressed as a string {supfast,stdfast,default,maximum}",
3798 "$4 code: The file exit code; where stop was called, as a fairly terse",
3799 " string {warning,libpng,zlib,invalid,read,write,unexpected}.",
3800 " file-bits: The zlib window bits recorded in the file.",
3801 "$5 read-errno: A system errno value from a read translated by strerror(3).",
3802 " zlib-rc: A zlib return code as a string (see zlib.h).",
3803 " ok-bits: The smallest zlib window bits value that works.",
3804 "$6 write-errno:A system errno value from a write translated by strerror(3).",
3805 " compressed: The count of compressed bytes in the zlib stream, when the",
3806 " reason is 'SKP'; this is a count of the bytes read from the",
3807 " stream when the fatal error was encountered.",
3808 "$7 message: An error message (spaces replaced by _, as in all parameters),",
3809 " uncompress: The count of bytes from uncompressing the zlib stream; this",
3810 " may not be the same as the number of bytes in the image.",
3811 "$8 file: The name of the file (this may contain spaces).",
3814 fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
3816 for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
3818 if (usage_string[i] != 0)
3819 fputs(usage_string[i], stderr);
3821 fputc('\n', stderr);
3824 exit(255);
3828 main(int argc, const char **argv)
3830 const char * prog = *argv;
3831 const char * outfile = NULL;
3832 const char * suffix = NULL;
3833 const char * prefix = NULL;
3834 int done = 0; /* if at least one file is processed */
3835 struct global global;
3837 global_init(&global);
3839 while (--argc > 0)
3841 ++argv;
3843 if (strcmp(*argv, "--debug") == 0)
3845 /* To help debugging problems: */
3846 global.errors = global.warnings = 1;
3847 global.quiet = 0;
3848 global.verbose = 7;
3851 else if (strncmp(*argv, "--max=", 6) == 0)
3853 global.idat_max = (png_uint_32)atol(6+*argv);
3855 if (global.skip < SKIP_UNSAFE)
3856 global.skip = SKIP_UNSAFE;
3859 else if (strcmp(*argv, "--max") == 0)
3861 global.idat_max = 0x7fffffff;
3863 if (global.skip < SKIP_UNSAFE)
3864 global.skip = SKIP_UNSAFE;
3867 else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
3868 global.optimize_zlib = 1;
3870 else if (strncmp(*argv, "--out=", 6) == 0)
3871 outfile = 6+*argv;
3873 else if (strncmp(*argv, "--suffix=", 9) == 0)
3874 suffix = 9+*argv;
3876 else if (strncmp(*argv, "--prefix=", 9) == 0)
3877 prefix = 9+*argv;
3879 else if (strcmp(*argv, "--strip=none") == 0)
3880 global.skip = SKIP_NONE;
3882 else if (strcmp(*argv, "--strip=crc") == 0)
3883 global.skip = SKIP_BAD_CRC;
3885 else if (strcmp(*argv, "--strip=unsafe") == 0)
3886 global.skip = SKIP_UNSAFE;
3888 else if (strcmp(*argv, "--strip=unused") == 0)
3889 global.skip = SKIP_UNUSED;
3891 else if (strcmp(*argv, "--strip=transform") == 0)
3892 global.skip = SKIP_TRANSFORM;
3894 else if (strcmp(*argv, "--strip=color") == 0)
3895 global.skip = SKIP_COLOR;
3897 else if (strcmp(*argv, "--strip=all") == 0)
3898 global.skip = SKIP_ALL;
3900 else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
3901 global.errors = 1;
3903 else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
3904 global.warnings = 1;
3906 else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
3908 if (global.quiet)
3909 global.quiet = 2;
3911 else
3912 global.quiet = 1;
3915 else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
3916 ++global.verbose;
3918 #if 0
3919 /* NYI */
3920 # ifdef PNG_MAXIMUM_INFLATE_WINDOW
3921 else if (strcmp(*argv, "--test") == 0)
3922 ++set_option;
3923 # endif
3924 #endif
3926 else if ((*argv)[0] == '-')
3927 usage(prog);
3929 else
3931 size_t outlen = strlen(*argv);
3932 char temp_name[FILENAME_MAX+1];
3934 if (outfile == NULL) /* else this takes precedence */
3936 /* Consider the prefix/suffix options */
3937 if (prefix != NULL)
3939 size_t prefixlen = strlen(prefix);
3941 if (prefixlen+outlen > FILENAME_MAX)
3943 fprintf(stderr, "%s: output file name too long: %s%s%s\n",
3944 prog, prefix, *argv, suffix ? suffix : "");
3945 global.status_code |= WRITE_ERROR;
3946 continue;
3949 memcpy(temp_name, prefix, prefixlen);
3950 memcpy(temp_name+prefixlen, *argv, outlen);
3951 outlen += prefixlen;
3952 outfile = temp_name;
3955 else if (suffix != NULL)
3956 memcpy(temp_name, *argv, outlen);
3958 temp_name[outlen] = 0;
3960 if (suffix != NULL)
3962 size_t suffixlen = strlen(suffix);
3964 if (outlen+suffixlen > FILENAME_MAX)
3966 fprintf(stderr, "%s: output file name too long: %s%s\n",
3967 prog, *argv, suffix);
3968 global.status_code |= WRITE_ERROR;
3969 continue;
3972 memcpy(temp_name+outlen, suffix, suffixlen);
3973 outlen += suffixlen;
3974 temp_name[outlen] = 0;
3975 outfile = temp_name;
3979 (void)one_file(&global, *argv, outfile);
3980 ++done;
3981 outfile = NULL;
3985 if (!done)
3986 usage(prog);
3988 return global_end(&global);
3991 #else /* PNG_ZLIB_VERNUM < 0x1240 */
3993 main(void)
3995 fprintf(stderr,
3996 "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n",
3997 PNG_ZLIB_VERNUM);
3998 return 77;
4000 #endif /* PNG_ZLIB_VERNUM */
4002 #else /* No read support */
4005 main(void)
4007 fprintf(stderr, "pngfix does not work without read support\n");
4008 return 77;
4010 #endif /* PNG_READ_SUPPORTED */