sync with TL rev. 36644 (trunk)
[luatex.git] / source / libs / libpng / libpng-1.6.17 / contrib / tools / pngfix.c
blob67bab6aec694eff951be5a5bd0f989242c06fa22
1 /* pngfix.c
3 * Copyright (c) 2014-2015 John Cunningham Bowler
5 * Last changed in libpng 1.6.17 [March 26, 2015]
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.
12 * See the usage message for more information.
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <limits.h>
19 #include <errno.h>
20 #include <assert.h>
22 #define implies(x,y) assert(!(x) || (y))
24 #ifdef __GNUC__
25 /* This is used to fix the error:
27 * pngfix.c:
28 * In function 'zlib_advance':
29 * pngfix.c:181:13: error: assuming signed overflow does not
30 * occur when simplifying conditional to constant [-Werror=strict-overflow]
32 # define FIX_GCC volatile
33 #else
34 # define FIX_GCC
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_SETJMP_SUPPORTED
53 #include <setjmp.h>
55 #if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED)
56 /* zlib.h defines the structure z_stream, an instance of which is included
57 * in this structure and is required for decompressing the LZ compressed
58 * data in PNG files.
60 #ifndef ZLIB_CONST
61 /* We must ensure that zlib uses 'const' in declarations. */
62 # define ZLIB_CONST
63 #endif
64 #include <zlib.h>
65 #ifdef const
66 /* zlib.h sometimes #defines const to nothing, undo this. */
67 # undef const
68 #endif
70 /* zlib.h has mediocre z_const use before 1.2.6, this stuff is for compatibility
71 * with older builds.
73 #if ZLIB_VERNUM < 0x1260
74 # define PNGZ_MSG_CAST(s) png_constcast(char*,s)
75 # define PNGZ_INPUT_CAST(b) png_constcast(png_bytep,b)
76 #else
77 # define PNGZ_MSG_CAST(s) (s)
78 # define PNGZ_INPUT_CAST(b) (b)
79 #endif
81 #ifndef PNG_MAXIMUM_INFLATE_WINDOW
82 # error "pngfix not supported in this libpng version"
83 #endif
85 #if ZLIB_VERNUM >= 0x1240
87 /* Copied from pngpriv.h */
88 #ifdef __cplusplus
89 # define png_voidcast(type, value) static_cast<type>(value)
90 # define png_constcast(type, value) const_cast<type>(value)
91 # define png_aligncast(type, value) \
92 static_cast<type>(static_cast<void*>(value))
93 # define png_aligncastconst(type, value) \
94 static_cast<type>(static_cast<const void*>(value))
95 #else
96 # define png_voidcast(type, value) (value)
97 # define png_constcast(type, value) ((type)(value))
98 # define png_aligncast(type, value) ((void*)(value))
99 # define png_aligncastconst(type, value) ((const void*)(value))
100 #endif /* __cplusplus */
102 #if PNG_LIBPNG_VER < 10700
103 /* Chunk tags (copied from pngpriv.h) */
104 #define PNG_32b(b,s) ((png_uint_32)(b) << (s))
105 #define PNG_U32(b1,b2,b3,b4) \
106 (PNG_32b(b1,24) | PNG_32b(b2,16) | PNG_32b(b3,8) | PNG_32b(b4,0))
108 /* Constants for known chunk types. */
109 #define png_IDAT PNG_U32( 73, 68, 65, 84)
110 #define png_IEND PNG_U32( 73, 69, 78, 68)
111 #define png_IHDR PNG_U32( 73, 72, 68, 82)
112 #define png_PLTE PNG_U32( 80, 76, 84, 69)
113 #define png_bKGD PNG_U32( 98, 75, 71, 68)
114 #define png_cHRM PNG_U32( 99, 72, 82, 77)
115 #define png_fRAc PNG_U32(102, 82, 65, 99) /* registered, not defined */
116 #define png_gAMA PNG_U32(103, 65, 77, 65)
117 #define png_gIFg PNG_U32(103, 73, 70, 103)
118 #define png_gIFt PNG_U32(103, 73, 70, 116) /* deprecated */
119 #define png_gIFx PNG_U32(103, 73, 70, 120)
120 #define png_hIST PNG_U32(104, 73, 83, 84)
121 #define png_iCCP PNG_U32(105, 67, 67, 80)
122 #define png_iTXt PNG_U32(105, 84, 88, 116)
123 #define png_oFFs PNG_U32(111, 70, 70, 115)
124 #define png_pCAL PNG_U32(112, 67, 65, 76)
125 #define png_pHYs PNG_U32(112, 72, 89, 115)
126 #define png_sBIT PNG_U32(115, 66, 73, 84)
127 #define png_sCAL PNG_U32(115, 67, 65, 76)
128 #define png_sPLT PNG_U32(115, 80, 76, 84)
129 #define png_sRGB PNG_U32(115, 82, 71, 66)
130 #define png_sTER PNG_U32(115, 84, 69, 82)
131 #define png_tEXt PNG_U32(116, 69, 88, 116)
132 #define png_tIME PNG_U32(116, 73, 77, 69)
133 #define png_tRNS PNG_U32(116, 82, 78, 83)
134 #define png_zTXt PNG_U32(122, 84, 88, 116)
135 #endif
137 /* The 8 byte signature as a pair of 32 bit quantities */
138 #define sig1 PNG_U32(137, 80, 78, 71)
139 #define sig2 PNG_U32( 13, 10, 26, 10)
141 /* Is the chunk critical? */
142 #define CRITICAL(chunk) (((chunk) & PNG_U32(32,0,0,0)) == 0)
144 /* Is it safe to copy? */
145 #define SAFE_TO_COPY(chunk) (((chunk) & PNG_U32(0,0,0,32)) != 0)
147 /* Fix ups for builds with limited read support */
148 #ifndef PNG_ERROR_TEXT_SUPPORTED
149 # define png_error(a,b) png_err(a)
150 #endif
152 /********************************* UTILITIES **********************************/
153 /* UNREACHED is a value to cause an assert to fail. Because of the way the
154 * assert macro is written the string "UNREACHED" is produced in the error
155 * message.
157 #define UNREACHED 0
159 /* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8 byte
160 * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so
161 * arithmetic of 80-bit numbers is sufficient. This representation uses an
162 * arbitrary length array of png_uint_16 digits (0..65535). The representation
163 * is little endian.
165 * The arithmetic functions take zero to two uarb values together with the
166 * number of digits in those values and write the result to the given uarb
167 * (always the first argument) returning the number of digits in the result.
168 * If the result is negative the return value is also negative (this would
169 * normally be an error).
171 typedef png_uint_16 udigit; /* A 'unum' is an array of these */
172 typedef png_uint_16p uarb;
173 typedef png_const_uint_16p uarbc;
175 #define UDIGITS(unum) ((sizeof unum)/(sizeof (udigit))
176 /* IMPORTANT: only apply this to an array, applied to a pointer the result
177 * will typically be '2', which is not useful.
180 static int
181 uarb_set(uarb result, png_alloc_size_t val)
182 /* Set (initialize) 'result' to 'val'. The size required for 'result' must
183 * be determined by the caller from a knowledge of the maximum for 'val'.
186 int ndigits = 0;
188 while (val > 0)
190 result[ndigits++] = (png_uint_16)(val & 0xffff);
191 val >>= 16;
194 return ndigits;
197 static int
198 uarb_copy(uarb to, uarb from, int idigits)
199 /* Copy a uarb, may reduce the digit count */
201 int d, odigits;
203 for (d=odigits=0; d<idigits; ++d)
204 if ((to[d] = from[d]) != 0)
205 odigits = d+1;
207 return odigits;
210 static int
211 uarb_inc(uarb num, int in_digits, png_int_32 add)
212 /* This is a signed 32-bit add, except that to avoid overflow the value added
213 * or subtracted must be no more than 2^31-65536. A negative result
214 * indicates a negative number (which is an error below). The size of
215 * 'num' should be max(in_digits+1,2) for arbitrary 'add' but can be just
216 * in_digits+1 if add is known to be in the range -65535..65535.
219 FIX_GCC int out_digits = 0;
221 while (out_digits < in_digits)
223 add += num[out_digits];
224 num[out_digits++] = (png_uint_16)(add & 0xffff);
225 add >>= 16;
228 while (add != 0 && add != (-1))
230 num[out_digits++] = (png_uint_16)(add & 0xffff);
231 add >>= 16;
234 if (add == 0)
236 while (out_digits > 0 && num[out_digits-1] == 0)
237 --out_digits;
238 return out_digits; /* may be 0 */
241 else /* negative result */
243 while (out_digits > 1 && num[out_digits-1] == 0xffff)
244 --out_digits;
246 return -out_digits;
250 static int
251 uarb_add32(uarb num, int in_digits, png_uint_32 add)
252 /* As above but this works with any 32-bit value and only does 'add' */
254 if (in_digits > 0)
256 in_digits = uarb_inc(num, in_digits, add & 0xffff);
257 return uarb_inc(num+1, in_digits-1, add >> 16)+1;
260 return uarb_set(num, add);
263 static int
264 uarb_mult_digit(uarb acc, int a_digits, uarb num, FIX_GCC int n_digits,
265 png_uint_16 val)
266 /* Primitive one-digit multiply - 'val' must be 0..65535. Note that this
267 * primitive is a multiply and accumulate - the result of *num * val is added
268 * to *acc.
270 * This is a one-digit multiply, so the product may be up to one digit longer
271 * than 'num', however the add to 'acc' means that the caller must ensure
272 * that 'acc' is at least one digit longer than this *and* at least one digit
273 * longer than the current length of 'acc'. (Or the caller must otherwise
274 * ensure 'adigits' is adequate from knowledge of the values.)
277 /* The digits in *acc, *num and val are in the range 0..65535, so the
278 * result below is at most (65535*65535)+2*65635 = 65535*(65535+2), which is
279 * exactly 0xffffffff.
281 if (val > 0 && n_digits > 0) /* Else the product is 0 */
283 png_uint_32 carry = 0;
284 int out_digits = 0;
286 while (out_digits < n_digits || carry > 0)
288 if (out_digits < a_digits)
289 carry += acc[out_digits];
291 if (out_digits < n_digits)
292 carry += (png_uint_32)num[out_digits] * val;
294 acc[out_digits++] = (png_uint_16)(carry & 0xffff);
295 carry >>= 16;
298 /* So carry is 0 and all the input digits have been consumed. This means
299 * that it is possible to skip any remaining digits in acc.
301 if (out_digits > a_digits)
302 return out_digits;
305 return a_digits;
308 static int
309 uarb_mult32(uarb acc, int a_digits, uarb num, int n_digits, png_uint_32 val)
310 /* calculate acc += num * val, 'val' may be any 32-bit value, 'acc' and 'num'
311 * may be any value, returns the number of digits in 'acc'.
314 if (n_digits > 0 && val > 0)
316 a_digits = uarb_mult_digit(acc, a_digits, num, n_digits,
317 (png_uint_16)(val & 0xffff));
319 /* Because n_digits and val are >0 the following must be true: */
320 assert(a_digits > 0);
322 val >>= 16;
323 if (val > 0)
324 a_digits = uarb_mult_digit(acc+1, a_digits-1, num, n_digits,
325 (png_uint_16)val) + 1;
328 return a_digits;
331 static int
332 uarb_shift(uarb inout, int ndigits, unsigned int right_shift)
333 /* Shift inout right by right_shift bits, right_shift must be in the range
334 * 1..15
337 FIX_GCC int i = ndigits;
338 png_uint_16 carry = 0;
340 assert(right_shift >= 1 && right_shift <= 15);
342 while (--i >= 0)
344 png_uint_16 temp = (png_uint_16)(carry | (inout[i] >> right_shift));
346 /* Bottom bits to top bits of carry */
347 carry = (png_uint_16)((inout[i] << (16-right_shift)) & 0xffff);
349 inout[i] = temp;
351 /* The shift may reduce ndigits */
352 if (i == ndigits-1 && temp == 0)
353 ndigits = i;
356 return ndigits;
359 static int
360 uarb_cmp(uarb a, int adigits, uarb b, int bdigits)
361 /* Return -1/0/+1 according as a<b/a==b/a>b */
363 if (adigits < bdigits)
364 return -1;
366 if (adigits > bdigits)
367 return 1;
369 while (adigits-- > 0)
370 if (a[adigits] < b[adigits])
371 return -1;
373 else if (a[adigits] > b[adigits])
374 return 1;
376 return 0;
379 #if 0 /*UNUSED*/
380 static int
381 uarb_eq32(uarb num, int digits, png_uint_32 val)
382 /* Return true if the uarb is equal to 'val' */
384 switch (digits)
386 case 0: return val == 0;
387 case 1: return val == num[0];
388 case 2: return (val & 0xffff) == num[0] && (val >> 16) == num[1];
389 default: return 0;
392 #endif
394 static void
395 uarb_printx(uarb num, int digits, FILE *out)
396 /* Print 'num' as a hexadecimal number (easier than decimal!) */
398 while (digits > 0)
399 if (num[--digits] > 0)
401 fprintf(out, "0x%x", num[digits]);
403 while (digits > 0)
404 fprintf(out, "%.4x", num[--digits]);
407 else if (digits == 0) /* the number is 0 */
408 fputs("0x0", out);
411 static void
412 uarb_print(uarb num, int digits, FILE *out)
413 /* Prints 'num' as a decimal if it will fit in an unsigned long, else as a
414 * hexadecimal number. Notice that the results vary for images over 4GByte
415 * in a system dependent way, and the hexadecimal form doesn't work very well
416 * in awk script input.
419 * TODO: write uarb_div10
422 if (digits * sizeof (udigit) > sizeof (unsigned long))
423 uarb_printx(num, digits, out);
425 else
427 unsigned long n = 0;
429 while (digits > 0)
430 n = (n << 16) + num[--digits];
432 fprintf(out, "%lu", n);
436 /* Generate random bytes. This uses a boring repeatable algorithm and it
437 * is implemented here so that it gives the same set of numbers on every
438 * architecture. It's a linear congruential generator (Knuth or Sedgewick
439 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
440 * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
441 * Generation.)
443 * (Copied from contrib/libtests/pngvalid.c)
445 static void
446 make_random_bytes(png_uint_32* seed, void* pv, size_t size)
448 png_uint_32 u0 = seed[0], u1 = seed[1];
449 png_bytep bytes = png_voidcast(png_bytep, pv);
451 /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR
452 * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
454 size_t i;
455 for (i=0; i<size; ++i)
457 /* First generate 8 new bits then shift them in at the end. */
458 png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
459 u1 <<= 8;
460 u1 |= u0 >> 24;
461 u0 <<= 8;
462 u0 |= u;
463 *bytes++ = (png_byte)u;
466 seed[0] = u0;
467 seed[1] = u1;
470 /* Clear an object to a random value. */
471 static void
472 clear(void *pv, size_t size)
474 static png_uint_32 clear_seed[2] = { 0x12345678, 0x9abcdef0 };
475 make_random_bytes(clear_seed, pv, size);
478 #define CLEAR(object) clear(&(object), sizeof (object))
480 /* Copied from unreleased 1.7 code.
482 * CRC checking uses a local pre-built implementation of the Ethernet CRC32.
483 * This is to avoid a function call to the zlib DLL and to optimize the
484 * byte-by-byte case.
486 static png_uint_32 crc_table[256] =
488 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
489 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
490 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
491 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
492 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
493 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
494 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
495 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
496 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
497 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
498 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
499 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
500 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
501 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
502 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
503 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
504 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
505 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
506 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
507 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
508 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
509 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
510 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
511 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
512 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
513 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
514 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
515 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
516 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
517 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
518 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
519 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
520 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
521 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
522 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
523 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
524 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
525 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
526 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
527 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
528 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
529 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
530 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
531 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
532 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
533 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
534 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
535 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
536 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
537 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
538 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
539 0x2d02ef8d
542 /* The CRC calculated here *IS* conditioned, the corresponding value used by
543 * zlib and the result value is obtained by XORing with CRC_INIT, which is also
544 * the first value that must be passed in (for the first byte) to crc_one_byte.
546 #define CRC_INIT 0xffffffff
548 static png_uint_32
549 crc_one_byte(png_uint_32 crc, int b)
551 return crc_table[(crc ^ b) & 0xff] ^ (crc >> 8);
554 static png_uint_32
555 crc_init_4(png_uint_32 value)
557 /* This is an alternative to the algorithm used in zlib, which requires four
558 * separate tables to parallelize the four byte operations, it only works for
559 * a CRC of the first four bytes of the stream, but this is what happens in
560 * the parser below where length+chunk-name is read and chunk-name used to
561 * initialize the CRC. Notice that the calculation here avoids repeated
562 * conditioning (xor with 0xffffffff) by storing the conditioned value.
564 png_uint_32 crc = crc_table[(~value >> 24)] ^ 0xffffff;
566 crc = crc_table[(crc ^ (value >> 16)) & 0xff] ^ (crc >> 8);
567 crc = crc_table[(crc ^ (value >> 8)) & 0xff] ^ (crc >> 8);
568 return crc_table[(crc ^ value) & 0xff] ^ (crc >> 8);
571 static int
572 chunk_type_valid(png_uint_32 c)
573 /* Bit whacking approach to chunk name validation that is intended to avoid
574 * branches. The cost is that it uses a lot of 32-bit constants, which might
575 * be bad on some architectures.
578 png_uint_32 t;
580 /* Remove bit 5 from all but the reserved byte; this means every
581 * 8-bit unit must be in the range 65-90 to be valid. So bit 5
582 * must be zero, bit 6 must be set and bit 7 zero.
584 c &= ~PNG_U32(32,32,0,32);
585 t = (c & ~0x1f1f1f1f) ^ 0x40404040;
587 /* Subtract 65 for each 8 bit quantity, this must not overflow
588 * and each byte must then be in the range 0-25.
590 c -= PNG_U32(65,65,65,65);
591 t |=c ;
593 /* Subtract 26, handling the overflow which should set the top
594 * three bits of each byte.
596 c -= PNG_U32(25,25,25,26);
597 t |= ~c;
599 return (t & 0xe0e0e0e0) == 0;
602 /**************************** CONTROL INFORMATION *****************************/
604 /* Information about a sequence of IDAT chunks, the chunks have been re-synced
605 * using sync_stream below and the new lengths are recorded here. Because the
606 * number of chunks is unlimited this is handled using a linked list of these
607 * structures.
609 struct IDAT_list
611 struct IDAT_list *next; /* Linked list */
612 unsigned int length; /* Actual length of the array below */
613 unsigned int count; /* Number of entries that are valid */
614 # define IDAT_INIT_LENGTH 16
615 png_uint_32 lengths[IDAT_INIT_LENGTH];
618 static void
619 IDAT_list_init(struct IDAT_list *list)
621 CLEAR(*list);
623 list->next = NULL;
624 list->length = IDAT_INIT_LENGTH;
627 static size_t
628 IDAT_list_size(struct IDAT_list *list, unsigned int length)
629 /* Return the size in bytes of an IDAT_list of the given length. */
631 if (list != NULL)
632 length = list->length;
634 return sizeof *list - sizeof list->lengths +
635 length * sizeof list->lengths[0];
638 static void
639 IDAT_list_end(struct IDAT_list *IDAT_list)
641 struct IDAT_list *list = IDAT_list->next;
643 CLEAR(*IDAT_list);
645 while (list != NULL)
647 struct IDAT_list *next = list->next;
649 clear(list, IDAT_list_size(list, 0));
650 free(list);
651 list = next;
655 static struct IDAT_list *
656 IDAT_list_extend(struct IDAT_list *tail)
658 /* Use the previous cached value if available. */
659 struct IDAT_list *next = tail->next;
661 if (next == NULL)
663 /* Insert a new, malloc'ed, block of IDAT information buffers, this
664 * one twice as large as the previous one:
666 unsigned int length = 2 * tail->length;
668 if (length < tail->length) /* arithmetic overflow */
669 length = tail->length;
671 next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length)));
672 CLEAR(*next);
674 /* The caller must handle this: */
675 if (next == NULL)
676 return NULL;
678 next->next = NULL;
679 next->length = length;
680 tail->next = next;
683 return next;
686 /* GLOBAL CONTROL STRUCTURE */
687 struct global
689 /* PUBLIC GLOBAL VARIABLES: OWNER INITIALIZE */
690 unsigned int errors :1; /* print file errors to stderr */
691 unsigned int warnings :1; /* print libpng warnings to stderr */
692 unsigned int optimize_zlib :1; /* Run optimization search */
693 unsigned int quiet :2; /* don't output summaries */
694 unsigned int verbose :3; /* various internal tracking */
695 unsigned int skip :3; /* Non-critical chunks to skip */
696 # define SKIP_NONE 0
697 # define SKIP_BAD_CRC 1 /* Chunks with a bad CRC */
698 # define SKIP_UNSAFE 2 /* Chunks not safe to copy */
699 # define SKIP_UNUSED 3 /* Chunks not used by libpng */
700 # define SKIP_TRANSFORM 4 /* Chunks only used in transforms */
701 # define SKIP_COLOR 5 /* Everything but tRNS, sBIT, gAMA and sRGB */
702 # define SKIP_ALL 6 /* Everything but tRNS and sBIT */
704 png_uint_32 idat_max; /* 0 to perform no re-chunking */
706 int status_code; /* Accumulated status code */
707 # define TOO_FAR_BACK 0x01 /* found a too-far-back error */
708 # define CRC_ERROR 0x02 /* fixed an invalid CRC */
709 # define STREAM_ERROR 0x04 /* damaged PNG stream (may be fixable) */
710 # define TRUNCATED 0x08 /* truncated but still readable */
711 # define FILE_ERROR 0x10 /* could not read the file */
712 # define WRITE_ERROR 0x20 /* write error (this terminates the read) */
713 # define INTERNAL_ERROR 0x40 /* internal limits/errors encountered */
715 /* PUBLIC GLOBAL VARIABLES: USED INTERNALLY BY IDAT READ CODE */
716 struct IDAT_list idat_cache; /* Cache of file IDAT information buffers */
717 /* The structure is shared across all uses of this global control
718 * structure to avoid reallocation between IDAT streams.
722 static int
723 global_end(struct global *global)
726 int rc;
728 IDAT_list_end(&global->idat_cache);
729 rc = global->status_code;
730 CLEAR(*global);
731 return rc;
734 static void
735 global_init(struct global *global)
736 /* Call this once (and only once) to initialize the control */
738 CLEAR(*global);
740 /* Globals */
741 global->errors = 0;
742 global->warnings = 0;
743 global->quiet = 0;
744 global->verbose = 0;
745 global->idat_max = 0; /* no re-chunking of IDAT */
746 global->optimize_zlib = 0;
747 global->skip = SKIP_NONE;
748 global->status_code = 0;
750 IDAT_list_init(&global->idat_cache);
753 static int
754 skip_chunk_type(const struct global *global, png_uint_32 type)
755 /* Return true if this chunk is to be skipped according to the --strip
756 * option. This code needs to recognize all known ancillary chunks in order
757 * to handle the --strip=unsafe option.
760 /* Never strip critical chunks: */
761 if (CRITICAL(type))
762 return 0;
764 switch (type)
766 /* Chunks that are treated as, effectively, critical because they affect
767 * correct interpretation of the pixel values:
769 case png_tRNS: case png_sBIT:
770 return 0;
772 /* Chunks that specify gamma encoding which should therefore only be
773 * removed the the user insists:
775 case png_gAMA: case png_sRGB:
776 if (global->skip >= SKIP_ALL)
777 return 1;
778 return 0;
780 /* Chunks that affect color interpretation - not used by libpng and rarely
781 * used by applications, but technically still required for correct
782 * interpretation of the image data:
784 case png_cHRM: case png_iCCP:
785 if (global->skip >= SKIP_COLOR)
786 return 1;
787 return 0;
789 /* Other chunks that are used by libpng in image transformations (as
790 * opposed to known chunks that have get/set APIs but are not otherwise
791 * used.)
793 case png_bKGD:
794 if (global->skip >= SKIP_TRANSFORM)
795 return 1;
796 return 0;
798 /* All other chunks that libpng knows about and affect neither image
799 * interpretation nor libpng transforms - chunks that are effectively
800 * unused by libpng even though libpng might recognize and store them.
802 case png_fRAc: case png_gIFg: case png_gIFt: case png_gIFx: case png_hIST:
803 case png_iTXt: case png_oFFs: case png_pCAL: case png_pHYs: case png_sCAL:
804 case png_sPLT: case png_sTER: case png_tEXt: case png_tIME: case png_zTXt:
805 if (global->skip >= SKIP_UNUSED)
806 return 1;
807 return 0;
809 /* Chunks that libpng does not know about (notice that this depends on the
810 * list above including all known chunks!) The decision here depends on
811 * whether the safe-to-copy bit is set in the chunk type.
813 default:
814 if (SAFE_TO_COPY(type))
816 if (global->skip >= SKIP_UNUSED) /* as above */
817 return 1;
820 else if (global->skip >= SKIP_UNSAFE)
821 return 1;
823 return 0;
827 /* PER-FILE CONTROL STRUCTURE */
828 struct chunk;
829 struct IDAT;
830 struct file
832 /* ANCESTORS */
833 struct global *global;
835 /* PUBLIC PER-FILE VARIABLES: CALLER INITIALIZE */
836 const char * file_name;
837 const char * out_name; /* Name of output file (if required) */
839 /* PUBLIC PER-FILE VARIABLES: SET BY PNG READ CODE */
840 /* File specific result codes */
841 int status_code; /* Set to a bit mask of the following: */
842 int read_errno; /* Records a read error errno */
843 int write_errno; /* Records a write error errno */
845 /* IHDR information */
846 png_uint_32 width;
847 png_uint_32 height;
848 png_byte bit_depth;
849 png_byte color_type;
850 png_byte compression_method;
851 png_byte filter_method;
852 png_byte interlace_method;
854 udigit image_bytes[5];
855 int image_digits;
857 /* PROTECTED PER-FILE VARIABLES: USED BY THE READ CODE */
858 FILE * file; /* Original PNG file */
859 FILE * out; /* If a new one is being written */
860 jmp_buf jmpbuf; /* Set while reading a PNG */
862 /* PROTECTED CHUNK SPECIFIC VARIABLES: USED BY CHUNK CODE */
863 /* The following variables are used during reading to record the length, type
864 * and data position of the *next* chunk or, right at the start, the
865 * signature (in length,type).
867 * When a chunk control structure is instantiated these values are copied
868 * into the structure and can then be overritten with the data for the next
869 * chunk.
871 fpos_t data_pos; /* Position of first byte of chunk data */
872 png_uint_32 length; /* First word (length or signature start) */
873 png_uint_32 type; /* Second word (type or signature end) */
874 png_uint_32 crc; /* Running chunk CRC (used by read_chunk) */
876 /* These counts are maintained by the read and write routines below and are
877 * reset by the chunk handling code. They record the total number of bytes
878 * read or written for the chunk, including the header (length,type) bytes.
880 png_uint_32 read_count; /* Count of bytes read (in the chunk) */
881 png_uint_32 write_count; /* Count of bytes written (in the chunk) */
882 int state; /* As defined here: */
883 # define STATE_SIGNATURE 0 /* The signature is being written */
884 # define STATE_CHUNKS 1 /* Non-IDAT chunks are being written */
885 # define STATE_IDAT 2 /* An IDAT stream is being written */
887 /* Two pointers used to enable clean-up in the event of fatal errors and to
888 * hold state about the parser process (only one of each at present.)
890 struct chunk * chunk;
891 struct IDAT * idat;
893 /* Interface to allocate a new chunk or IDAT control structure. The result
894 * is returned by setting one or other of the above variables. Note that the
895 * relevant initializer is called by the allocator function. The alloc_ptr
896 * is used only by the implementation of the allocate function.
898 void * alloc_ptr;
899 void (*alloc)(struct file*,int idat);
900 /* idat: allocate IDAT not chunk */
903 /* Valid longjmp (stop) codes are: */
904 #define LIBPNG_WARNING_CODE 1 /* generic png_error */
905 #define LIBPNG_ERROR_CODE 2 /* generic png_error */
906 #define ZLIB_ERROR_CODE 3 /* generic zlib error */
907 #define INVALID_ERROR_CODE 4 /* detected an invalid PNG */
908 #define READ_ERROR_CODE 5 /* read failed */
909 #define WRITE_ERROR_CODE 6 /* error in write */
910 #define UNEXPECTED_ERROR_CODE 7 /* unexpected (internal?) error */
912 static void
913 emit_string(const char *str, FILE *out)
914 /* Print a string with spaces replaced by '_' and non-printing characters by
915 * an octal escape.
918 for (; *str; ++str)
919 if (isgraph(UCHAR_MAX & *str))
920 putc(*str, out);
922 else if (isspace(UCHAR_MAX & *str))
923 putc('_', out);
925 else
926 fprintf(out, "\\%.3o", *str);
929 static const char *
930 strcode(int code)
932 switch (code)
934 case LIBPNG_WARNING_CODE: return "warning";
935 case LIBPNG_ERROR_CODE: return "libpng";
936 case ZLIB_ERROR_CODE: return "zlib";
937 case INVALID_ERROR_CODE: return "invalid";
938 case READ_ERROR_CODE: return "read";
939 case WRITE_ERROR_CODE: return "write";
940 case UNEXPECTED_ERROR_CODE: return "unexpected";
941 default: return "INVALID";
945 static void
946 emit_error(struct file *file, int code, const char *what)
947 /* Generic error message routine, takes a 'stop' code but can be used
948 * elsewhere. Always outputs a message.
951 const char *reason;
952 int err = 0;
954 switch (code)
956 case LIBPNG_WARNING_CODE: reason = "libpng warning:"; break;
957 case LIBPNG_ERROR_CODE: reason = "libpng error:"; break;
958 case ZLIB_ERROR_CODE: reason = "zlib error:"; break;
959 case INVALID_ERROR_CODE: reason = "invalid"; break;
960 case READ_ERROR_CODE: reason = "read failure:";
961 err = file->read_errno;
962 break;
963 case WRITE_ERROR_CODE: reason = "write error";
964 err = file->write_errno;
965 break;
966 case UNEXPECTED_ERROR_CODE: reason = "unexpected error:";
967 err = file->read_errno;
968 if (err == 0)
969 err = file->write_errno;
970 break;
971 default: reason = "INVALID (internal error):"; break;
974 if (err != 0)
975 fprintf(stderr, "%s: %s %s [%s]\n", file->file_name, reason, what,
976 strerror(err));
978 else
979 fprintf(stderr, "%s: %s %s\n", file->file_name, reason, what);
982 static void chunk_end(struct chunk **);
983 static void IDAT_end(struct IDAT **);
985 static int
986 file_end(struct file *file)
988 int rc;
990 /* If either of the chunk pointers are set end them here, the IDAT structure
991 * must be deallocated first as it may deallocate the chunk structure.
993 if (file->idat != NULL)
994 IDAT_end(&file->idat);
996 if (file->chunk != NULL)
997 chunk_end(&file->chunk);
999 rc = file->status_code;
1001 if (file->file != NULL)
1002 (void)fclose(file->file);
1004 if (file->out != NULL)
1006 /* NOTE: this is bitwise |, all the following functions must execute and
1007 * must succeed.
1009 if (ferror(file->out) | fflush(file->out) | fclose(file->out))
1011 perror(file->out_name);
1012 emit_error(file, READ_ERROR_CODE, "output write error");
1013 rc |= WRITE_ERROR;
1017 /* Accumulate the result codes */
1018 file->global->status_code |= rc;
1020 CLEAR(*file);
1022 return rc; /* status code: non-zero on read or write error */
1025 static int
1026 file_init(struct file *file, struct global *global, const char *file_name,
1027 const char *out_name, void *alloc_ptr, void (*alloc)(struct file*,int))
1028 /* Initialize a file control structure. This will open the given files as
1029 * well. The status code returned is 0 on success, non zero (using the flags
1030 * above) on a file open error.
1033 CLEAR(*file);
1034 file->global = global;
1036 file->file_name = file_name;
1037 file->out_name = out_name;
1038 file->status_code = 0;
1039 file->read_errno = 0;
1040 file->write_errno = 0;
1042 file->file = NULL;
1043 file->out = NULL;
1044 /* jmpbuf is garbage: must be set by read_png */
1046 file->read_count = 0;
1047 file->state = STATE_SIGNATURE;
1049 file->chunk = NULL;
1050 file->idat = NULL;
1052 file->alloc_ptr = alloc_ptr;
1053 file->alloc = alloc;
1055 /* Open the files: */
1056 assert(file_name != NULL);
1057 file->file = fopen(file_name, "rb");
1059 if (file->file == NULL)
1061 file->read_errno = errno;
1062 file->status_code |= FILE_ERROR;
1063 /* Always output: please give a readable file! */
1064 perror(file_name);
1065 return FILE_ERROR;
1068 if (out_name != NULL)
1070 file->out = fopen(out_name, "wb");
1072 if (file->out == NULL)
1074 file->write_errno = errno;
1075 file->status_code |= WRITE_ERROR;
1076 perror(out_name);
1077 return WRITE_ERROR;
1081 return 0;
1084 static void
1085 log_error(struct file *file, int code, const char *what)
1086 /* Like emit_error but checks the global 'errors' flag */
1088 if (file->global->errors)
1089 emit_error(file, code, what);
1092 static char
1093 type_char(png_uint_32 v)
1095 /* In fact because chunk::chunk_type is validated prior to any call to this
1096 * function it will always return a-zA-Z, but the extra codes are just there
1097 * to help in finding internal (programming) errors. Note that the code only
1098 * ever considers the low 7 bits of the value (so it is not necessary for the
1099 * type_name function to mask of the byte.)
1101 if (v & 32)
1102 return "!abcdefghijklmnopqrstuvwxyz56789"[(v-96)&31];
1104 else
1105 return "@ABCDEFGHIJKLMNOPQRSTUVWXYZ01234"[(v-64)&31];
1108 static void
1109 type_name(png_uint_32 type, FILE *out)
1111 putc(type_char(type >> 24), out);
1112 putc(type_char(type >> 16), out);
1113 putc(type_char(type >> 8), out);
1114 putc(type_char(type ), out);
1117 static void
1118 type_sep(FILE *out)
1120 putc(':', out);
1121 putc(' ', out);
1124 static png_uint_32 current_type(struct file *file, int code);
1126 PNG_NORETURN static void
1127 stop(struct file *file, int code, const char *what)
1128 /* Return control when a PNG file cannot be read. This outputs an 'ERR'
1129 * summary line too.
1132 log_error(file, code, what);
1134 /* The chunk being read is typically identified by file->chunk or, if this is
1135 * NULL, by file->type. This may be wrong if libpng reads ahead, but this
1136 * only happens with IDAT where libpng reads the header then jumps around
1137 * finding errors in the previous chunks. We know that is happening because
1138 * we are at the start of the IDAT (i.e. no IDAT data has yet been written.)
1140 * SUMMARY FORMAT (stop):
1142 * IDAT ERR status code read-errno write-errno message file
1144 * 'uncompressed' will be 0 if there was a problem in the IHDR. The errno
1145 * values are emit_string(strerror(errno)).
1147 if (file->global->quiet < 2) /* need two quiets to stop this. */
1149 png_uint_32 type;
1151 if (file->chunk != NULL)
1152 type = current_type(file, code); /* Gropes in struct chunk and IDAT */
1154 else
1155 type = file->type;
1157 if (type)
1158 type_name(type, stdout);
1160 else /* magic: an IDAT header, produces bogons for too many IDATs */
1161 fputs("HEAD", stdout); /* not a registered chunk! */
1163 printf(" ERR %.2x %s ", file->status_code, strcode(code));
1164 /* This only works one strerror at a time, because of the way strerror is
1165 * implemented.
1167 emit_string(strerror(file->read_errno), stdout);
1168 putc(' ', stdout);
1169 emit_string(strerror(file->write_errno), stdout);
1170 putc(' ', stdout);
1171 emit_string(what, stdout);
1172 putc(' ', stdout);
1173 fputs(file->file_name, stdout);
1174 putc('\n', stdout);
1177 file->status_code |= FILE_ERROR;
1178 longjmp(file->jmpbuf, code);
1181 PNG_NORETURN static void
1182 stop_invalid(struct file *file, const char *what)
1184 stop(file, INVALID_ERROR_CODE, what);
1187 static void
1188 type_message(struct file *file, png_uint_32 type, const char *what)
1189 /* Error message for a chunk; the chunk name comes from 'type' */
1191 if (file->global->errors)
1193 fputs(file->file_name, stderr);
1194 type_sep(stderr);
1195 type_name(type, stderr);
1196 type_sep(stderr);
1197 fputs(what, stderr);
1198 putc('\n', stderr);
1202 /* Input file positioning - we jump around in the input file while reading
1203 * stuff, these wrappers deal with the error handling.
1205 static void
1206 file_getpos(struct file *file, fpos_t *pos)
1208 if (fgetpos(file->file, pos))
1210 /* This is unexpected, so perror it */
1211 perror(file->file_name);
1212 stop(file, READ_ERROR_CODE, "fgetpos");
1216 static void
1217 file_setpos(struct file *file, const fpos_t *pos)
1219 if (fsetpos(file->file, pos))
1221 perror(file->file_name);
1222 stop(file, READ_ERROR_CODE, "fsetpos");
1226 static void
1227 getpos(struct file *file)
1228 /* Get the current position and store it in 'data_pos'. The corresponding
1229 * setpos() function is chunk specific because it uses the copy of the
1230 * position for the specific chunk.
1233 file_getpos(file, &file->data_pos);
1237 /* Read utility - read a single byte, returns a value in the range 0..255 or EOF
1238 * on a read error. In the latter case status_code and read_errno are updated
1239 * appropriately.
1241 static int
1242 read_byte(struct file *file)
1244 int ch = getc(file->file);
1246 if (ch >= 0 && ch <= 255)
1248 ++(file->read_count);
1249 return ch;
1252 else if (ch != EOF)
1254 file->status_code |= INTERNAL_ERROR;
1255 file->read_errno = ERANGE; /* out of range character */
1257 /* This is very unexpected; an error message is always output: */
1258 emit_error(file, UNEXPECTED_ERROR_CODE, "file read");
1261 # ifdef EINTR
1262 else if (errno == EINTR) /* Interrupted, try again */
1264 errno = 0;
1265 return read_byte(file);
1267 # endif
1269 else
1271 /* An error, it doesn't really matter what the error is but it gets
1272 * recorded anyway.
1274 if (ferror(file->file))
1275 file->read_errno = errno;
1277 else if (feof(file->file))
1278 file->read_errno = 0; /* I.e. a regular EOF, no error */
1280 else /* unexpected */
1281 file->read_errno = EDOM;
1284 /* 'TRUNCATED' is used for all cases of failure to read a byte, because of
1285 * the way libpng works a byte read is never attempted unless the byte is
1286 * expected to be there, so EOF should not occur.
1288 file->status_code |= TRUNCATED;
1289 return EOF;
1292 static png_byte
1293 reread_byte(struct file *file)
1294 /* Read a byte when an error is not expected to happen because the byte has
1295 * been read before without error.
1298 int ch = getc(file->file);
1300 if (errno != 0)
1301 file->read_errno = errno;
1303 if (ch < 0 || ch > 255)
1304 stop(file, UNEXPECTED_ERROR_CODE, "reread");
1306 return (png_byte)ch;
1309 static png_uint_32
1310 reread_4(struct file *file)
1311 /* The same but for a four byte quantity */
1313 png_uint_32 result = 0;
1314 int i = 0;
1316 while (++i <= 4)
1317 result = (result << 8) + reread_byte(file);
1319 return result;
1322 static void
1323 skip_12(struct file *file)
1324 /* Skip exactly 12 bytes in the input stream - used to skip a CRC and chunk
1325 * header that has been read before.
1328 /* Since the chunks were read before this shouldn't fail: */
1329 if (fseek(file->file, 12, SEEK_CUR) != 0)
1331 if (errno != 0)
1332 file->read_errno = errno;
1334 stop(file, UNEXPECTED_ERROR_CODE, "reskip");
1338 static void
1339 write_byte(struct file *file, int b)
1340 /* Write one byte to the output - this causes a fatal error if the write
1341 * fails and the read of this PNG file immediately terminates. Just
1342 * increments the write count if there is no output file.
1345 if (file->out != NULL)
1347 if (putc(b, file->out) != b)
1349 file->write_errno = errno;
1350 file->status_code |= WRITE_ERROR;
1351 stop(file, WRITE_ERROR_CODE, "write byte");
1355 ++(file->write_count);
1358 /* Derivatives of the read/write functions. */
1359 static unsigned int
1360 read_4(struct file *file, png_uint_32 *pu)
1361 /* Read four bytes, returns the number of bytes read successfully and, if all
1362 * four bytes are read, assigns the result to *pu.
1365 unsigned int i = 0;
1366 png_uint_32 val = 0;
1370 int ch = read_byte(file);
1372 if (ch == EOF)
1373 return i;
1375 val = (val << 8) + ch;
1376 } while (++i < 4);
1378 *pu = val;
1379 return i;
1382 /* CRC handling - read but calculate the CRC while doing so. */
1383 static int
1384 crc_read_many(struct file *file, png_uint_32 length)
1385 /* Reads 'length' bytes and updates the CRC, returns true on success, false
1386 * if the input is truncated.
1389 if (length > 0)
1391 png_uint_32 crc = file->crc;
1395 int ch = read_byte(file);
1397 if (ch == EOF)
1398 return 0; /* Truncated */
1400 crc = crc_one_byte(crc, ch);
1402 while (--length > 0);
1404 file->crc = crc;
1407 return 1; /* OK */
1410 static int
1411 calc_image_size(struct file *file)
1412 /* Fill in the image_bytes field given the IHDR information, calls stop on
1413 * error.
1416 png_uint_16 pd = file->bit_depth;
1418 switch (file->color_type)
1420 default:
1421 stop_invalid(file, "IHDR: colour type");
1423 invalid_bit_depth:
1424 stop_invalid(file, "IHDR: bit depth");
1426 case 0: /* g */
1427 if (pd != 1 && pd != 2 && pd != 4 && pd != 8 && pd != 16)
1428 goto invalid_bit_depth;
1429 break;
1431 case 3:
1432 if (pd != 1 && pd != 2 && pd != 4 && pd != 8)
1433 goto invalid_bit_depth;
1434 break;
1436 case 2: /* rgb */
1437 if (pd != 8 && pd != 16)
1438 goto invalid_bit_depth;
1440 pd = (png_uint_16)(pd * 3);
1441 break;
1443 case 4: /* ga */
1444 if (pd != 8 && pd != 16)
1445 goto invalid_bit_depth;
1447 pd = (png_uint_16)(pd * 2);
1448 break;
1450 case 6: /* rgba */
1451 if (pd != 8 && pd != 16)
1452 goto invalid_bit_depth;
1454 pd = (png_uint_16)(pd * 4);
1455 break;
1458 if (file->width < 1 || file->width > 0x7fffffff)
1459 stop_invalid(file, "IHDR: width");
1461 else if (file->height < 1 || file->height > 0x7fffffff)
1462 stop_invalid(file, "IHDR: height");
1464 else if (file->compression_method != 0)
1465 stop_invalid(file, "IHDR: compression method");
1467 else if (file->filter_method != 0)
1468 stop_invalid(file, "IHDR: filter method");
1470 else switch (file->interlace_method)
1472 case PNG_INTERLACE_ADAM7:
1473 /* Interlacing makes the image larger because of the replication of
1474 * both the filter byte and the padding to a byte boundary.
1477 int pass;
1478 int image_digits = 0;
1479 udigit row_width[2], row_bytes[3];
1481 for (pass=0; pass<=6; ++pass)
1483 png_uint_32 pw = PNG_PASS_COLS(file->width, pass);
1485 if (pw > 0)
1487 int digits;
1489 /* calculate 1+((pw*pd+7)>>3) in row_bytes */
1490 digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1491 row_width, uarb_set(row_width, pw), pd);
1492 digits = uarb_shift(row_bytes, digits, 3);
1493 digits = uarb_inc(row_bytes, digits, 1);
1495 /* Add row_bytes * pass-height to the file image_bytes field
1497 image_digits = uarb_mult32(file->image_bytes, image_digits,
1498 row_bytes, digits,
1499 PNG_PASS_ROWS(file->height, pass));
1503 file->image_digits = image_digits;
1505 break;
1507 case PNG_INTERLACE_NONE:
1509 int digits;
1510 udigit row_width[2], row_bytes[3];
1512 /* As above, but use image_width in place of the pass width: */
1513 digits = uarb_mult_digit(row_bytes, uarb_set(row_bytes, 7),
1514 row_width, uarb_set(row_width, file->width), pd);
1515 digits = uarb_shift(row_bytes, digits, 3);
1516 digits = uarb_inc(row_bytes, digits, 1);
1518 /* Set row_bytes * image-height to the file image_bytes field */
1519 file->image_digits = uarb_mult32(file->image_bytes, 0,
1520 row_bytes, digits, file->height);
1522 break;
1524 default:
1525 stop_invalid(file, "IHDR: interlace method");
1528 assert(file->image_digits >= 1 && file->image_digits <= 5);
1529 return 1;
1532 /* PER-CHUNK CONTROL STRUCTURE
1533 * This structure is instantiated for each chunk, except for the IDAT chunks
1534 * where one chunk control structure is used for the whole of a single stream of
1535 * IDAT chunks (see the IDAT control structure below).
1537 struct chunk
1539 /* ANCESTORS */
1540 struct file * file;
1541 struct global * global;
1543 /* PUBLIC IDAT INFORMATION: SET BY THE ZLIB CODE */
1544 udigit uncompressed_bytes[5];
1545 int uncompressed_digits;
1546 udigit compressed_bytes[5];
1547 int compressed_digits;
1549 /* PUBLIC PER-CHUNK INFORMATION: USED BY CHUNK READ CODE */
1550 /* This information is filled in by chunk_init from the data in the file
1551 * control structure, but chunk_length may be changed later.
1553 fpos_t chunk_data_pos; /* Position of first byte of chunk data */
1554 png_uint_32 chunk_length; /* From header (or modified below) */
1555 png_uint_32 chunk_type; /* From header */
1557 /* PUBLIC PER-CHUNK INFORMATION: FOR THE CHUNK WRITE CODE */
1558 png_uint_32 write_crc; /* Output CRC (may differ from read_crc) */
1559 png_uint_32 rewrite_offset; /* Count of bytes before rewrite. */
1560 int rewrite_length; /* Number of bytes left to change */
1561 png_byte rewrite_buffer[2]; /* Buffer of new byte values */
1564 static void
1565 chunk_message(struct chunk *chunk, const char *message)
1567 type_message(chunk->file, chunk->chunk_type, message);
1570 static void
1571 chunk_end(struct chunk **chunk_var)
1573 struct chunk *chunk = *chunk_var;
1575 *chunk_var = NULL;
1576 CLEAR(*chunk);
1579 static void
1580 chunk_init(struct chunk * const chunk, struct file * const file)
1581 /* When a chunk is initialized the file length/type/pos are copied into the
1582 * corresponding chunk fields and the new chunk is registered in the file
1583 * structure. There can only be one chunk at a time.
1585 * NOTE: this routine must onely be called from the file alloc routine!
1588 assert(file->chunk == NULL);
1590 CLEAR(*chunk);
1592 chunk->file = file;
1593 chunk->global = file->global;
1595 chunk->chunk_data_pos = file->data_pos;
1596 chunk->chunk_length = file->length;
1597 chunk->chunk_type = file->type;
1599 /* Compresssed/uncompressed size information (from the zlib control structure
1600 * that is used to check the compressed data in a chunk.)
1602 chunk->uncompressed_digits = 0;
1603 chunk->compressed_digits = 0;
1605 file->chunk = chunk;
1608 static png_uint_32
1609 current_type(struct file *file, int code)
1610 /* Guess the actual chunk type that causes a stop() */
1612 /* This may return png_IDAT for errors detected (late) in the header; that
1613 * includes any inter-chunk consistency check that libpng performs. Assume
1614 * that if the chunk_type is png_IDAT and the file write count is 8 this is
1615 * what is happening.
1617 if (file->chunk != NULL)
1619 png_uint_32 type = file->chunk->chunk_type;
1621 /* This is probably wrong for the excess IDATs case, because then libpng
1622 * whines about too many of them (apparently in some cases erroneously)
1623 * when the header is read.
1625 if (code <= LIBPNG_ERROR_CODE && type == png_IDAT &&
1626 file->write_count == 8)
1627 type = 0; /* magic */
1629 return type;
1632 else
1633 return file->type;
1636 static void
1637 setpos(struct chunk *chunk)
1638 /* Reset the position to 'chunk_data_pos' - the start of the data for this
1639 * chunk. As a side effect the read_count in the file is reset to 8, just
1640 * after the length/type header.
1643 chunk->file->read_count = 8;
1644 file_setpos(chunk->file, &chunk->chunk_data_pos);
1647 /* Specific chunk handling - called for each chunk header, all special chunk
1648 * processing is initiated in these functions.
1650 /* The next functions handle special processing for those chunks with LZ data,
1651 * the data is identified and checked for validity. If there are problems which
1652 * cannot be corrected the routines return false, otherwise true (although
1653 * modification to the zlib header may be required.)
1655 * The compressed data is in zlib format (RFC1950) and consequently has a
1656 * minimum length of 7 bytes.
1658 static int zlib_check(struct file *file, png_uint_32 offset);
1660 static int
1661 process_zTXt_iCCP(struct file *file)
1662 /* zTXt and iCCP have exactly the same form - keyword, null, compression
1663 * method then compressed data.
1666 struct chunk *chunk = file->chunk;
1667 png_uint_32 length;
1668 png_uint_32 index = 0;
1670 assert(chunk != NULL && file->idat == NULL);
1671 length = chunk->chunk_length;
1672 setpos(chunk);
1674 while (length >= 9)
1676 --length;
1677 ++index;
1678 if (reread_byte(file) == 0) /* keyword null terminator */
1680 --length;
1681 ++index;
1682 (void)reread_byte(file); /* compression method */
1683 return zlib_check(file, index);
1687 chunk_message(chunk, "too short");
1688 return 0; /* skip */
1691 static int
1692 process_iTXt(struct file *file)
1694 /* Like zTXt but more fields. */
1695 struct chunk *chunk = file->chunk;
1696 png_uint_32 length;
1697 png_uint_32 index = 0;
1699 assert(chunk != NULL && file->idat == NULL);
1700 length = chunk->chunk_length;
1701 setpos(chunk);
1703 while (length >= 5)
1705 --length;
1706 ++index;
1707 if (reread_byte(file) == 0) /* keyword null terminator */
1709 --length;
1710 ++index;
1711 if (reread_byte(file) == 0) /* uncompressed text */
1712 return 1; /* nothing to check */
1714 --length;
1715 ++index;
1716 (void)reread_byte(file); /* compression method */
1718 /* Skip the language tag (null terminated). */
1719 while (length >= 9)
1721 --length;
1722 ++index;
1723 if (reread_byte(file) == 0) /* terminator */
1725 /* Skip the translated keyword */
1726 while (length >= 8)
1728 --length;
1729 ++index;
1730 if (reread_byte(file) == 0) /* terminator */
1731 return zlib_check(file, index);
1736 /* Ran out of bytes in the compressed case. */
1737 break;
1741 log_error(file, INVALID_ERROR_CODE, "iTXt chunk length");
1743 return 0; /* skip */
1746 /* IDAT READ/WRITE CONTROL STRUCTURE */
1747 struct IDAT
1749 /* ANCESTORS */
1750 struct file * file;
1751 struct global * global;
1753 /* PROTECTED IDAT INFORMATION: SET BY THE IDAT READ CODE */
1754 struct IDAT_list *idat_list_head; /* START of the list of IDAT information */
1755 struct IDAT_list *idat_list_tail; /* *END* of the list of IDAT information */
1757 /* PROTECTED IDAT INFORMATION: USED BY THE IDAT WRITE CODE */
1758 struct IDAT_list *idat_cur; /* Current list entry */
1759 unsigned int idat_count; /* And the *current* index into the list */
1760 png_uint_32 idat_index; /* Index of *next* input byte to write */
1761 png_uint_32 idat_length; /* Cache of current chunk length */
1764 /* NOTE: there is currently no IDAT_reset, so a stream cannot contain more than
1765 * one IDAT sequence (i.e. MNG is not supported).
1768 static void
1769 IDAT_end(struct IDAT **idat_var)
1771 struct IDAT *idat = *idat_var;
1772 struct file *file = idat->file;
1774 *idat_var = NULL;
1776 CLEAR(*idat);
1778 assert(file->chunk != NULL);
1779 chunk_end(&file->chunk);
1781 /* Regardless of why the IDAT was killed set the state back to CHUNKS (it may
1782 * already be CHUNKS because the state isn't changed until process_IDAT
1783 * returns; a stop will cause IDAT_end to be entered in state CHUNKS!)
1785 file->state = STATE_CHUNKS;
1788 static void
1789 IDAT_init(struct IDAT * const idat, struct file * const file)
1790 /* When the chunk is png_IDAT instantiate an IDAT control structure in place
1791 * of a chunk control structure. The IDAT will instantiate a chunk control
1792 * structure using the file alloc routine.
1794 * NOTE: this routine must only be called from the file alloc routine!
1797 assert(file->chunk == NULL);
1798 assert(file->idat == NULL);
1800 CLEAR(*idat);
1802 idat->file = file;
1803 idat->global = file->global;
1805 /* Initialize the tail to the pre-allocated buffer and set the count to 0
1806 * (empty.)
1808 idat->global->idat_cache.count = 0;
1809 idat->idat_list_head = idat->idat_list_tail = &idat->global->idat_cache;
1811 /* Now the chunk. The allocator calls the initializer of the new chunk and
1812 * stores the result in file->chunk:
1814 file->alloc(file, 0/*chunk*/);
1815 assert(file->chunk != NULL);
1817 /* And store this for cleanup (and to check for double alloc or failure to
1818 * free.)
1820 file->idat = idat;
1823 static png_uint_32
1824 rechunk_length(struct IDAT *idat)
1825 /* Return the length for the next IDAT chunk, taking into account
1826 * rechunking.
1829 png_uint_32 len = idat->global->idat_max;
1831 if (len == 0) /* use original chunk lengths */
1833 const struct IDAT_list *cur;
1834 unsigned int count;
1836 if (idat->idat_index == 0) /* at the new chunk (first time) */
1837 return idat->idat_length; /* use the cache */
1839 /* Otherwise rechunk_length is called at the end of a chunk for the length
1840 * of the next one.
1842 cur = idat->idat_cur;
1843 count = idat->idat_count;
1845 assert(idat->idat_index == idat->idat_length &&
1846 idat->idat_length == cur->lengths[count]);
1848 /* Return length of the *next* chunk */
1849 if (++count < cur->count)
1850 return cur->lengths[count];
1852 /* End of this list */
1853 assert(cur != idat->idat_list_tail);
1854 cur = cur->next;
1855 assert(cur != NULL && cur->count > 0);
1856 return cur->lengths[0];
1859 else /* rechunking */
1861 /* The chunk size is the lesser of file->idat_max and the number
1862 * of remaining bytes.
1864 png_uint_32 have = idat->idat_length - idat->idat_index;
1866 if (len > have)
1868 struct IDAT_list *cur = idat->idat_cur;
1869 unsigned int j = idat->idat_count+1; /* the next IDAT in the list */
1873 /* Add up the remaining bytes. This can't overflow because the
1874 * individual lengths are always <= 0x7fffffff, so when we add two
1875 * of them overflow is not possible.
1877 assert(cur != NULL);
1879 for (;;)
1881 /* NOTE: IDAT_list::count here, not IDAT_list::length */
1882 for (; j < cur->count; ++j)
1884 have += cur->lengths[j];
1885 if (len <= have)
1886 return len;
1889 /* If this was the end return the count of the available bytes */
1890 if (cur == idat->idat_list_tail)
1891 return have;
1893 cur = cur->next;
1894 j = 0;
1897 while (len > have);
1900 return len;
1904 static int
1905 process_IDAT(struct file *file)
1906 /* Process the IDAT stream, this is the more complex than the preceding
1907 * cases because the compressed data is spread across multiple IDAT chunks
1908 * (typically). Rechunking of the data is not handled here; all this
1909 * function does is establish whether the zlib header needs to be modified.
1911 * Initially the function returns false, indicating that the chunk should not
1912 * be written. It does this until the last IDAT chunk is passed in, then it
1913 * checks the zlib data and returns true.
1915 * It does not return false on a fatal error; it calls stop instead.
1917 * The caller must have an instantiated (IDAT) control structure and it must
1918 * have extent over the whole read of the IDAT stream. For a PNG this means
1919 * the whole PNG read, for MNG it could have lesser extent.
1922 struct IDAT_list *list;
1924 assert(file->idat != NULL && file->chunk != NULL);
1926 /* We need to first check the entire sequence of IDAT chunks to ensure the
1927 * stream is in sync. Do this by building a list of all the chunks and
1928 * recording the length of each because the length may have been fixed up by
1929 * sync_stream below.
1931 * At the end of the list of chunks, where the type of the next chunk is not
1932 * png_IDAT, process the whole stream using the list data to check validity
1933 * then return control to the start and rewrite everything.
1935 list = file->idat->idat_list_tail;
1937 if (list->count == list->length)
1939 list = IDAT_list_extend(list);
1941 if (list == NULL)
1942 stop(file, READ_ERROR_CODE, "out of memory");
1944 /* Move to the next block */
1945 list->count = 0;
1946 file->idat->idat_list_tail = list;
1949 /* And fill in the next IDAT information buffer. */
1950 list->lengths[(list->count)++] = file->chunk->chunk_length;
1952 /* The type of the next chunk was recorded in the file control structure by
1953 * the caller, if this is png_IDAT return 'skip' to the caller.
1955 if (file->type == png_IDAT)
1956 return 0; /* skip this for the moment */
1958 /* This is the final IDAT chunk, so run the tests to check for the too far
1959 * back error and possibly optimize the window bits. This means going back
1960 * to the start of the first chunk data, which is stored in the original
1961 * chunk allocation.
1963 setpos(file->chunk);
1965 if (zlib_check(file, 0))
1967 struct IDAT *idat;
1968 int cmp;
1970 /* The IDAT stream was successfully uncompressed; see whether it
1971 * contained the correct number of bytes of image data.
1973 cmp = uarb_cmp(file->image_bytes, file->image_digits,
1974 file->chunk->uncompressed_bytes, file->chunk->uncompressed_digits);
1976 if (cmp < 0)
1977 type_message(file, png_IDAT, "extra uncompressed data");
1979 else if (cmp > 0)
1980 stop(file, LIBPNG_ERROR_CODE, "IDAT: uncompressed data too small");
1982 /* Return the stream to the start of the first IDAT chunk; the length
1983 * is set in the write case below but the input chunk variables must be
1984 * set (once) here:
1986 setpos(file->chunk);
1988 idat = file->idat;
1989 idat->idat_cur = idat->idat_list_head;
1990 idat->idat_length = idat->idat_cur->lengths[0];
1991 idat->idat_count = 0; /* Count of chunks read in current list */
1992 idat->idat_index = 0; /* Index into chunk data */
1994 /* Update the chunk length to the correct value for the IDAT chunk: */
1995 file->chunk->chunk_length = rechunk_length(idat);
1997 /* Change the state to writing IDAT chunks */
1998 file->state = STATE_IDAT;
2000 return 1;
2003 else /* Failure to decompress the IDAT stream; give up. */
2004 stop(file, ZLIB_ERROR_CODE, "could not uncompress IDAT");
2007 /* ZLIB CONTROL STRUCTURE */
2008 struct zlib
2010 /* ANCESTORS */
2011 struct IDAT * idat; /* NOTE: May be NULL */
2012 struct chunk * chunk;
2013 struct file * file;
2014 struct global *global;
2016 /* GLOBAL ZLIB INFORMATION: SET BY THE CALLER */
2017 png_uint_32 rewrite_offset;
2019 /* GLOBAL ZLIB INFORMATION: SET BY THE ZLIB READ CODE */
2020 udigit compressed_bytes[5];
2021 int compressed_digits;
2022 udigit uncompressed_bytes[5];
2023 int uncompressed_digits;
2024 int file_bits; /* window bits from the file */
2025 int ok_bits; /* Set <16 on a successful read */
2026 int cksum; /* Set on a checksum error */
2028 /* PROTECTED ZLIB INFORMATION: USED BY THE ZLIB ROUTINES */
2029 z_stream z;
2030 png_uint_32 extra_bytes; /* Count of extra compressed bytes */
2031 int state;
2032 int rc; /* Last return code */
2033 int window_bits; /* 0 if no change */
2034 png_byte header[2];
2037 static const char *
2038 zlib_flevel(struct zlib *zlib)
2040 switch (zlib->header[1] >> 6)
2042 case 0: return "supfast";
2043 case 1: return "stdfast";
2044 case 2: return "default";
2045 case 3: return "maximum";
2046 default: assert(UNREACHED);
2049 return "COMPILER BUG";
2052 static const char *
2053 zlib_rc(struct zlib *zlib)
2054 /* Return a string for the zlib return code */
2056 switch (zlib->rc)
2058 case Z_OK: return "Z_OK";
2059 case Z_STREAM_END: return "Z_STREAM_END";
2060 case Z_NEED_DICT: return "Z_NEED_DICT";
2061 case Z_ERRNO: return "Z_ERRNO";
2062 case Z_STREAM_ERROR: return "Z_STREAM_ERROR";
2063 case Z_DATA_ERROR: return "Z_DATA_ERROR";
2064 case Z_MEM_ERROR: return "Z_MEM_ERROR";
2065 case Z_BUF_ERROR: return "Z_BUF_ERROR";
2066 case Z_VERSION_ERROR: return "Z_VERSION_ERROR";
2067 default: return "Z_*INVALID_RC*";
2071 static void
2072 zlib_message(struct zlib *zlib, int unexpected)
2073 /* Output a message given a zlib rc */
2075 if (zlib->global->errors)
2077 const char *reason = zlib->z.msg;
2079 if (reason == NULL)
2080 reason = "[no message]";
2082 fputs(zlib->file->file_name, stderr);
2083 type_sep(stderr);
2084 type_name(zlib->chunk->chunk_type, stderr);
2085 fprintf(stderr, ": %szlib error: %d (%s) (%s)\n",
2086 unexpected ? "unexpected " : "", zlib->rc, zlib_rc(zlib), reason);
2090 static void
2091 zlib_end(struct zlib *zlib)
2093 /* Output the summary line now; this ensures a summary line always gets
2094 * output regardless of the manner of exit.
2096 if (!zlib->global->quiet)
2098 if (zlib->ok_bits < 16) /* stream was read ok */
2100 const char *reason;
2102 if (zlib->cksum)
2103 reason = "CHK"; /* checksum error */
2105 else if (zlib->ok_bits > zlib->file_bits)
2106 reason = "TFB"; /* fixing a too-far-back error */
2108 else if (zlib->ok_bits == zlib->file_bits)
2109 reason = "OK ";
2111 else
2112 reason = "OPT"; /* optimizing window bits */
2114 /* SUMMARY FORMAT (for a successful zlib inflate):
2116 * IDAT reason flevel file-bits ok-bits compressed uncompressed file
2118 type_name(zlib->chunk->chunk_type, stdout);
2119 printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits,
2120 zlib->ok_bits);
2121 uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2122 putc(' ', stdout);
2123 uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits,
2124 stdout);
2125 putc(' ', stdout);
2126 fputs(zlib->file->file_name, stdout);
2127 putc('\n', stdout);
2130 else
2132 /* This is a zlib read error; the chunk will be skipped. For an IDAT
2133 * stream this will also cause a fatal read error (via stop()).
2135 * SUMMARY FORMAT:
2137 * IDAT SKP flevel file-bits z-rc compressed message file
2139 * z-rc is the zlib failure code; message is the error message with
2140 * spaces replaced by '-'. The compressed byte count indicates where
2141 * in the zlib stream the error occurred.
2143 type_name(zlib->chunk->chunk_type, stdout);
2144 printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits,
2145 zlib_rc(zlib));
2146 uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout);
2147 putc(' ', stdout);
2148 emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout);
2149 putc(' ', stdout);
2150 fputs(zlib->file->file_name, stdout);
2151 putc('\n', stdout);
2155 if (zlib->state >= 0)
2157 zlib->rc = inflateEnd(&zlib->z);
2159 if (zlib->rc != Z_OK)
2160 zlib_message(zlib, 1/*unexpected*/);
2163 CLEAR(*zlib);
2166 static int
2167 zlib_reset(struct zlib *zlib, int window_bits)
2168 /* Reinitializes a zlib with a different window_bits */
2170 assert(zlib->state >= 0); /* initialized by zlib_init */
2172 zlib->z.next_in = Z_NULL;
2173 zlib->z.avail_in = 0;
2174 zlib->z.next_out = Z_NULL;
2175 zlib->z.avail_out = 0;
2177 zlib->window_bits = window_bits;
2178 zlib->compressed_digits = 0;
2179 zlib->uncompressed_digits = 0;
2181 zlib->state = 0; /* initialized, once */
2182 zlib->rc = inflateReset2(&zlib->z, 0);
2183 if (zlib->rc != Z_OK)
2185 zlib_message(zlib, 1/*unexpected*/);
2186 return 0;
2189 return 1;
2192 static int
2193 zlib_init(struct zlib *zlib, struct IDAT *idat, struct chunk *chunk,
2194 int window_bits, png_uint_32 offset)
2195 /* Initialize a zlib_control; the result is true/false */
2197 CLEAR(*zlib);
2199 zlib->idat = idat;
2200 zlib->chunk = chunk;
2201 zlib->file = chunk->file;
2202 zlib->global = chunk->global;
2203 zlib->rewrite_offset = offset; /* never changed for this zlib */
2205 /* *_out does not need to be set: */
2206 zlib->z.next_in = Z_NULL;
2207 zlib->z.avail_in = 0;
2208 zlib->z.zalloc = Z_NULL;
2209 zlib->z.zfree = Z_NULL;
2210 zlib->z.opaque = Z_NULL;
2212 zlib->state = -1;
2213 zlib->window_bits = window_bits;
2215 zlib->compressed_digits = 0;
2216 zlib->uncompressed_digits = 0;
2218 /* These values are sticky across reset (in addition to the stuff in the
2219 * first block, which is actually constant.)
2221 zlib->file_bits = 16;
2222 zlib->ok_bits = 16; /* unset */
2223 zlib->cksum = 0; /* set when a checksum error is detected */
2225 /* '0' means use the header; inflateInit2 should always succeed because it
2226 * does nothing apart from allocating the internal zstate.
2228 zlib->rc = inflateInit2(&zlib->z, 0);
2229 if (zlib->rc != Z_OK)
2231 zlib_message(zlib, 1/*unexpected*/);
2232 return 0;
2235 else
2237 zlib->state = 0; /* initialized */
2238 return 1;
2242 static int
2243 max_window_bits(uarbc size, int ndigits)
2244 /* Return the zlib stream window bits required for data of the given size. */
2246 png_uint_16 cb;
2248 if (ndigits > 1)
2249 return 15;
2251 cb = size[0];
2253 if (cb > 16384) return 15;
2254 if (cb > 8192) return 14;
2255 if (cb > 4096) return 13;
2256 if (cb > 2048) return 12;
2257 if (cb > 1024) return 11;
2258 if (cb > 512) return 10;
2259 if (cb > 256) return 9;
2260 return 8;
2263 static int
2264 zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
2265 /* Read nbytes compressed bytes; the stream will be initialized if required.
2266 * Bytes are always being reread and errors are fatal. The return code is as
2267 * follows:
2269 * -1: saw the "too far back" error
2270 * 0: ok, keep going
2271 * 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
2272 * 2: a zlib error that cannot be corrected (error message already
2273 * output if required.)
2275 # define ZLIB_TOO_FAR_BACK (-1)
2276 # define ZLIB_OK 0
2277 # define ZLIB_STREAM_END 1
2278 # define ZLIB_FATAL 2
2280 int state = zlib->state;
2281 int endrc = ZLIB_OK;
2282 png_uint_32 in_bytes = 0;
2283 struct file *file = zlib->file;
2285 assert(state >= 0);
2287 while (in_bytes < nbytes && endrc == ZLIB_OK)
2289 png_uint_32 out_bytes;
2290 int flush;
2291 png_byte bIn = reread_byte(file);
2292 png_byte bOut;
2294 switch (state)
2296 case 0: /* first header byte */
2298 int file_bits = 8+(bIn >> 4);
2299 int new_bits = zlib->window_bits;
2301 zlib->file_bits = file_bits;
2303 /* Check against the existing value - it may not need to be
2304 * changed.
2306 if (new_bits == 0) /* no change */
2307 zlib->window_bits = file_bits;
2309 else if (new_bits != file_bits) /* rewrite required */
2310 bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
2313 zlib->header[0] = bIn;
2314 zlib->state = state = 1;
2315 break;
2317 case 1: /* second header byte */
2319 int b2 = bIn & 0xe0; /* top 3 bits */
2321 /* The checksum calculation, on the first 11 bits: */
2322 b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
2324 /* Update the checksum byte if required: */
2325 if (bIn != b2)
2327 /* If the first byte wasn't changed this indicates an error in
2328 * the checksum calculation; signal this by setting file_bits
2329 * (not window_bits) to 0.
2331 if (zlib->file_bits == zlib->window_bits)
2332 zlib->cksum = 1;
2334 bIn = (png_byte)b2;
2338 zlib->header[1] = bIn;
2339 zlib->state = state = 2;
2340 break;
2342 default: /* After the header bytes */
2343 break;
2346 /* For some streams, perhaps only those compressed with 'superfast
2347 * compression' (which results in a lot of copying) Z_BUF_ERROR can happen
2348 * immediately after all output has been flushed on the next input byte.
2349 * This is handled below when Z_BUF_ERROR is detected by adding an output
2350 * byte.
2352 zlib->z.next_in = &bIn;
2353 zlib->z.avail_in = 1;
2354 zlib->z.next_out = &bOut;
2355 zlib->z.avail_out = 0; /* Initially */
2357 /* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
2358 * byte without confusing what is going on with output.
2360 flush = Z_NO_FLUSH;
2361 out_bytes = 0;
2363 /* NOTE: expression 3 is only evaluted on 'continue', because of the
2364 * 'break' at the end of this loop below.
2366 for (;endrc == ZLIB_OK;
2367 flush = Z_SYNC_FLUSH,
2368 zlib->z.next_out = &bOut,
2369 zlib->z.avail_out = 1,
2370 ++out_bytes)
2372 zlib->rc = inflate(&zlib->z, flush);
2373 out_bytes -= zlib->z.avail_out;
2375 switch (zlib->rc)
2377 case Z_BUF_ERROR:
2378 if (zlib->z.avail_out == 0)
2379 continue; /* Try another output byte. */
2381 if (zlib->z.avail_in == 0)
2382 break; /* Try another input byte */
2384 /* Both avail_out and avail_in are 1 yet zlib returned a code
2385 * indicating no progress was possible. This is unexpected.
2387 zlib_message(zlib, 1/*unexpected*/);
2388 endrc = ZLIB_FATAL; /* stop processing */
2389 break;
2391 case Z_OK:
2392 /* Zlib is supposed to have made progress: */
2393 assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
2394 continue;
2396 case Z_STREAM_END:
2397 /* This is the successful end. */
2398 zlib->state = 3; /* end of stream */
2399 endrc = ZLIB_STREAM_END;
2400 break;
2402 case Z_NEED_DICT:
2403 zlib_message(zlib, 0/*stream error*/);
2404 endrc = ZLIB_FATAL;
2405 break;
2407 case Z_DATA_ERROR:
2408 /* The too far back error can be corrected, others cannot: */
2409 if (zlib->z.msg != NULL &&
2410 strcmp(zlib->z.msg, "invalid distance too far back") == 0)
2412 endrc = ZLIB_TOO_FAR_BACK;
2413 break;
2415 /* FALL THROUGH */
2417 default:
2418 zlib_message(zlib, 0/*stream error*/);
2419 endrc = ZLIB_FATAL;
2420 break;
2421 } /* switch (inflate rc) */
2423 /* Control gets here when further output is not possible; endrc may
2424 * still be ZLIB_OK if more input is required.
2426 break;
2427 } /* for (output bytes) */
2429 /* Keep a running count of output byte produced: */
2430 zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
2431 zlib->uncompressed_digits, out_bytes);
2433 /* Keep going, the loop will terminate when endrc is no longer set to
2434 * ZLIB_OK or all the input bytes have been consumed; meanwhile keep
2435 * adding input bytes.
2437 assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
2439 in_bytes += 1 - zlib->z.avail_in;
2440 } /* while (input bytes) */
2442 assert(in_bytes == nbytes || endrc != ZLIB_OK);
2444 /* Update the running total of input bytes consumed */
2445 zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
2446 zlib->compressed_digits, in_bytes - zlib->z.avail_in);
2448 /* At the end of the stream update the chunk with the accumulated
2449 * information if it is an improvement:
2451 if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
2453 struct chunk *chunk = zlib->chunk;
2455 chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
2456 zlib->uncompressed_bytes, zlib->uncompressed_digits);
2457 chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
2458 zlib->compressed_bytes, zlib->compressed_digits);
2459 chunk->rewrite_buffer[0] = zlib->header[0];
2460 chunk->rewrite_buffer[1] = zlib->header[1];
2462 if (zlib->window_bits != zlib->file_bits || zlib->cksum)
2464 /* A rewrite is required */
2465 chunk->rewrite_offset = zlib->rewrite_offset;
2466 chunk->rewrite_length = 2;
2469 else
2471 chunk->rewrite_offset = 0;
2472 chunk->rewrite_length = 0;
2475 if (in_bytes < nbytes)
2476 chunk_message(chunk, "extra compressed data");
2478 zlib->extra_bytes = nbytes - in_bytes;
2479 zlib->ok_bits = zlib->window_bits;
2482 return endrc;
2485 static int
2486 zlib_run(struct zlib *zlib)
2487 /* Like zlib_advance but also handles a stream of IDAT chunks. */
2489 /* The 'extra_bytes' field is set by zlib_advance if there is extra
2490 * compressed data in the chunk it handles (if it sees Z_STREAM_END before
2491 * all the input data has been used.) This function uses the value to update
2492 * the correct chunk length, so the problem should only ever be detected once
2493 * for each chunk. zlib_advance outputs the error message, though see the
2494 * IDAT specific check below.
2496 zlib->extra_bytes = 0;
2498 if (zlib->idat != NULL)
2500 struct IDAT_list *list = zlib->idat->idat_list_head;
2501 struct IDAT_list *last = zlib->idat->idat_list_tail;
2502 int skip = 0;
2504 /* 'rewrite_offset' is the offset of the LZ data within the chunk, for
2505 * IDAT it should be 0:
2507 assert(zlib->rewrite_offset == 0);
2509 /* Process each IDAT_list in turn; the caller has left the stream
2510 * positioned at the start of the first IDAT chunk data.
2512 for (;;)
2514 const unsigned int count = list->count;
2515 unsigned int i;
2517 for (i = 0; i<count; ++i)
2519 int rc;
2521 if (skip > 0) /* Skip CRC and next IDAT header */
2522 skip_12(zlib->file);
2524 skip = 12; /* for the next time */
2526 rc = zlib_advance(zlib, list->lengths[i]);
2528 switch (rc)
2530 case ZLIB_OK: /* keep going */
2531 break;
2533 case ZLIB_STREAM_END: /* stop */
2534 /* There may be extra chunks; if there are and one of them is
2535 * not zero length output the 'extra data' message. Only do
2536 * this check if errors are being output.
2538 if (zlib->global->errors && zlib->extra_bytes == 0)
2540 struct IDAT_list *check = list;
2541 int j = i+1, jcount = count;
2543 for (;;)
2545 for (; j<jcount; ++j)
2546 if (check->lengths[j] > 0)
2548 chunk_message(zlib->chunk,
2549 "extra compressed data");
2550 goto end_check;
2553 if (check == last)
2554 break;
2556 check = check->next;
2557 jcount = check->count;
2558 j = 0;
2562 end_check:
2563 /* Terminate the list at the current position, reducing the
2564 * length of the last IDAT too if required.
2566 list->lengths[i] -= zlib->extra_bytes;
2567 list->count = i+1;
2568 zlib->idat->idat_list_tail = list;
2569 /* FALL THROUGH */
2571 default:
2572 return rc;
2576 /* At the end of the compressed data and Z_STREAM_END was not seen. */
2577 if (list == last)
2578 return ZLIB_OK;
2580 list = list->next;
2584 else
2586 struct chunk *chunk = zlib->chunk;
2587 int rc;
2589 assert(zlib->rewrite_offset < chunk->chunk_length);
2591 rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset);
2593 /* The extra bytes in the chunk are handled now by adjusting the chunk
2594 * length to exclude them; the zlib data is always stored at the end of
2595 * the PNG chunk (although clearly this is not necessary.) zlib_advance
2596 * has already output a warning message.
2598 chunk->chunk_length -= zlib->extra_bytes;
2599 return rc;
2603 static int /* global function; not a member function */
2604 zlib_check(struct file *file, png_uint_32 offset)
2605 /* Check the stream of zlib compressed data in either idat (if given) or (if
2606 * not) chunk. In fact it is zlib_run that handles the difference in reading
2607 * a single chunk and a list of IDAT chunks.
2609 * In either case the input file must be positioned at the first byte of zlib
2610 * compressed data (the first header byte).
2612 * The return value is true on success, including the case where the zlib
2613 * header may need to be rewritten, and false on an unrecoverable error.
2615 * In the case of IDAT chunks 'offset' should be 0.
2618 fpos_t start_pos;
2619 struct zlib zlib;
2621 /* Record the start of the LZ data to allow a re-read. */
2622 file_getpos(file, &start_pos);
2624 /* First test the existing (file) window bits: */
2625 if (zlib_init(&zlib, file->idat, file->chunk, 0/*window bits*/, offset))
2627 int min_bits, max_bits, rc;
2629 /* The first run using the existing window bits. */
2630 rc = zlib_run(&zlib);
2632 switch (rc)
2634 case ZLIB_TOO_FAR_BACK:
2635 /* too far back error */
2636 file->status_code |= TOO_FAR_BACK;
2637 min_bits = zlib.window_bits + 1;
2638 max_bits = 15;
2639 break;
2641 case ZLIB_STREAM_END:
2642 if (!zlib.global->optimize_zlib &&
2643 zlib.window_bits == zlib.file_bits && !zlib.cksum)
2645 /* The trivial case where the stream is ok and optimization was
2646 * not requested.
2648 zlib_end(&zlib);
2649 return 1;
2652 max_bits = max_window_bits(zlib.uncompressed_bytes,
2653 zlib.uncompressed_digits);
2654 if (zlib.ok_bits < max_bits)
2655 max_bits = zlib.ok_bits;
2656 min_bits = 8;
2658 /* cksum is set if there is an error in the zlib header checksum
2659 * calculation in the original file (and this may be the only reason
2660 * a rewrite is required). We can't rely on the file window bits in
2661 * this case, so do the optimization anyway.
2663 if (zlib.cksum)
2664 chunk_message(zlib.chunk, "zlib checkum");
2665 break;
2668 case ZLIB_OK:
2669 /* Truncated stream; unrecoverable, gets converted to ZLIB_FATAL */
2670 zlib.z.msg = PNGZ_MSG_CAST("[truncated]");
2671 zlib_message(&zlib, 0/*expected*/);
2672 /* FALL THROUGH */
2674 default:
2675 /* Unrecoverable error; skip the chunk; a zlib_message has already
2676 * been output.
2678 zlib_end(&zlib);
2679 return 0;
2682 /* Optimize window bits or fix a too-far-back error. min_bits and
2683 * max_bits have been set appropriately, ok_bits records the bit value
2684 * known to work.
2686 while (min_bits < max_bits || max_bits < zlib.ok_bits/*if 16*/)
2688 int test_bits = (min_bits + max_bits) >> 1;
2690 if (zlib_reset(&zlib, test_bits))
2692 file_setpos(file, &start_pos);
2693 rc = zlib_run(&zlib);
2695 switch (rc)
2697 case ZLIB_TOO_FAR_BACK:
2698 min_bits = test_bits+1;
2699 if (min_bits > max_bits)
2701 /* This happens when the stream really is damaged and it
2702 * contains a distance code that addresses bytes before
2703 * the start of the uncompressed data.
2705 assert(test_bits == 15);
2707 /* Output the error that wasn't output before: */
2708 if (zlib.z.msg == NULL)
2709 zlib.z.msg = PNGZ_MSG_CAST(
2710 "invalid distance too far back");
2711 zlib_message(&zlib, 0/*stream error*/);
2712 zlib_end(&zlib);
2713 return 0;
2715 break;
2717 case ZLIB_STREAM_END: /* success */
2718 max_bits = test_bits;
2719 break;
2721 default:
2722 /* A fatal error; this happens if a too-far-back error was
2723 * hiding a more serious error, zlib_advance has already
2724 * output a zlib_message.
2726 zlib_end(&zlib);
2727 return 0;
2731 else /* inflateReset2 failed */
2733 zlib_end(&zlib);
2734 return 0;
2738 /* The loop guarantees this */
2739 assert(zlib.ok_bits == max_bits);
2740 zlib_end(&zlib);
2741 return 1;
2744 else /* zlib initialization failed - skip the chunk */
2746 zlib_end(&zlib);
2747 return 0;
2751 /***************************** LIBPNG CALLBACKS *******************************/
2752 /* The strategy here is to run a regular libpng PNG file read but examine the
2753 * input data (from the file) before passing it to libpng so as to be aware of
2754 * the state we expect libpng to be in. Warning and error callbacks are also
2755 * intercepted so that they can be quieted and interpreted. Interpretation
2756 * depends on a somewhat risky string match for known error messages; let us
2757 * hope that this can be fixed in the next version of libpng.
2759 * The control structure is pointed to by the libpng error pointer. It contains
2760 * that set of structures which must persist across multiple read callbacks,
2761 * which is pretty much everything except the 'zlib' control structure.
2763 * The file structure is instantiated in the caller of the per-file routine, but
2764 * the per-file routine contains the chunk and IDAT control structures.
2766 /* The three routines read_chunk, process_chunk and sync_stream can only be
2767 * called via a call to read_chunk and only exit at a return from process_chunk.
2768 * These routines could have been written as one confusing large routine,
2769 * instead this code relies on the compiler to do tail call elimination. The
2770 * possible calls are as follows:
2772 * read_chunk
2773 * -> sync_stream
2774 * -> process_chunk
2775 * -> process_chunk
2776 * -> read_chunk
2777 * returns
2779 static void read_chunk(struct file *file);
2780 static void
2781 process_chunk(struct file *file, png_uint_32 file_crc, png_uint_32 next_length,
2782 png_uint_32 next_type)
2783 /* Called when the chunk data has been read, next_length and next_type
2784 * will be set for the next chunk (or 0 if this is IEND).
2786 * When this routine returns, chunk_length and chunk_type will be set for the
2787 * next chunk to write because if a chunk is skipped this return calls back
2788 * to read_chunk.
2791 const png_uint_32 type = file->type;
2793 if (file->global->verbose > 1)
2795 fputs(" ", stderr);
2796 type_name(file->type, stderr);
2797 fprintf(stderr, " %lu 0x%.8x 0x%.8x\n", (unsigned long)file->length,
2798 file->crc ^ 0xffffffff, file_crc);
2801 /* The basic structure seems correct but the CRC may not match, in this
2802 * case assume that it is simply a bad CRC, either wrongly calculated or
2803 * because of damaged stream data.
2805 if ((file->crc ^ 0xffffffff) != file_crc)
2807 /* The behavior is set by the 'skip' setting; if it is anything other
2808 * than SKIP_BAD_CRC ignore the bad CRC and return the chunk, with a
2809 * corrected CRC and possibly processed, to libpng. Otherwise skip the
2810 * chunk, which will result in a fatal error if the chunk is critical.
2812 file->status_code |= CRC_ERROR;
2814 /* Ignore the bad CRC */
2815 if (file->global->skip != SKIP_BAD_CRC)
2816 type_message(file, type, "bad CRC");
2818 /* This will cause an IEND with a bad CRC to stop */
2819 else if (CRITICAL(type))
2820 stop(file, READ_ERROR_CODE, "bad CRC in critical chunk");
2822 else
2824 type_message(file, type, "skipped: bad CRC");
2826 /* NOTE: this cannot be reached for IEND because it is critical. */
2827 goto skip_chunk;
2831 /* Check for other 'skip' cases and handle these; these only apply to
2832 * ancillary chunks (and not tRNS, which should probably have been a critical
2833 * chunk.)
2835 if (skip_chunk_type(file->global, type))
2836 goto skip_chunk;
2838 /* The chunk may still be skipped if problems are detected in the LZ data,
2839 * however the LZ data check requires a chunk. Handle this by instantiating
2840 * a chunk unless an IDAT is already instantiated (IDAT control structures
2841 * instantiate their own chunk.)
2843 if (type != png_IDAT)
2844 file->alloc(file, 0/*chunk*/);
2846 else if (file->idat == NULL)
2847 file->alloc(file, 1/*IDAT*/);
2849 else
2851 /* The chunk length must be updated for process_IDAT */
2852 assert(file->chunk != NULL);
2853 assert(file->chunk->chunk_type == png_IDAT);
2854 file->chunk->chunk_length = file->length;
2857 /* Record the 'next' information too, now that the original values for
2858 * this chunk have been copied. Notice that the IDAT chunks only make a
2859 * copy of the position of the first chunk, this is fine - process_IDAT does
2860 * not need the position of this chunk.
2862 file->length = next_length;
2863 file->type = next_type;
2864 getpos(file);
2866 /* Do per-type processing, note that if this code does not return from the
2867 * function the chunk will be skipped. The rewrite is cancelled here so that
2868 * it can be set in the per-chunk processing.
2870 file->chunk->rewrite_length = 0;
2871 file->chunk->rewrite_offset = 0;
2872 switch (type)
2874 default:
2875 return;
2877 case png_IHDR:
2878 /* Read this now and update the control structure with the information
2879 * it contains. The header is validated completely to ensure this is a
2880 * PNG.
2883 struct chunk *chunk = file->chunk;
2885 if (chunk->chunk_length != 13)
2886 stop_invalid(file, "IHDR length");
2888 /* Read all the IHDR information and validate it. */
2889 setpos(chunk);
2890 file->width = reread_4(file);
2891 file->height = reread_4(file);
2892 file->bit_depth = reread_byte(file);
2893 file->color_type = reread_byte(file);
2894 file->compression_method = reread_byte(file);
2895 file->filter_method = reread_byte(file);
2896 file->interlace_method = reread_byte(file);
2898 /* This validates all the fields, and calls stop_invalid if
2899 * there is a problem.
2901 calc_image_size(file);
2903 return;
2905 /* Ancillary chunks that require further processing: */
2906 case png_zTXt: case png_iCCP:
2907 if (process_zTXt_iCCP(file))
2908 return;
2909 chunk_end(&file->chunk);
2910 file_setpos(file, &file->data_pos);
2911 break;
2913 case png_iTXt:
2914 if (process_iTXt(file))
2915 return;
2916 chunk_end(&file->chunk);
2917 file_setpos(file, &file->data_pos);
2918 break;
2920 case png_IDAT:
2921 if (process_IDAT(file))
2922 return;
2923 /* First pass: */
2924 assert(next_type == png_IDAT);
2925 break;
2928 /* Control reaches this point if the chunk must be skipped. For chunks other
2929 * than IDAT this means that the zlib compressed data is fatally damanged and
2930 * the chunk will not be passed to libpng. For IDAT it means that the end of
2931 * the IDAT stream has not yet been reached and we must handle the next
2932 * (IDAT) chunk. If the LZ data in an IDAT stream cannot be read 'stop' must
2933 * be used to halt parsing of the PNG.
2935 read_chunk(file);
2936 return;
2938 /* This is the generic code to skip the current chunk; simply jump to the
2939 * next one.
2941 skip_chunk:
2942 file->length = next_length;
2943 file->type = next_type;
2944 getpos(file);
2945 read_chunk(file);
2948 static png_uint_32
2949 get32(png_bytep buffer, int offset)
2950 /* Read a 32-bit value from an 8-byte circular buffer (used only below).
2953 return
2954 (buffer[ offset & 7] << 24) +
2955 (buffer[(offset+1) & 7] << 16) +
2956 (buffer[(offset+2) & 7] << 8) +
2957 (buffer[(offset+3) & 7] );
2960 static void
2961 sync_stream(struct file *file)
2962 /* The stream seems to be messed up, attempt to resync from the current chunk
2963 * header. Executes stop on a fatal error, otherwise calls process_chunk.
2966 png_uint_32 file_crc;
2968 file->status_code |= STREAM_ERROR;
2970 if (file->global->verbose)
2972 fputs(" SYNC ", stderr);
2973 type_name(file->type, stderr);
2974 putc('\n', stderr);
2977 /* Return to the start of the chunk data */
2978 file_setpos(file, &file->data_pos);
2979 file->read_count = 8;
2981 if (read_4(file, &file_crc) == 4) /* else completely truncated */
2983 /* Ignore the recorded chunk length, proceed through the data looking for
2984 * a leading sequence of bytes that match the CRC in the following four
2985 * bytes. Each time a match is found check the next 8 bytes for a valid
2986 * length, chunk-type pair.
2988 png_uint_32 length;
2989 png_uint_32 type = file->type;
2990 png_uint_32 crc = crc_init_4(type);
2991 png_byte buffer[8];
2992 unsigned int nread = 0, nused = 0;
2994 for (length=0; length <= 0x7fffffff; ++length)
2996 int ch;
2998 if ((crc ^ 0xffffffff) == file_crc)
3000 /* A match on the CRC; for IEND this is sufficient, but for anything
3001 * else expect a following chunk header.
3003 if (type == png_IEND)
3005 file->length = length;
3006 process_chunk(file, file_crc, 0, 0);
3007 return;
3010 else
3012 /* Need 8 bytes */
3013 while (nread < 8+nused)
3015 ch = read_byte(file);
3016 if (ch == EOF)
3017 goto truncated;
3018 buffer[(nread++) & 7] = (png_byte)ch;
3021 /* Prevent overflow */
3022 nread -= nused & ~7;
3023 nused -= nused & ~7; /* or, nused &= 7 ;-) */
3025 /* Examine the 8 bytes for a valid chunk header. */
3027 png_uint_32 next_length = get32(buffer, nused);
3029 if (next_length < 0x7fffffff)
3031 png_uint_32 next_type = get32(buffer, nused+4);
3033 if (chunk_type_valid(next_type))
3035 file->read_count -= 8;
3036 process_chunk(file, file_crc, next_length, next_type);
3037 return;
3041 /* Not valid, keep going. */
3046 /* This catches up with the circular buffer which gets filled above
3047 * while checking a chunk header. This code is slightly tricky - if
3048 * the chunk_type is IEND the buffer will never be used, if it is not
3049 * the code will always read ahead exactly 8 bytes and pass this on to
3050 * process_chunk. So the invariant that IEND leaves the file position
3051 * after the IEND CRC and other chunk leave it after the *next* chunk
3052 * header is not broken.
3054 if (nread <= nused)
3056 ch = read_byte(file);
3058 if (ch == EOF)
3059 goto truncated;
3062 else
3063 ch = buffer[(++nused) & 7];
3065 crc = crc_one_byte(crc, file_crc >> 24);
3066 file_crc = (file_crc << 8) + ch;
3069 /* Control gets to here if when 0x7fffffff bytes (plus 8) have been read,
3070 * ok, treat this as a damaged stream too:
3074 truncated:
3075 stop(file, READ_ERROR_CODE, "damaged PNG stream");
3078 static void
3079 read_chunk(struct file *file)
3080 /* On entry file::data_pos must be set to the position of the first byte
3081 * of the chunk data *and* the input file must be at this position. This
3082 * routine (via process_chunk) instantiates a chunk or IDAT control structure
3083 * based on file::length and file::type and also resets these fields and
3084 * file::data_pos for the chunk after this one. For an IDAT chunk the whole
3085 * stream of IDATs will be read, until something other than an IDAT is
3086 * encountered, and the file fields will be set for the chunk after the end
3087 * of the stream of IDATs.
3089 * For IEND the file::type field will be set to 0, and nothing beyond the end
3090 * of the IEND chunk will have been read.
3093 png_uint_32 length = file->length;
3094 png_uint_32 type = file->type;
3096 /* After IEND file::type is set to 0, if libpng attempts to read
3097 * more data at this point this is a bug in libpng.
3099 if (type == 0)
3100 stop(file, UNEXPECTED_ERROR_CODE, "read beyond IEND");
3102 if (file->global->verbose > 2)
3104 fputs(" ", stderr);
3105 type_name(type, stderr);
3106 fprintf(stderr, " %lu\n", (unsigned long)length);
3109 /* Start the read_crc calculation with the chunk type, then read to the end
3110 * of the chunk data (without processing it in any way) to check that it is
3111 * all there and calculate the CRC.
3113 file->crc = crc_init_4(type);
3114 if (crc_read_many(file, length)) /* else it was truncated */
3116 png_uint_32 file_crc; /* CRC read from file */
3117 unsigned int nread = read_4(file, &file_crc);
3119 if (nread == 4)
3121 if (type != png_IEND) /* do not read beyond IEND */
3123 png_uint_32 next_length;
3125 nread += read_4(file, &next_length);
3126 if (nread == 8 && next_length <= 0x7fffffff)
3128 png_uint_32 next_type;
3130 nread += read_4(file, &next_type);
3132 if (nread == 12 && chunk_type_valid(next_type))
3134 /* Adjust the read count back to the correct value for this
3135 * chunk.
3137 file->read_count -= 8;
3138 process_chunk(file, file_crc, next_length, next_type);
3139 return;
3144 else /* IEND */
3146 process_chunk(file, file_crc, 0, 0);
3147 return;
3152 /* Control gets to here if the the stream seems invalid or damaged in some
3153 * way. Either there was a problem reading all the expected data (this
3154 * chunk's data, its CRC and the length and type of the next chunk) or the
3155 * next chunk length/type are invalid. Notice that the cases that end up
3156 * here all correspond to cases that would otherwise terminate the read of
3157 * the PNG file.
3159 sync_stream(file);
3162 /* This returns a file* from a png_struct in an implementation specific way. */
3163 static struct file *get_control(png_const_structrp png_ptr);
3165 static void PNGCBAPI
3166 error_handler(png_structp png_ptr, png_const_charp message)
3168 stop(get_control(png_ptr), LIBPNG_ERROR_CODE, message);
3171 static void PNGCBAPI
3172 warning_handler(png_structp png_ptr, png_const_charp message)
3174 struct file *file = get_control(png_ptr);
3176 if (file->global->warnings)
3177 emit_error(file, LIBPNG_WARNING_CODE, message);
3180 /* Read callback - this is where the work gets done to check the stream before
3181 * passing it to libpng
3183 static void PNGCBAPI
3184 read_callback(png_structp png_ptr, png_bytep buffer, size_t count)
3185 /* Return 'count' bytes to libpng in 'buffer' */
3187 struct file *file = get_control(png_ptr);
3188 png_uint_32 type, length; /* For the chunk be *WRITTEN* */
3189 struct chunk *chunk;
3191 /* libpng should always ask for at least one byte */
3192 if (count == 0)
3193 stop(file, UNEXPECTED_ERROR_CODE, "read callback for 0 bytes");
3195 /* The callback always reads ahead by 8 bytes - the signature or chunk header
3196 * - these bytes are stored in chunk_length and chunk_type. This block is
3197 * executed once for the signature and once for the first chunk right at the
3198 * start.
3200 if (file->read_count < 8)
3202 assert(file->read_count == 0);
3203 assert((file->status_code & TRUNCATED) == 0);
3205 (void)read_4(file, &file->length);
3207 if (file->read_count == 4)
3208 (void)read_4(file, &file->type);
3210 if (file->read_count < 8)
3212 assert((file->status_code & TRUNCATED) != 0);
3213 stop(file, READ_ERROR_CODE, "not a PNG (too short)");
3216 if (file->state == STATE_SIGNATURE)
3218 if (file->length != sig1 || file->type != sig2)
3219 stop(file, LIBPNG_ERROR_CODE, "not a PNG (signature)");
3221 /* Else write it (this is the initialization of write_count, prior to
3222 * this it contains CLEAR garbage.)
3224 file->write_count = 0;
3227 else
3229 assert(file->state == STATE_CHUNKS);
3231 /* The first chunk must be a well formed IHDR (this could be relaxed to
3232 * use the checks in process_chunk, but that seems unnecessary.)
3234 if (file->length != 13 || file->type != png_IHDR)
3235 stop(file, LIBPNG_ERROR_CODE, "not a PNG (IHDR)");
3237 /* The position of the data must be stored too */
3238 getpos(file);
3242 /* Retrieve previous state (because the read callbacks are made pretty much
3243 * byte-by-byte in the sequential reader prior to 1.7).
3245 chunk = file->chunk;
3247 if (chunk != NULL)
3249 length = chunk->chunk_length;
3250 type = chunk->chunk_type;
3253 else
3255 /* This is the signature case; for IDAT and other chunks these values will
3256 * be overwritten when read_chunk is called below.
3258 length = file->length;
3259 type = file->type;
3264 png_uint_32 b;
3266 /* Complete the read of a chunk; as a side effect this also instantiates
3267 * a chunk control structure and sets the file length/type/data_pos fields
3268 * for the *NEXT* chunk header.
3270 * NOTE: at an IDAT any following IDAT chunks will also be read and the
3271 * next_ fields will refer to the chunk after the last IDAT.
3273 * NOTE: read_chunk only returns when it has read a chunk that must now be
3274 * written.
3276 if (file->state != STATE_SIGNATURE && chunk == NULL)
3278 assert(file->read_count == 8);
3279 assert(file->idat == NULL);
3280 read_chunk(file);
3281 chunk = file->chunk;
3282 assert(chunk != NULL);
3284 /* Do the initialization that was not done before. */
3285 length = chunk->chunk_length;
3286 type = chunk->chunk_type;
3288 /* And start writing the new chunk. */
3289 file->write_count = 0;
3292 /* The chunk_ fields describe a chunk that must be written, or hold the
3293 * signature. Write the header first. In the signature case this
3294 * rewrites the signature.
3296 switch (file->write_count)
3298 case 0: b = length >> 24; break;
3299 case 1: b = length >> 16; break;
3300 case 2: b = length >> 8; break;
3301 case 3: b = length ; break;
3303 case 4: b = type >> 24; break;
3304 case 5: b = type >> 16; break;
3305 case 6: b = type >> 8; break;
3306 case 7: b = type ; break;
3308 case 8:
3309 /* The header has been written. If this is really the signature
3310 * that's all that is required and we can go to normal chunk
3311 * processing.
3313 if (file->state == STATE_SIGNATURE)
3315 /* The signature has been written, the tail call to read_callback
3316 * below (it's just a goto to the start with a decent compiler)
3317 * will read the IHDR header ahead and validate it.
3319 assert(length == sig1 && type == sig2);
3320 file->read_count = 0; /* Forces a header read */
3321 file->state = STATE_CHUNKS; /* IHDR: checked above */
3322 read_callback(png_ptr, buffer, count);
3323 return;
3326 else
3328 assert(chunk != NULL);
3330 /* Set up for write, notice that repositioning the input stream
3331 * is only necessary if something is to be read from it. Also
3332 * notice that for the IDAT stream this must only happen once -
3333 * on the first IDAT - to get back to the start of the list and
3334 * this is done inside process_IDAT:
3336 chunk->write_crc = crc_init_4(type);
3337 if (file->state != STATE_IDAT && length > 0)
3338 setpos(chunk);
3340 /* FALL THROUGH */
3342 default:
3343 assert(chunk != NULL);
3345 /* NOTE: the arithmetic below overflows and gives a large positive
3346 * png_uint_32 value until the whole chunk data has been written.
3348 switch (file->write_count - length)
3350 /* Write the chunk data, normally this just comes from
3351 * the file. The only exception is for that part of a
3352 * chunk which is zlib data and which must be rewritten,
3353 * and IDAT chunks which can be completely
3354 * reconstructed.
3356 default:
3357 if (file->state == STATE_IDAT)
3359 struct IDAT *idat = file->idat;
3361 assert(idat != NULL);
3363 /* Read an IDAT byte from the input stream of IDAT chunks.
3364 * Because the IDAT stream can be re-chunked this stream is
3365 * held in the struct IDAT members. The chunk members, in
3366 * particular chunk_length (and therefore the length local)
3367 * refer to the output chunk.
3369 while (idat->idat_index >= idat->idat_length)
3371 /* Advance one chunk */
3372 struct IDAT_list *cur = idat->idat_cur;
3374 assert(idat->idat_index == idat->idat_length);
3375 assert(cur != NULL && cur->count > 0);
3377 /* NOTE: IDAT_list::count here, not IDAT_list::length */
3378 if (++(idat->idat_count) >= cur->count)
3380 assert(idat->idat_count == cur->count);
3382 /* Move on to the next IDAT_list: */
3383 cur = cur->next;
3385 /* This is an internal error - read beyond the end of
3386 * the pre-calculated stream.
3388 if (cur == NULL || cur->count == 0)
3389 stop(file, UNEXPECTED_ERROR_CODE,
3390 "read beyond end of IDAT");
3392 idat->idat_count = 0;
3393 idat->idat_cur = cur;
3396 idat->idat_index = 0;
3397 /* Zero length IDAT chunks are permitted, so the length
3398 * here may be 0.
3400 idat->idat_length = cur->lengths[idat->idat_count];
3402 /* And skip 12 bytes to the next chunk data */
3403 skip_12(file);
3406 /* The index is always that of the next byte, the rest of
3407 * the information is always the current IDAT chunk and the
3408 * current list.
3410 ++(idat->idat_index);
3413 /* Read the byte from the stream. */
3414 b = reread_byte(file);
3416 /* If the byte must be rewritten handle that here */
3417 if (chunk->rewrite_length > 0)
3419 if (chunk->rewrite_offset > 0)
3420 --(chunk->rewrite_offset);
3422 else
3424 b = chunk->rewrite_buffer[0];
3425 memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,
3426 (sizeof chunk->rewrite_buffer)-
3427 (sizeof chunk->rewrite_buffer[0]));
3429 --(chunk->rewrite_length);
3433 chunk->write_crc = crc_one_byte(chunk->write_crc, b);
3434 break;
3436 /* The CRC is written at:
3438 * chunk_write == chunk_length+8..chunk_length+11
3440 * so 8 to 11. The CRC is not (yet) conditioned.
3442 case 8: b = chunk->write_crc >> 24; goto write_crc;
3443 case 9: b = chunk->write_crc >> 16; goto write_crc;
3444 case 10: b = chunk->write_crc >> 8; goto write_crc;
3445 case 11:
3446 /* This must happen before the chunk_end below: */
3447 b = chunk->write_crc;
3449 if (file->global->verbose > 2)
3451 fputs(" ", stderr);
3452 type_name(type, stderr);
3453 fprintf(stderr, " %lu 0x%.8x\n", (unsigned long)length,
3454 chunk->write_crc ^ 0xffffffff);
3457 /* The IDAT stream is written without a call to read_chunk
3458 * until the end is reached. rechunk_length() calculates the
3459 * length of the output chunks. Control gets to this point at
3460 * the end of an *output* chunk - the length calculated by
3461 * rechunk_length. If this corresponds to the end of the
3462 * input stream stop writing IDAT chunks, otherwise continue.
3464 if (file->state == STATE_IDAT &&
3465 (file->idat->idat_index < file->idat->idat_length ||
3466 1+file->idat->idat_count < file->idat->idat_cur->count ||
3467 file->idat->idat_cur != file->idat->idat_list_tail))
3469 /* Write another IDAT chunk. Call rechunk_length to
3470 * calculate the length required.
3472 length = chunk->chunk_length = rechunk_length(file->idat);
3473 assert(type == png_IDAT);
3474 file->write_count = 0; /* for the new chunk */
3475 --(file->write_count); /* fake out the increment below */
3478 else
3480 /* Entered at the end of a non-IDAT chunk and at the end of
3481 * the IDAT stream. The rewrite should have been cleared.
3483 if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)
3484 stop(file, UNEXPECTED_ERROR_CODE, "pending rewrite");
3486 /* This is the last byte so reset chunk_read for the next
3487 * chunk and move the input file to the position after the
3488 * *next* chunk header if required.
3490 file->read_count = 8;
3491 file_setpos(file, &file->data_pos);
3493 if (file->idat == NULL)
3494 chunk_end(&file->chunk);
3496 else
3497 IDAT_end(&file->idat);
3500 write_crc:
3501 b ^= 0xff; /* conditioning */
3502 break;
3504 break;
3507 /* Write one byte */
3508 b &= 0xff;
3509 *buffer++ = (png_byte)b;
3510 --count;
3511 write_byte(file, (png_byte)b); /* increments chunk_write */
3513 while (count > 0);
3516 /* Bundle the file and an uninitialized chunk and IDAT control structure
3517 * together to allow implementation of the chunk/IDAT allocate routine.
3519 struct control
3521 struct file file;
3522 struct chunk chunk;
3523 struct IDAT idat;
3526 static int
3527 control_end(struct control *control)
3529 return file_end(&control->file);
3532 static struct file *
3533 get_control(png_const_structrp png_ptr)
3535 /* This just returns the (file*). The chunk and idat control structures
3536 * don't always exist.
3538 struct control *control = png_voidcast(struct control*,
3539 png_get_error_ptr(png_ptr));
3540 return &control->file;
3543 static void
3544 allocate(struct file *file, int allocate_idat)
3546 struct control *control = png_voidcast(struct control*, file->alloc_ptr);
3548 if (allocate_idat)
3550 assert(file->idat == NULL);
3551 IDAT_init(&control->idat, file);
3554 else /* chunk */
3556 assert(file->chunk == NULL);
3557 chunk_init(&control->chunk, file);
3561 static int
3562 control_init(struct control *control, struct global *global,
3563 const char *file_name, const char *out_name)
3564 /* This wraps file_init(&control::file) and simply returns the result from
3565 * file_init.
3568 return file_init(&control->file, global, file_name, out_name, control,
3569 allocate);
3572 static int
3573 read_png(struct control *control)
3574 /* Read a PNG, return 0 on success else an error (status) code; a bit mask as
3575 * defined for file::status_code as above.
3578 png_structp png_ptr;
3579 png_infop info_ptr = NULL;
3580 volatile int rc;
3582 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
3583 error_handler, warning_handler);
3585 if (png_ptr == NULL)
3587 /* This is not really expected. */
3588 log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
3589 control->file.status_code |= INTERNAL_ERROR;
3590 return LIBPNG_ERROR_CODE;
3593 rc = setjmp(control->file.jmpbuf);
3594 if (rc == 0)
3596 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
3597 /* Remove any limits on the size of PNG files that can be read,
3598 * without this we may reject files based on built-in safety
3599 * limits.
3601 png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff);
3602 png_set_chunk_cache_max(png_ptr, 0);
3603 png_set_chunk_malloc_max(png_ptr, 0);
3604 # endif
3606 png_set_read_fn(png_ptr, control, read_callback);
3608 info_ptr = png_create_info_struct(png_ptr);
3609 if (info_ptr == NULL)
3610 png_error(png_ptr, "OOM allocating info structure");
3612 if (control->file.global->verbose)
3613 fprintf(stderr, " INFO\n");
3615 png_read_info(png_ptr, info_ptr);
3618 png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
3619 int passes = png_set_interlace_handling(png_ptr);
3620 int pass;
3622 png_start_read_image(png_ptr);
3624 for (pass = 0; pass < passes; ++pass)
3626 png_uint_32 y = height;
3628 /* NOTE: this skips asking libpng to return either version of
3629 * the image row, but libpng still reads the rows.
3631 while (y-- > 0)
3632 png_read_row(png_ptr, NULL, NULL);
3636 if (control->file.global->verbose)
3637 fprintf(stderr, " END\n");
3639 /* Make sure to read to the end of the file: */
3640 png_read_end(png_ptr, info_ptr);
3643 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
3644 return rc;
3647 static int
3648 one_file(struct global *global, const char *file_name, const char *out_name)
3650 int rc;
3651 struct control control;
3653 if (global->verbose)
3654 fprintf(stderr, "FILE %s -> %s\n", file_name,
3655 out_name ? out_name : "<none>");
3657 /* Although control_init can return a failure code the structure is always
3658 * initialized, so control_end can be used to accumulate any status codes.
3660 rc = control_init(&control, global, file_name, out_name);
3662 if (rc == 0)
3663 rc = read_png(&control);
3665 rc |= control_end(&control);
3667 return rc;
3670 static void
3671 usage(const char *prog)
3673 /* ANSI C-90 limits strings to 509 characters, so use a string array: */
3674 size_t i;
3675 static const char *usage_string[] = {
3676 " Tests, optimizes and optionally fixes the zlib header in PNG files.",
3677 " Optionally, when fixing, strips ancilliary chunks from the file.",
3679 "OPTIONS",
3680 " OPERATION",
3681 " By default files are just checked for readability with a summary of the",
3682 " of zlib issues founds for each compressed chunk and the IDAT stream in",
3683 " the file.",
3684 " --optimize (-o):",
3685 " Find the smallest deflate window size for the compressed data.",
3686 " --strip=[none|crc|unsafe|unused|transform|color|all]:",
3687 " none (default): Retain all chunks.",
3688 " crc: Remove chunks with a bad CRC.",
3689 " unsafe: Remove chunks that may be unsafe to retain if the image data",
3690 " is modified. This is set automatically if --max is given but",
3691 " may be cancelled by a later --strip=none.",
3692 " unused: Remove chunks not used by libpng when decoding an image.",
3693 " This retains any chunks that might be used by libpng image",
3694 " transformations.",
3695 " transform: unused+bKGD.",
3696 " color: transform+iCCP and cHRM.",
3697 " all: color+gAMA and sRGB.",
3698 " Only ancillary chunks are ever removed. In addition the tRNS and sBIT",
3699 " chunks are never removed as they affect exact interpretation of the",
3700 " image pixel values. The following known chunks are treated specially",
3701 " by the above options:",
3702 " gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
3703 " values.",
3704 " cHRM, iCCP [color]: These specify how colors are encoded. iCCP also",
3705 " specifies the exact encoding of a pixel value; however, in",
3706 " practice most programs will ignore it.",
3707 " bKGD [transform]: This is used by libpng transforms."
3708 " --max=<number>:",
3709 " Use IDAT chunks sized <number>. If no number is given the the IDAT",
3710 " chunks will be the maximum size permitted; 2^31-1 bytes. If the option",
3711 " is omitted the original chunk sizes will not be changed. When the",
3712 " option is given --strip=unsafe is set automatically. This may be",
3713 " cancelled if you know that all unknown unsafe-to-copy chunks really are",
3714 " safe to copy across an IDAT size change. This is true of all chunks",
3715 " that have ever been formally proposed as PNG extensions.",
3716 " MESSAGES",
3717 " By default the program only outputs summaries for each file.",
3718 " --quiet (-q):",
3719 " Do not output the summaries except for files that cannot be read. With",
3720 " two --quiets these are not output either.",
3721 " --errors (-e):",
3722 " Output errors from libpng and the program (except too-far-back).",
3723 " --warnings (-w):",
3724 " Output warnings from libpng.",
3725 " OUTPUT",
3726 " By default nothing is written.",
3727 " --out=<file>:",
3728 " Write the optimized/corrected version of the next PNG to <file>. This",
3729 " overrides the following two options",
3730 " --suffix=<suffix>:",
3731 " Set --out=<name><suffix> for all following files unless overridden on",
3732 " a per-file basis by explicit --out.",
3733 " --prefix=<prefix>:",
3734 " Set --out=<prefix><name> for all the following files unless overridden",
3735 " on a per-file basis by explicit --out.",
3736 " These two options can be used together to produce a suffix and prefix.",
3737 " INTERNAL OPTIONS",
3738 #if 0 /*NYI*/
3739 #ifdef PNG_MAXIMUM_INFLATE_WINDOW
3740 " --test:",
3741 " Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables",
3742 " output as this would produce a broken file.",
3743 #endif
3744 #endif
3746 "EXIT CODES",
3747 " *** SUBJECT TO CHANGE ***",
3748 " The program exit code is value in the range 0..127 holding a bit mask of",
3749 " the following codes. Notice that the results for each file are combined",
3750 " together - check one file at a time to get a meaningful error code!",
3751 " 0x01: The zlib too-far-back error existed in at least one chunk.",
3752 " 0x02: At least one chunk had a CRC error.",
3753 " 0x04: A chunk length was incorrect.",
3754 " 0x08: The file was truncated.",
3755 " Errors less than 16 are potentially recoverable, for a single file if the",
3756 " exit code is less than 16 the file could be read (with corrections if a",
3757 " non-zero code is returned).",
3758 " 0x10: The file could not be read, even with corrections.",
3759 " 0x20: The output file could not be written.",
3760 " 0x40: An unexpected, potentially internal, error occurred.",
3761 " If the command line arguments are incorrect the program exits with exit",
3762 " 255. Some older operating systems only support 7-bit exit codes, on those",
3763 " systems it is suggested that this program is first tested by supplying",
3764 " invalid arguments.",
3766 "DESCRIPTION",
3767 " " PROGRAM_NAME ":",
3768 " checks each PNG file on the command line for errors. By default errors are",
3769 " not output and the program just returns an exit code and prints a summary.",
3770 " With the --quiet (-q) option the summaries are suppressed too and the",
3771 " program only outputs unexpected errors (internal errors and file open",
3772 " errors).",
3773 " Various known problems in PNG files are fixed while the file is being read",
3774 " The exit code says what problems were fixed. In particular the zlib error:",
3776 " \"invalid distance too far back\"",
3778 " caused by an incorrect optimization of a zlib stream is fixed in any",
3779 " compressed chunk in which it is encountered. An integrity problem of the",
3780 " PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
3781 " is also fixed. Chunk CRC errors are automatically fixed up.",
3783 " Setting one of the \"OUTPUT\" options causes the possibly modified file to",
3784 " be written to a new file.",
3786 " Notice that some PNG files with the zlib optimization problem can still be",
3787 " read by libpng under some circumstances. This program will still detect",
3788 " and, if requested, correct the error.",
3790 " The program will reliably process all files on the command line unless",
3791 " either an invalid argument causes the usage message (this message) to be",
3792 " produced or the program crashes.",
3794 " The summary lines describe issues encountered with the zlib compressed",
3795 " stream of a chunk. They have the following format, which is SUBJECT TO",
3796 " CHANGE in the future:",
3798 " chunk reason comp-level p1 p2 p3 p4 file",
3800 " p1 through p4 vary according to the 'reason'. There are always 8 space",
3801 " separated fields. Reasons specific formats are:",
3803 " chunk ERR status code read-errno write-errno message file",
3804 " chunk SKP comp-level file-bits zlib-rc compressed message file",
3805 " chunk ??? comp-level file-bits ok-bits compressed uncompress file",
3807 " The various fields are",
3809 "$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem",
3810 " is reported by libpng at the start of the IDAT stream.",
3811 "$2 reason: One of:",
3812 " CHK: A zlib header checksum was detected and fixed.",
3813 " TFB: The zlib too far back error was detected and fixed.",
3814 " OK : No errors were detected in the zlib stream and optimization",
3815 " was not requested, or was not possible.",
3816 " OPT: The zlib stream window bits value could be improved (and was).",
3817 " SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
3818 " explanation 'message'",
3819 " ERR: The read of the file was aborted. The parameters explain why.",
3820 "$3 status: For 'ERR' the accumulated status code from 'EXIT CODES' above.",
3821 " This is printed as a 2 digit hexadecimal value",
3822 " comp-level: The recorded compression level (FLEVEL) of a zlib stream",
3823 " expressed as a string {supfast,stdfast,default,maximum}",
3824 "$4 code: The file exit code; where stop was called, as a fairly terse",
3825 " string {warning,libpng,zlib,invalid,read,write,unexpected}.",
3826 " file-bits: The zlib window bits recorded in the file.",
3827 "$5 read-errno: A system errno value from a read translated by strerror(3).",
3828 " zlib-rc: A zlib return code as a string (see zlib.h).",
3829 " ok-bits: The smallest zlib window bits value that works.",
3830 "$6 write-errno:A system errno value from a write translated by strerror(3).",
3831 " compressed: The count of compressed bytes in the zlib stream, when the",
3832 " reason is 'SKP'; this is a count of the bytes read from the",
3833 " stream when the fatal error was encountered.",
3834 "$7 message: An error message (spaces replaced by _, as in all parameters),",
3835 " uncompress: The count of bytes from uncompressing the zlib stream; this",
3836 " may not be the same as the number of bytes in the image.",
3837 "$8 file: The name of the file (this may contain spaces).",
3840 fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
3842 for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
3844 if (usage_string[i] != 0)
3845 fputs(usage_string[i], stderr);
3847 fputc('\n', stderr);
3850 exit(255);
3854 main(int argc, const char **argv)
3856 const char * prog = *argv;
3857 const char * outfile = NULL;
3858 const char * suffix = NULL;
3859 const char * prefix = NULL;
3860 int done = 0; /* if at least one file is processed */
3861 struct global global;
3863 global_init(&global);
3865 while (--argc > 0)
3867 ++argv;
3869 if (strcmp(*argv, "--debug") == 0)
3871 /* To help debugging problems: */
3872 global.errors = global.warnings = 1;
3873 global.quiet = 0;
3874 global.verbose = 7;
3877 else if (strncmp(*argv, "--max=", 6) == 0)
3879 global.idat_max = (png_uint_32)atol(6+*argv);
3881 if (global.skip < SKIP_UNSAFE)
3882 global.skip = SKIP_UNSAFE;
3885 else if (strcmp(*argv, "--max") == 0)
3887 global.idat_max = 0x7fffffff;
3889 if (global.skip < SKIP_UNSAFE)
3890 global.skip = SKIP_UNSAFE;
3893 else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
3894 global.optimize_zlib = 1;
3896 else if (strncmp(*argv, "--out=", 6) == 0)
3897 outfile = 6+*argv;
3899 else if (strncmp(*argv, "--suffix=", 9) == 0)
3900 suffix = 9+*argv;
3902 else if (strncmp(*argv, "--prefix=", 9) == 0)
3903 prefix = 9+*argv;
3905 else if (strcmp(*argv, "--strip=none") == 0)
3906 global.skip = SKIP_NONE;
3908 else if (strcmp(*argv, "--strip=crc") == 0)
3909 global.skip = SKIP_BAD_CRC;
3911 else if (strcmp(*argv, "--strip=unsafe") == 0)
3912 global.skip = SKIP_UNSAFE;
3914 else if (strcmp(*argv, "--strip=unused") == 0)
3915 global.skip = SKIP_UNUSED;
3917 else if (strcmp(*argv, "--strip=transform") == 0)
3918 global.skip = SKIP_TRANSFORM;
3920 else if (strcmp(*argv, "--strip=color") == 0)
3921 global.skip = SKIP_COLOR;
3923 else if (strcmp(*argv, "--strip=all") == 0)
3924 global.skip = SKIP_ALL;
3926 else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
3927 global.errors = 1;
3929 else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
3930 global.warnings = 1;
3932 else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
3934 if (global.quiet)
3935 global.quiet = 2;
3937 else
3938 global.quiet = 1;
3941 else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
3942 ++global.verbose;
3944 #if 0
3945 /* NYI */
3946 # ifdef PNG_MAXIMUM_INFLATE_WINDOW
3947 else if (strcmp(*argv, "--test") == 0)
3948 ++set_option;
3949 # endif
3950 #endif
3952 else if ((*argv)[0] == '-')
3953 usage(prog);
3955 else
3957 size_t outlen = strlen(*argv);
3958 char temp_name[FILENAME_MAX+1];
3960 if (outfile == NULL) /* else this takes precedence */
3962 /* Consider the prefix/suffix options */
3963 if (prefix != NULL)
3965 size_t prefixlen = strlen(prefix);
3967 if (prefixlen+outlen > FILENAME_MAX)
3969 fprintf(stderr, "%s: output file name too long: %s%s%s\n",
3970 prog, prefix, *argv, suffix ? suffix : "");
3971 global.status_code |= WRITE_ERROR;
3972 continue;
3975 memcpy(temp_name, prefix, prefixlen);
3976 memcpy(temp_name+prefixlen, *argv, outlen);
3977 outlen += prefixlen;
3978 outfile = temp_name;
3981 else if (suffix != NULL)
3982 memcpy(temp_name, *argv, outlen);
3984 temp_name[outlen] = 0;
3986 if (suffix != NULL)
3988 size_t suffixlen = strlen(suffix);
3990 if (outlen+suffixlen > FILENAME_MAX)
3992 fprintf(stderr, "%s: output file name too long: %s%s\n",
3993 prog, *argv, suffix);
3994 global.status_code |= WRITE_ERROR;
3995 continue;
3998 memcpy(temp_name+outlen, suffix, suffixlen);
3999 outlen += suffixlen;
4000 temp_name[outlen] = 0;
4001 outfile = temp_name;
4005 (void)one_file(&global, *argv, outfile);
4006 ++done;
4007 outfile = NULL;
4011 if (!done)
4012 usage(prog);
4014 return global_end(&global);
4017 #else /* ZLIB_VERNUM < 0x1240 */
4019 main(void)
4021 fprintf(stderr,
4022 "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n",
4023 ZLIB_VERNUM);
4024 return 77;
4026 #endif /* ZLIB_VERNUM */
4028 #else /* No read support */
4031 main(void)
4033 fprintf(stderr, "pngfix does not work without read support\n");
4034 return 77;
4036 #endif /* PNG_READ_SUPPORTED && PNG_EASY_ACCESS_SUPPORTED */
4037 #else /* No setjmp support */
4039 main(void)
4041 fprintf(stderr, "pngfix does not work without setjmp support\n");
4042 return 77;
4044 #endif /* PNG_SETJMP_SUPPORTED */