xref: /aosp_15_r20/external/libpng/contrib/libtests/pngvalid.c (revision a67afe4df73cf47866eedc69947994b8ff839aba)
1 
2 /* pngvalid.c - validate libpng by constructing then reading png files.
3  *
4  * Copyright (c) 2021 Cosmin Truta
5  * Copyright (c) 2014-2017 John Cunningham Bowler
6  *
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
10  *
11  * NOTES:
12  *   This is a C program that is intended to be linked against libpng.  It
13  *   generates bitmaps internally, stores them as PNG files (using the
14  *   sequential write code) then reads them back (using the sequential
15  *   read code) and validates that the result has the correct data.
16  *
17  *   The program can be modified and extended to test the correctness of
18  *   transformations performed by libpng.
19  */
20 
21 #define _POSIX_SOURCE 1
22 #define _ISOC99_SOURCE 1 /* For floating point */
23 #define _GNU_SOURCE 1 /* For the floating point exception extension */
24 #define _BSD_SOURCE 1 /* For the floating point exception extension */
25 #define _DEFAULT_SOURCE 1 /* For the floating point exception extension */
26 
27 #include <signal.h>
28 #include <stdio.h>
29 
30 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
31 #  include <config.h>
32 #endif
33 
34 #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
35 #  include <fenv.h>
36 #endif
37 
38 #ifndef FE_DIVBYZERO
39 #  define FE_DIVBYZERO 0
40 #endif
41 #ifndef FE_INVALID
42 #  define FE_INVALID 0
43 #endif
44 #ifndef FE_OVERFLOW
45 #  define FE_OVERFLOW 0
46 #endif
47 
48 /* Define the following to use this test against your installed libpng, rather
49  * than the one being built here:
50  */
51 #ifdef PNG_FREESTANDING_TESTS
52 #  include <png.h>
53 #else
54 #  include "../../png.h"
55 #endif
56 
57 #ifdef PNG_ZLIB_HEADER
58 #  include PNG_ZLIB_HEADER
59 #else
60 #  include <zlib.h>   /* For crc32 */
61 #endif
62 
63 /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
64  * a skipped test, in earlier versions we need to succeed on a skipped test, so:
65  */
66 #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
67 #  define SKIP 77
68 #else
69 #  define SKIP 0
70 #endif
71 
72 /* pngvalid requires write support and one of the fixed or floating point APIs.
73  * progressive read is also required currently as the progressive read pointer
74  * is used to record the 'display' structure.
75  */
76 #if defined PNG_WRITE_SUPPORTED &&\
77    (defined PNG_PROGRESSIVE_READ_SUPPORTED) &&\
78    (defined PNG_FIXED_POINT_SUPPORTED || defined PNG_FLOATING_POINT_SUPPORTED)
79 
80 #if PNG_LIBPNG_VER < 10500
81 /* This deliberately lacks the const. */
82 typedef png_byte *png_const_bytep;
83 
84 /* This is copied from 1.5.1 png.h: */
85 #define PNG_INTERLACE_ADAM7_PASSES 7
86 #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
87 #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
88 #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
89 #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
90 #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
91    -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
92 #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
93    -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
94 #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
95    (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
96 #define PNG_COL_FROM_PASS_COL(xIn, pass) \
97    (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
98 #define PNG_PASS_MASK(pass,off) ( \
99    ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
100    ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
101 #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
102    ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
103 #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
104    ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
105 
106 /* These are needed too for the default build: */
107 #define PNG_WRITE_16BIT_SUPPORTED
108 #define PNG_READ_16BIT_SUPPORTED
109 
110 /* This comes from pnglibconf.h after 1.5: */
111 #define PNG_FP_1 100000
112 #define PNG_GAMMA_THRESHOLD_FIXED\
113    ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
114 #endif
115 
116 #if PNG_LIBPNG_VER < 10600
117    /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
118     * compiled against earlier versions.
119     */
120 #  define png_const_structp png_structp
121 #endif
122 
123 #ifndef RELEASE_BUILD
124    /* RELEASE_BUILD is true for releases and release candidates: */
125 #  define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
126 #endif
127 #if RELEASE_BUILD
128 #   define debugonly(something)
129 #else /* !RELEASE_BUILD */
130 #   define debugonly(something) something
131 #endif /* !RELEASE_BUILD */
132 
133 #include <float.h>  /* For floating point constants */
134 #include <stdlib.h> /* For malloc */
135 #include <string.h> /* For memcpy, memset */
136 #include <math.h>   /* For floor */
137 
138 /* Convenience macros. */
139 #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
140 #define CHUNK_IHDR CHUNK(73,72,68,82)
141 #define CHUNK_PLTE CHUNK(80,76,84,69)
142 #define CHUNK_IDAT CHUNK(73,68,65,84)
143 #define CHUNK_IEND CHUNK(73,69,78,68)
144 #define CHUNK_cHRM CHUNK(99,72,82,77)
145 #define CHUNK_gAMA CHUNK(103,65,77,65)
146 #define CHUNK_sBIT CHUNK(115,66,73,84)
147 #define CHUNK_sRGB CHUNK(115,82,71,66)
148 
149 /* Unused formal parameter errors are removed using the following macro which is
150  * expected to have no bad effects on performance.
151  */
152 #ifndef UNUSED
153 #  if defined(__GNUC__) || defined(_MSC_VER)
154 #     define UNUSED(param) (void)param;
155 #  else
156 #     define UNUSED(param)
157 #  endif
158 #endif
159 
160 /***************************** EXCEPTION HANDLING *****************************/
161 #ifdef PNG_FREESTANDING_TESTS
162 #  include <cexcept.h>
163 #else
164 #  include "../visupng/cexcept.h"
165 #endif
166 
167 #ifdef __cplusplus
168 #  define this not_the_cpp_this
169 #  define new not_the_cpp_new
170 #  define voidcast(type, value) static_cast<type>(value)
171 #else
172 #  define voidcast(type, value) (value)
173 #endif /* __cplusplus */
174 
175 struct png_store;
176 define_exception_type(struct png_store*);
177 
178 /* The following are macros to reduce typing everywhere where the well known
179  * name 'the_exception_context' must be defined.
180  */
181 #define anon_context(ps) struct exception_context *the_exception_context = \
182    &(ps)->exception_context
183 #define context(ps,fault) anon_context(ps); png_store *fault
184 
185 /* This macro returns the number of elements in an array as an (unsigned int),
186  * it is necessary to avoid the inability of certain versions of GCC to use
187  * the value of a compile-time constant when performing range checks.  It must
188  * be passed an array name.
189  */
190 #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
191 
192 /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
193  * some broken GCC versions to be fixed up to avoid invalid whining about auto
194  * variables that are *not* changed within the scope of a setjmp being changed.
195  *
196  * Feel free to extend the list of broken versions.
197  */
198 #define is_gnu(major,minor)\
199    (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
200 #define is_gnu_patch(major,minor,patch)\
201    is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
202 /* For the moment just do it always; all versions of GCC seem to be broken: */
203 #ifdef __GNUC__
204    const void * volatile make_volatile_for_gnu;
205 #  define gnu_volatile(x) make_volatile_for_gnu = &x;
206 #else /* !GNUC broken versions */
207 #  define gnu_volatile(x)
208 #endif /* !GNUC broken versions */
209 
210 /******************************* UTILITIES ************************************/
211 /* Error handling is particularly problematic in production code - error
212  * handlers often themselves have bugs which lead to programs that detect
213  * minor errors crashing.  The following functions deal with one very
214  * common class of errors in error handlers - attempting to format error or
215  * warning messages into buffers that are too small.
216  */
safecat(char * buffer,size_t bufsize,size_t pos,const char * cat)217 static size_t safecat(char *buffer, size_t bufsize, size_t pos,
218    const char *cat)
219 {
220    while (pos < bufsize && cat != NULL && *cat != 0)
221       buffer[pos++] = *cat++;
222 
223    if (pos >= bufsize)
224       pos = bufsize-1;
225 
226    buffer[pos] = 0;
227    return pos;
228 }
229 
safecatn(char * buffer,size_t bufsize,size_t pos,int n)230 static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
231 {
232    char number[64];
233    sprintf(number, "%d", n);
234    return safecat(buffer, bufsize, pos, number);
235 }
236 
237 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
safecatd(char * buffer,size_t bufsize,size_t pos,double d,int precision)238 static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
239     int precision)
240 {
241    char number[64];
242    sprintf(number, "%.*f", precision, d);
243    return safecat(buffer, bufsize, pos, number);
244 }
245 #endif
246 
247 static const char invalid[] = "invalid";
248 static const char sep[] = ": ";
249 
250 static const char *colour_types[8] =
251 {
252    "grayscale", invalid, "truecolour", "indexed-colour",
253    "grayscale with alpha", invalid, "truecolour with alpha", invalid
254 };
255 
256 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
257 /* Convert a double precision value to fixed point. */
258 static png_fixed_point
fix(double d)259 fix(double d)
260 {
261    d = floor(d * PNG_FP_1 + .5);
262    return (png_fixed_point)d;
263 }
264 #endif /* PNG_READ_SUPPORTED */
265 
266 /* Generate random bytes.  This uses a boring repeatable algorithm and it
267  * is implemented here so that it gives the same set of numbers on every
268  * architecture.  It's a linear congruential generator (Knuth or Sedgewick
269  * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
270  * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
271  * Generation.)
272  */
273 static void
make_random_bytes(png_uint_32 * seed,void * pv,size_t size)274 make_random_bytes(png_uint_32* seed, void* pv, size_t size)
275 {
276    png_uint_32 u0 = seed[0], u1 = seed[1];
277    png_bytep bytes = voidcast(png_bytep, pv);
278 
279    /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
280     * bit-20.  The top 1 bit is in u1, the bottom 32 are in u0.
281     */
282    size_t i;
283    for (i=0; i<size; ++i)
284    {
285       /* First generate 8 new bits then shift them in at the end. */
286       png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
287       u1 <<= 8;
288       u1 |= u0 >> 24;
289       u0 <<= 8;
290       u0 |= u;
291       *bytes++ = (png_byte)u;
292    }
293 
294    seed[0] = u0;
295    seed[1] = u1;
296 }
297 
298 static void
make_four_random_bytes(png_uint_32 * seed,png_bytep bytes)299 make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
300 {
301    make_random_bytes(seed, bytes, 4);
302 }
303 
304 #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\
305     defined PNG_WRITE_FILTER_SUPPORTED
306 static void
randomize(void * pv,size_t size)307 randomize(void *pv, size_t size)
308 {
309    static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
310    make_random_bytes(random_seed, pv, size);
311 }
312 
313 #define R8(this) randomize(&(this), sizeof (this))
314 
315 #ifdef PNG_READ_SUPPORTED
316 static png_byte
random_byte(void)317 random_byte(void)
318 {
319    unsigned char b1[1];
320    randomize(b1, sizeof b1);
321    return b1[0];
322 }
323 #endif /* READ */
324 
325 static png_uint_16
random_u16(void)326 random_u16(void)
327 {
328    unsigned char b2[2];
329    randomize(b2, sizeof b2);
330    return png_get_uint_16(b2);
331 }
332 
333 #if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\
334     defined PNG_READ_FILLER_SUPPORTED
335 static png_uint_32
random_u32(void)336 random_u32(void)
337 {
338    unsigned char b4[4];
339    randomize(b4, sizeof b4);
340    return png_get_uint_32(b4);
341 }
342 #endif /* READ_FILLER || READ_RGB_TO_GRAY */
343 
344 #endif /* READ || WRITE_tRNS || WRITE_FILTER */
345 
346 #if defined PNG_READ_TRANSFORMS_SUPPORTED ||\
347     defined PNG_WRITE_FILTER_SUPPORTED
348 static unsigned int
random_mod(unsigned int max)349 random_mod(unsigned int max)
350 {
351    return random_u16() % max; /* 0 .. max-1 */
352 }
353 #endif /* READ_TRANSFORMS || WRITE_FILTER */
354 
355 #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
356     (defined PNG_READ_FILLER_SUPPORTED)
357 static int
random_choice(void)358 random_choice(void)
359 {
360    return random_byte() & 1;
361 }
362 #endif /* READ_RGB_TO_GRAY || READ_FILLER */
363 
364 /* A numeric ID based on PNG file characteristics.  The 'do_interlace' field
365  * simply records whether pngvalid did the interlace itself or whether it
366  * was done by libpng.  Width and height must be less than 256.  'palette' is an
367  * index of the palette to use for formats with a palette otherwise a boolean
368  * indicating if a tRNS chunk was generated.
369  */
370 #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
371    ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
372     (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
373 
374 #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
375 #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
376 #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
377 #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
378 #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
379 #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
380 #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
381 
382 /* Utility to construct a standard name for a standard image. */
383 static size_t
standard_name(char * buffer,size_t bufsize,size_t pos,png_byte colour_type,int bit_depth,unsigned int npalette,int interlace_type,png_uint_32 w,png_uint_32 h,int do_interlace)384 standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
385     int bit_depth, unsigned int npalette, int interlace_type,
386     png_uint_32 w, png_uint_32 h, int do_interlace)
387 {
388    pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
389    if (colour_type == 3) /* must have a palette */
390    {
391       pos = safecat(buffer, bufsize, pos, "[");
392       pos = safecatn(buffer, bufsize, pos, npalette);
393       pos = safecat(buffer, bufsize, pos, "]");
394    }
395 
396    else if (npalette != 0)
397       pos = safecat(buffer, bufsize, pos, "+tRNS");
398 
399    pos = safecat(buffer, bufsize, pos, " ");
400    pos = safecatn(buffer, bufsize, pos, bit_depth);
401    pos = safecat(buffer, bufsize, pos, " bit");
402 
403    if (interlace_type != PNG_INTERLACE_NONE)
404    {
405       pos = safecat(buffer, bufsize, pos, " interlaced");
406       if (do_interlace)
407          pos = safecat(buffer, bufsize, pos, "(pngvalid)");
408       else
409          pos = safecat(buffer, bufsize, pos, "(libpng)");
410    }
411 
412    if (w > 0 || h > 0)
413    {
414       pos = safecat(buffer, bufsize, pos, " ");
415       pos = safecatn(buffer, bufsize, pos, w);
416       pos = safecat(buffer, bufsize, pos, "x");
417       pos = safecatn(buffer, bufsize, pos, h);
418    }
419 
420    return pos;
421 }
422 
423 static size_t
standard_name_from_id(char * buffer,size_t bufsize,size_t pos,png_uint_32 id)424 standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
425 {
426    return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
427       DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
428       WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
429 }
430 
431 /* Convenience API and defines to list valid formats.  Note that 16 bit read and
432  * write support is required to do 16 bit read tests (we must be able to make a
433  * 16 bit image to test!)
434  */
435 #ifdef PNG_WRITE_16BIT_SUPPORTED
436 #  define WRITE_BDHI 4
437 #  ifdef PNG_READ_16BIT_SUPPORTED
438 #     define READ_BDHI 4
439 #     define DO_16BIT
440 #  endif
441 #else
442 #  define WRITE_BDHI 3
443 #endif
444 #ifndef DO_16BIT
445 #  define READ_BDHI 3
446 #endif
447 
448 /* The following defines the number of different palettes to generate for
449  * each log bit depth of a colour type 3 standard image.
450  */
451 #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
452 
453 static int
next_format(png_bytep colour_type,png_bytep bit_depth,unsigned int * palette_number,int low_depth_gray,int tRNS)454 next_format(png_bytep colour_type, png_bytep bit_depth,
455    unsigned int* palette_number, int low_depth_gray, int tRNS)
456 {
457    if (*bit_depth == 0)
458    {
459       *colour_type = 0;
460       if (low_depth_gray)
461          *bit_depth = 1;
462       else
463          *bit_depth = 8;
464       *palette_number = 0;
465       return 1;
466    }
467 
468    if  (*colour_type < 4/*no alpha channel*/)
469    {
470       /* Add multiple palettes for colour type 3, one image with tRNS
471        * and one without for other non-alpha formats:
472        */
473       unsigned int pn = ++*palette_number;
474       png_byte ct = *colour_type;
475 
476       if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
477           (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
478          return 1;
479 
480       /* No: next bit depth */
481       *palette_number = 0;
482    }
483 
484    *bit_depth = (png_byte)(*bit_depth << 1);
485 
486    /* Palette images are restricted to 8 bit depth */
487    if (*bit_depth <= 8
488 #ifdef DO_16BIT
489          || (*colour_type != 3 && *bit_depth <= 16)
490 #endif
491       )
492       return 1;
493 
494    /* Move to the next color type, or return 0 at the end. */
495    switch (*colour_type)
496    {
497       case 0:
498          *colour_type = 2;
499          *bit_depth = 8;
500          return 1;
501 
502       case 2:
503          *colour_type = 3;
504          *bit_depth = 1;
505          return 1;
506 
507       case 3:
508          *colour_type = 4;
509          *bit_depth = 8;
510          return 1;
511 
512       case 4:
513          *colour_type = 6;
514          *bit_depth = 8;
515          return 1;
516 
517       default:
518          return 0;
519    }
520 }
521 
522 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
523 static unsigned int
sample(png_const_bytep row,png_byte colour_type,png_byte bit_depth,png_uint_32 x,unsigned int sample_index,int swap16,int littleendian)524 sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
525     png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
526 {
527    png_uint_32 bit_index, result;
528 
529    /* Find a sample index for the desired sample: */
530    x *= bit_depth;
531    bit_index = x;
532 
533    if ((colour_type & 1) == 0) /* !palette */
534    {
535       if (colour_type & 2)
536          bit_index *= 3;
537 
538       if (colour_type & 4)
539          bit_index += x; /* Alpha channel */
540 
541       /* Multiple channels; select one: */
542       if (colour_type & (2+4))
543          bit_index += sample_index * bit_depth;
544    }
545 
546    /* Return the sample from the row as an integer. */
547    row += bit_index >> 3;
548    result = *row;
549 
550    if (bit_depth == 8)
551       return result;
552 
553    else if (bit_depth > 8)
554    {
555       if (swap16)
556          return (*++row << 8) + result;
557       else
558          return (result << 8) + *++row;
559    }
560 
561    /* Less than 8 bits per sample.  By default PNG has the big end of
562     * the egg on the left of the screen, but if littleendian is set
563     * then the big end is on the right.
564     */
565    bit_index &= 7;
566 
567    if (!littleendian)
568       bit_index = 8-bit_index-bit_depth;
569 
570    return (result >> bit_index) & ((1U<<bit_depth)-1);
571 }
572 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
573 
574 /* Copy a single pixel, of a given size, from one buffer to another -
575  * while this is basically bit addressed there is an implicit assumption
576  * that pixels 8 or more bits in size are byte aligned and that pixels
577  * do not otherwise cross byte boundaries.  (This is, so far as I know,
578  * universally true in bitmap computer graphics.  [JCB 20101212])
579  *
580  * NOTE: The to and from buffers may be the same.
581  */
582 static void
pixel_copy(png_bytep toBuffer,png_uint_32 toIndex,png_const_bytep fromBuffer,png_uint_32 fromIndex,unsigned int pixelSize,int littleendian)583 pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
584    png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
585    int littleendian)
586 {
587    /* Assume we can multiply by 'size' without overflow because we are
588     * just working in a single buffer.
589     */
590    toIndex *= pixelSize;
591    fromIndex *= pixelSize;
592    if (pixelSize < 8) /* Sub-byte */
593    {
594       /* Mask to select the location of the copied pixel: */
595       unsigned int destMask = ((1U<<pixelSize)-1) <<
596          (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
597       /* The following read the entire pixels and clears the extra: */
598       unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
599       unsigned int sourceByte = fromBuffer[fromIndex >> 3];
600 
601       /* Don't rely on << or >> supporting '0' here, just in case: */
602       fromIndex &= 7;
603       if (littleendian)
604       {
605          if (fromIndex > 0) sourceByte >>= fromIndex;
606          if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
607       }
608 
609       else
610       {
611          if (fromIndex > 0) sourceByte <<= fromIndex;
612          if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
613       }
614 
615       toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
616    }
617    else /* One or more bytes */
618       memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
619 }
620 
621 #ifdef PNG_READ_SUPPORTED
622 /* Copy a complete row of pixels, taking into account potential partial
623  * bytes at the end.
624  */
625 static void
row_copy(png_bytep toBuffer,png_const_bytep fromBuffer,unsigned int bitWidth,int littleendian)626 row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
627       int littleendian)
628 {
629    memcpy(toBuffer, fromBuffer, bitWidth >> 3);
630 
631    if ((bitWidth & 7) != 0)
632    {
633       unsigned int mask;
634 
635       toBuffer += bitWidth >> 3;
636       fromBuffer += bitWidth >> 3;
637       if (littleendian)
638          mask = 0xff << (bitWidth & 7);
639       else
640          mask = 0xff >> (bitWidth & 7);
641       *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
642    }
643 }
644 
645 /* Compare pixels - they are assumed to start at the first byte in the
646  * given buffers.
647  */
648 static int
pixel_cmp(png_const_bytep pa,png_const_bytep pb,png_uint_32 bit_width)649 pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
650 {
651 #if PNG_LIBPNG_VER < 10506
652    if (memcmp(pa, pb, bit_width>>3) == 0)
653    {
654       png_uint_32 p;
655 
656       if ((bit_width & 7) == 0) return 0;
657 
658       /* Ok, any differences? */
659       p = pa[bit_width >> 3];
660       p ^= pb[bit_width >> 3];
661 
662       if (p == 0) return 0;
663 
664       /* There are, but they may not be significant, remove the bits
665        * after the end (the low order bits in PNG.)
666        */
667       bit_width &= 7;
668       p >>= 8-bit_width;
669 
670       if (p == 0) return 0;
671    }
672 #else
673    /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
674     * bits too:
675     */
676    if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
677       return 0;
678 #endif
679 
680    /* Return the index of the changed byte. */
681    {
682       png_uint_32 where = 0;
683 
684       while (pa[where] == pb[where]) ++where;
685       return 1+where;
686    }
687 }
688 #endif /* PNG_READ_SUPPORTED */
689 
690 /*************************** BASIC PNG FILE WRITING ***************************/
691 /* A png_store takes data from the sequential writer or provides data
692  * to the sequential reader.  It can also store the result of a PNG
693  * write for later retrieval.
694  */
695 #define STORE_BUFFER_SIZE 500 /* arbitrary */
696 typedef struct png_store_buffer
697 {
698    struct png_store_buffer*  prev;    /* NOTE: stored in reverse order */
699    png_byte                  buffer[STORE_BUFFER_SIZE];
700 } png_store_buffer;
701 
702 #define FILE_NAME_SIZE 64
703 
704 typedef struct store_palette_entry /* record of a single palette entry */
705 {
706    png_byte red;
707    png_byte green;
708    png_byte blue;
709    png_byte alpha;
710 } store_palette_entry, store_palette[256];
711 
712 typedef struct png_store_file
713 {
714    struct png_store_file*  next;      /* as many as you like... */
715    char                    name[FILE_NAME_SIZE];
716    unsigned int            IDAT_bits; /* Number of bits in IDAT size */
717    png_uint_32             IDAT_size; /* Total size of IDAT data */
718    png_uint_32             id;        /* must be correct (see FILEID) */
719    size_t                  datacount; /* In this (the last) buffer */
720    png_store_buffer        data;      /* Last buffer in file */
721    int                     npalette;  /* Number of entries in palette */
722    store_palette_entry*    palette;   /* May be NULL */
723 } png_store_file;
724 
725 /* The following is a pool of memory allocated by a single libpng read or write
726  * operation.
727  */
728 typedef struct store_pool
729 {
730    struct png_store    *store;   /* Back pointer */
731    struct store_memory *list;    /* List of allocated memory */
732    png_byte             mark[4]; /* Before and after data */
733 
734    /* Statistics for this run. */
735    png_alloc_size_t     max;     /* Maximum single allocation */
736    png_alloc_size_t     current; /* Current allocation */
737    png_alloc_size_t     limit;   /* Highest current allocation */
738    png_alloc_size_t     total;   /* Total allocation */
739 
740    /* Overall statistics (retained across successive runs). */
741    png_alloc_size_t     max_max;
742    png_alloc_size_t     max_limit;
743    png_alloc_size_t     max_total;
744 } store_pool;
745 
746 typedef struct png_store
747 {
748    /* For cexcept.h exception handling - simply store one of these;
749     * the context is a self pointer but it may point to a different
750     * png_store (in fact it never does in this program.)
751     */
752    struct exception_context
753                       exception_context;
754 
755    unsigned int       verbose :1;
756    unsigned int       treat_warnings_as_errors :1;
757    unsigned int       expect_error :1;
758    unsigned int       expect_warning :1;
759    unsigned int       saw_warning :1;
760    unsigned int       speed :1;
761    unsigned int       progressive :1; /* use progressive read */
762    unsigned int       validated :1;   /* used as a temporary flag */
763    int                nerrors;
764    int                nwarnings;
765    int                noptions;       /* number of options below: */
766    struct {
767       unsigned char   option;         /* option number, 0..30 */
768       unsigned char   setting;        /* setting (unset,invalid,on,off) */
769    }                  options[16];
770    char               test[128];      /* Name of test */
771    char               error[256];
772 
773    /* Share fields */
774    png_uint_32        chunklen; /* Length of chunk+overhead (chunkpos >= 8) */
775    png_uint_32        chunktype;/* Type of chunk (valid if chunkpos >= 4) */
776    png_uint_32        chunkpos; /* Position in chunk */
777    png_uint_32        IDAT_size;/* Accumulated IDAT size in .new */
778    unsigned int       IDAT_bits;/* Cache of the file store value */
779 
780    /* Read fields */
781    png_structp        pread;    /* Used to read a saved file */
782    png_infop          piread;
783    png_store_file*    current;  /* Set when reading */
784    png_store_buffer*  next;     /* Set when reading */
785    size_t             readpos;  /* Position in *next */
786    png_byte*          image;    /* Buffer for reading interlaced images */
787    size_t             cb_image; /* Size of this buffer */
788    size_t             cb_row;   /* Row size of the image(s) */
789    uLong              IDAT_crc;
790    png_uint_32        IDAT_len; /* Used when re-chunking IDAT chunks */
791    png_uint_32        IDAT_pos; /* Used when re-chunking IDAT chunks */
792    png_uint_32        image_h;  /* Number of rows in a single image */
793    store_pool         read_memory_pool;
794 
795    /* Write fields */
796    png_store_file*    saved;
797    png_structp        pwrite;   /* Used when writing a new file */
798    png_infop          piwrite;
799    size_t             writepos; /* Position in .new */
800    char               wname[FILE_NAME_SIZE];
801    png_store_buffer   new;      /* The end of the new PNG file being written. */
802    store_pool         write_memory_pool;
803    store_palette_entry* palette;
804    int                  npalette;
805 } png_store;
806 
807 /* Initialization and cleanup */
808 static void
store_pool_mark(png_bytep mark)809 store_pool_mark(png_bytep mark)
810 {
811    static png_uint_32 store_seed[2] = { 0x12345678, 1};
812 
813    make_four_random_bytes(store_seed, mark);
814 }
815 
816 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
817 /* Use this for random 32 bit values; this function makes sure the result is
818  * non-zero.
819  */
820 static png_uint_32
random_32(void)821 random_32(void)
822 {
823 
824    for (;;)
825    {
826       png_byte mark[4];
827       png_uint_32 result;
828 
829       store_pool_mark(mark);
830       result = png_get_uint_32(mark);
831 
832       if (result != 0)
833          return result;
834    }
835 }
836 #endif /* PNG_READ_SUPPORTED */
837 
838 static void
store_pool_init(png_store * ps,store_pool * pool)839 store_pool_init(png_store *ps, store_pool *pool)
840 {
841    memset(pool, 0, sizeof *pool);
842 
843    pool->store = ps;
844    pool->list = NULL;
845    pool->max = pool->current = pool->limit = pool->total = 0;
846    pool->max_max = pool->max_limit = pool->max_total = 0;
847    store_pool_mark(pool->mark);
848 }
849 
850 static void
store_init(png_store * ps)851 store_init(png_store* ps)
852 {
853    memset(ps, 0, sizeof *ps);
854    init_exception_context(&ps->exception_context);
855    store_pool_init(ps, &ps->read_memory_pool);
856    store_pool_init(ps, &ps->write_memory_pool);
857    ps->verbose = 0;
858    ps->treat_warnings_as_errors = 0;
859    ps->expect_error = 0;
860    ps->expect_warning = 0;
861    ps->saw_warning = 0;
862    ps->speed = 0;
863    ps->progressive = 0;
864    ps->validated = 0;
865    ps->nerrors = ps->nwarnings = 0;
866    ps->pread = NULL;
867    ps->piread = NULL;
868    ps->saved = ps->current = NULL;
869    ps->next = NULL;
870    ps->readpos = 0;
871    ps->image = NULL;
872    ps->cb_image = 0;
873    ps->cb_row = 0;
874    ps->image_h = 0;
875    ps->pwrite = NULL;
876    ps->piwrite = NULL;
877    ps->writepos = 0;
878    ps->chunkpos = 8;
879    ps->chunktype = 0;
880    ps->chunklen = 16;
881    ps->IDAT_size = 0;
882    ps->IDAT_bits = 0;
883    ps->new.prev = NULL;
884    ps->palette = NULL;
885    ps->npalette = 0;
886    ps->noptions = 0;
887 }
888 
889 static void
store_freebuffer(png_store_buffer * psb)890 store_freebuffer(png_store_buffer* psb)
891 {
892    if (psb->prev)
893    {
894       store_freebuffer(psb->prev);
895       free(psb->prev);
896       psb->prev = NULL;
897    }
898 }
899 
900 static void
store_freenew(png_store * ps)901 store_freenew(png_store *ps)
902 {
903    store_freebuffer(&ps->new);
904    ps->writepos = 0;
905    ps->chunkpos = 8;
906    ps->chunktype = 0;
907    ps->chunklen = 16;
908    ps->IDAT_size = 0;
909    ps->IDAT_bits = 0;
910    if (ps->palette != NULL)
911    {
912       free(ps->palette);
913       ps->palette = NULL;
914       ps->npalette = 0;
915    }
916 }
917 
918 static void
store_storenew(png_store * ps)919 store_storenew(png_store *ps)
920 {
921    png_store_buffer *pb;
922 
923    pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
924 
925    if (pb == NULL)
926       png_error(ps->pwrite, "store new: OOM");
927 
928    *pb = ps->new;
929    ps->new.prev = pb;
930    ps->writepos = 0;
931 }
932 
933 static void
store_freefile(png_store_file ** ppf)934 store_freefile(png_store_file **ppf)
935 {
936    if (*ppf != NULL)
937    {
938       store_freefile(&(*ppf)->next);
939 
940       store_freebuffer(&(*ppf)->data);
941       (*ppf)->datacount = 0;
942       if ((*ppf)->palette != NULL)
943       {
944          free((*ppf)->palette);
945          (*ppf)->palette = NULL;
946          (*ppf)->npalette = 0;
947       }
948       free(*ppf);
949       *ppf = NULL;
950    }
951 }
952 
953 static unsigned int
bits_of(png_uint_32 num)954 bits_of(png_uint_32 num)
955 {
956    /* Return the number of bits in 'num' */
957    unsigned int b = 0;
958 
959    if (num & 0xffff0000U)  b += 16U, num >>= 16;
960    if (num & 0xff00U)      b += 8U, num >>= 8;
961    if (num & 0xf0U)        b += 4U, num >>= 4;
962    if (num & 0xcU)         b += 2U, num >>= 2;
963    if (num & 0x2U)         ++b, num >>= 1;
964    if (num)                ++b;
965 
966    return b; /* 0..32 */
967 }
968 
969 /* Main interface to file storage, after writing a new PNG file (see the API
970  * below) call store_storefile to store the result with the given name and id.
971  */
972 static void
store_storefile(png_store * ps,png_uint_32 id)973 store_storefile(png_store *ps, png_uint_32 id)
974 {
975    png_store_file *pf;
976 
977    if (ps->chunkpos != 0U || ps->chunktype != 0U || ps->chunklen != 0U ||
978        ps->IDAT_size == 0)
979       png_error(ps->pwrite, "storefile: incomplete write");
980 
981    pf = voidcast(png_store_file*, malloc(sizeof *pf));
982    if (pf == NULL)
983       png_error(ps->pwrite, "storefile: OOM");
984    safecat(pf->name, sizeof pf->name, 0, ps->wname);
985    pf->id = id;
986    pf->data = ps->new;
987    pf->datacount = ps->writepos;
988    pf->IDAT_size = ps->IDAT_size;
989    pf->IDAT_bits = bits_of(ps->IDAT_size);
990    /* Because the IDAT always has zlib header stuff this must be true: */
991    if (pf->IDAT_bits == 0U)
992       png_error(ps->pwrite, "storefile: 0 sized IDAT");
993    ps->new.prev = NULL;
994    ps->writepos = 0;
995    ps->chunkpos = 8;
996    ps->chunktype = 0;
997    ps->chunklen = 16;
998    ps->IDAT_size = 0;
999    pf->palette = ps->palette;
1000    pf->npalette = ps->npalette;
1001    ps->palette = 0;
1002    ps->npalette = 0;
1003 
1004    /* And save it. */
1005    pf->next = ps->saved;
1006    ps->saved = pf;
1007 }
1008 
1009 /* Generate an error message (in the given buffer) */
1010 static size_t
store_message(png_store * ps,png_const_structp pp,char * buffer,size_t bufsize,size_t pos,const char * msg)1011 store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
1012    size_t pos, const char *msg)
1013 {
1014    if (pp != NULL && pp == ps->pread)
1015    {
1016       /* Reading a file */
1017       pos = safecat(buffer, bufsize, pos, "read: ");
1018 
1019       if (ps->current != NULL)
1020       {
1021          pos = safecat(buffer, bufsize, pos, ps->current->name);
1022          pos = safecat(buffer, bufsize, pos, sep);
1023       }
1024    }
1025 
1026    else if (pp != NULL && pp == ps->pwrite)
1027    {
1028       /* Writing a file */
1029       pos = safecat(buffer, bufsize, pos, "write: ");
1030       pos = safecat(buffer, bufsize, pos, ps->wname);
1031       pos = safecat(buffer, bufsize, pos, sep);
1032    }
1033 
1034    else
1035    {
1036       /* Neither reading nor writing (or a memory error in struct delete) */
1037       pos = safecat(buffer, bufsize, pos, "pngvalid: ");
1038    }
1039 
1040    if (ps->test[0] != 0)
1041    {
1042       pos = safecat(buffer, bufsize, pos, ps->test);
1043       pos = safecat(buffer, bufsize, pos, sep);
1044    }
1045    pos = safecat(buffer, bufsize, pos, msg);
1046    return pos;
1047 }
1048 
1049 /* Verbose output to the error stream: */
1050 static void
store_verbose(png_store * ps,png_const_structp pp,png_const_charp prefix,png_const_charp message)1051 store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
1052    png_const_charp message)
1053 {
1054    char buffer[512];
1055 
1056    if (prefix)
1057       fputs(prefix, stderr);
1058 
1059    (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
1060    fputs(buffer, stderr);
1061    fputc('\n', stderr);
1062 }
1063 
1064 /* Log an error or warning - the relevant count is always incremented. */
1065 static void
store_log(png_store * ps,png_const_structp pp,png_const_charp message,int is_error)1066 store_log(png_store* ps, png_const_structp pp, png_const_charp message,
1067    int is_error)
1068 {
1069    /* The warning is copied to the error buffer if there are no errors and it is
1070     * the first warning.  The error is copied to the error buffer if it is the
1071     * first error (overwriting any prior warnings).
1072     */
1073    if (is_error ? (ps->nerrors)++ == 0 :
1074        (ps->nwarnings)++ == 0 && ps->nerrors == 0)
1075       store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
1076 
1077    if (ps->verbose)
1078       store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
1079 }
1080 
1081 #ifdef PNG_READ_SUPPORTED
1082 /* Internal error function, called with a png_store but no libpng stuff. */
1083 static void
internal_error(png_store * ps,png_const_charp message)1084 internal_error(png_store *ps, png_const_charp message)
1085 {
1086    store_log(ps, NULL, message, 1 /* error */);
1087 
1088    /* And finally throw an exception. */
1089    {
1090       struct exception_context *the_exception_context = &ps->exception_context;
1091       Throw ps;
1092    }
1093 }
1094 #endif /* PNG_READ_SUPPORTED */
1095 
1096 /* Functions to use as PNG callbacks. */
1097 static void PNGCBAPI
store_error(png_structp ppIn,png_const_charp message)1098 store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
1099 {
1100    png_const_structp pp = ppIn;
1101    png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1102 
1103    if (!ps->expect_error)
1104       store_log(ps, pp, message, 1 /* error */);
1105 
1106    /* And finally throw an exception. */
1107    {
1108       struct exception_context *the_exception_context = &ps->exception_context;
1109       Throw ps;
1110    }
1111 }
1112 
1113 static void PNGCBAPI
store_warning(png_structp ppIn,png_const_charp message)1114 store_warning(png_structp ppIn, png_const_charp message)
1115 {
1116    png_const_structp pp = ppIn;
1117    png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1118 
1119    if (!ps->expect_warning)
1120       store_log(ps, pp, message, 0 /* warning */);
1121    else
1122       ps->saw_warning = 1;
1123 }
1124 
1125 /* These somewhat odd functions are used when reading an image to ensure that
1126  * the buffer is big enough, the png_structp is for errors.
1127  */
1128 /* Return a single row from the correct image. */
1129 static png_bytep
store_image_row(const png_store * ps,png_const_structp pp,int nImage,png_uint_32 y)1130 store_image_row(const png_store* ps, png_const_structp pp, int nImage,
1131    png_uint_32 y)
1132 {
1133    size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
1134 
1135    if (ps->image == NULL)
1136       png_error(pp, "no allocated image");
1137 
1138    if (coffset + ps->cb_row + 3 > ps->cb_image)
1139       png_error(pp, "image too small");
1140 
1141    return ps->image + coffset;
1142 }
1143 
1144 static void
store_image_free(png_store * ps,png_const_structp pp)1145 store_image_free(png_store *ps, png_const_structp pp)
1146 {
1147    if (ps->image != NULL)
1148    {
1149       png_bytep image = ps->image;
1150 
1151       if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1152       {
1153          if (pp != NULL)
1154             png_error(pp, "png_store image overwrite (1)");
1155          else
1156             store_log(ps, NULL, "png_store image overwrite (2)", 1);
1157       }
1158 
1159       ps->image = NULL;
1160       ps->cb_image = 0;
1161       --image;
1162       free(image);
1163    }
1164 }
1165 
1166 static void
store_ensure_image(png_store * ps,png_const_structp pp,int nImages,size_t cbRow,png_uint_32 cRows)1167 store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
1168    size_t cbRow, png_uint_32 cRows)
1169 {
1170    size_t cb = nImages * cRows * (cbRow + 5);
1171 
1172    if (ps->cb_image < cb)
1173    {
1174       png_bytep image;
1175 
1176       store_image_free(ps, pp);
1177 
1178       /* The buffer is deliberately mis-aligned. */
1179       image = voidcast(png_bytep, malloc(cb+2));
1180       if (image == NULL)
1181       {
1182          /* Called from the startup - ignore the error for the moment. */
1183          if (pp == NULL)
1184             return;
1185 
1186          png_error(pp, "OOM allocating image buffer");
1187       }
1188 
1189       /* These magic tags are used to detect overwrites above. */
1190       ++image;
1191       image[-1] = 0xed;
1192       image[cb] = 0xfe;
1193 
1194       ps->image = image;
1195       ps->cb_image = cb;
1196    }
1197 
1198    /* We have an adequate sized image; lay out the rows.  There are 2 bytes at
1199     * the start and three at the end of each (this ensures that the row
1200     * alignment starts out odd - 2+1 and changes for larger images on each row.)
1201     */
1202    ps->cb_row = cbRow;
1203    ps->image_h = cRows;
1204 
1205    /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
1206     * This deliberately doesn't match the bits in the size test image which are
1207     * outside the image; these are set to 0xff (all 1).  To make the row
1208     * comparison work in the 'size' test case the size rows are pre-initialized
1209     * to the same value prior to calling 'standard_row'.
1210     */
1211    memset(ps->image, 178, cb);
1212 
1213    /* Then put in the marks. */
1214    while (--nImages >= 0)
1215    {
1216       png_uint_32 y;
1217 
1218       for (y=0; y<cRows; ++y)
1219       {
1220          png_bytep row = store_image_row(ps, pp, nImages, y);
1221 
1222          /* The markers: */
1223          row[-2] = 190;
1224          row[-1] = 239;
1225          row[cbRow] = 222;
1226          row[cbRow+1] = 173;
1227          row[cbRow+2] = 17;
1228       }
1229    }
1230 }
1231 
1232 #ifdef PNG_READ_SUPPORTED
1233 static void
store_image_check(const png_store * ps,png_const_structp pp,int iImage)1234 store_image_check(const png_store* ps, png_const_structp pp, int iImage)
1235 {
1236    png_const_bytep image = ps->image;
1237 
1238    if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1239       png_error(pp, "image overwrite");
1240    else
1241    {
1242       size_t cbRow = ps->cb_row;
1243       png_uint_32 rows = ps->image_h;
1244 
1245       image += iImage * (cbRow+5) * ps->image_h;
1246 
1247       image += 2; /* skip image first row markers */
1248 
1249       for (; rows > 0; --rows)
1250       {
1251          if (image[-2] != 190 || image[-1] != 239)
1252             png_error(pp, "row start overwritten");
1253 
1254          if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
1255             image[cbRow+2] != 17)
1256             png_error(pp, "row end overwritten");
1257 
1258          image += cbRow+5;
1259       }
1260    }
1261 }
1262 #endif /* PNG_READ_SUPPORTED */
1263 
1264 static int
valid_chunktype(png_uint_32 chunktype)1265 valid_chunktype(png_uint_32 chunktype)
1266 {
1267    /* Each byte in the chunk type must be in one of the ranges 65..90, 97..122
1268     * (both inclusive), so:
1269     */
1270    unsigned int i;
1271 
1272    for (i=0; i<4; ++i)
1273    {
1274       unsigned int c = chunktype & 0xffU;
1275 
1276       if (!((c >= 65U && c <= 90U) || (c >= 97U && c <= 122U)))
1277          return 0;
1278 
1279       chunktype >>= 8;
1280    }
1281 
1282    return 1; /* It's valid */
1283 }
1284 
1285 static void PNGCBAPI
store_write(png_structp ppIn,png_bytep pb,size_t st)1286 store_write(png_structp ppIn, png_bytep pb, size_t st)
1287 {
1288    png_const_structp pp = ppIn;
1289    png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1290    size_t writepos = ps->writepos;
1291    png_uint_32 chunkpos = ps->chunkpos;
1292    png_uint_32 chunktype = ps->chunktype;
1293    png_uint_32 chunklen = ps->chunklen;
1294 
1295    if (ps->pwrite != pp)
1296       png_error(pp, "store state damaged");
1297 
1298    /* Technically this is legal, but in practice libpng never writes more than
1299     * the maximum chunk size at once so if it happens something weird has
1300     * changed inside libpng (probably).
1301     */
1302    if (st > 0x7fffffffU)
1303       png_error(pp, "unexpected write size");
1304 
1305    /* Now process the bytes to be written.  Do this in units of the space in the
1306     * output (write) buffer or, at the start 4 bytes for the chunk type and
1307     * length limited in any case by the amount of data.
1308     */
1309    while (st > 0)
1310    {
1311       if (writepos >= STORE_BUFFER_SIZE)
1312          store_storenew(ps), writepos = 0;
1313 
1314       if (chunkpos < 4)
1315       {
1316          png_byte b = *pb++;
1317          --st;
1318          chunklen = (chunklen << 8) + b;
1319          ps->new.buffer[writepos++] = b;
1320          ++chunkpos;
1321       }
1322 
1323       else if (chunkpos < 8)
1324       {
1325          png_byte b = *pb++;
1326          --st;
1327          chunktype = (chunktype << 8) + b;
1328          ps->new.buffer[writepos++] = b;
1329 
1330          if (++chunkpos == 8)
1331          {
1332             chunklen &= 0xffffffffU;
1333             if (chunklen > 0x7fffffffU)
1334                png_error(pp, "chunk length too great");
1335 
1336             chunktype &= 0xffffffffU;
1337             if (chunktype == CHUNK_IDAT)
1338             {
1339                if (chunklen > ~ps->IDAT_size)
1340                   png_error(pp, "pngvalid internal image too large");
1341 
1342                ps->IDAT_size += chunklen;
1343             }
1344 
1345             else if (!valid_chunktype(chunktype))
1346                png_error(pp, "invalid chunk type");
1347 
1348             chunklen += 12; /* for header and CRC */
1349          }
1350       }
1351 
1352       else /* chunkpos >= 8 */
1353       {
1354          size_t cb = st;
1355 
1356          if (cb > STORE_BUFFER_SIZE - writepos)
1357             cb = STORE_BUFFER_SIZE - writepos;
1358 
1359          if (cb  > chunklen - chunkpos/* bytes left in chunk*/)
1360             cb = (size_t)/*SAFE*/(chunklen - chunkpos);
1361 
1362          memcpy(ps->new.buffer + writepos, pb, cb);
1363          chunkpos += (png_uint_32)/*SAFE*/cb;
1364          pb += cb;
1365          writepos += cb;
1366          st -= cb;
1367 
1368          if (chunkpos >= chunklen) /* must be equal */
1369             chunkpos = chunktype = chunklen = 0;
1370       }
1371    } /* while (st > 0) */
1372 
1373    ps->writepos = writepos;
1374    ps->chunkpos = chunkpos;
1375    ps->chunktype = chunktype;
1376    ps->chunklen = chunklen;
1377 }
1378 
1379 static void PNGCBAPI
store_flush(png_structp ppIn)1380 store_flush(png_structp ppIn)
1381 {
1382    UNUSED(ppIn) /*DOES NOTHING*/
1383 }
1384 
1385 #ifdef PNG_READ_SUPPORTED
1386 static size_t
store_read_buffer_size(png_store * ps)1387 store_read_buffer_size(png_store *ps)
1388 {
1389    /* Return the bytes available for read in the current buffer. */
1390    if (ps->next != &ps->current->data)
1391       return STORE_BUFFER_SIZE;
1392 
1393    return ps->current->datacount;
1394 }
1395 
1396 /* Return total bytes available for read. */
1397 static size_t
store_read_buffer_avail(png_store * ps)1398 store_read_buffer_avail(png_store *ps)
1399 {
1400    if (ps->current != NULL && ps->next != NULL)
1401    {
1402       png_store_buffer *next = &ps->current->data;
1403       size_t cbAvail = ps->current->datacount;
1404 
1405       while (next != ps->next && next != NULL)
1406       {
1407          next = next->prev;
1408          cbAvail += STORE_BUFFER_SIZE;
1409       }
1410 
1411       if (next != ps->next)
1412          png_error(ps->pread, "buffer read error");
1413 
1414       if (cbAvail > ps->readpos)
1415          return cbAvail - ps->readpos;
1416    }
1417 
1418    return 0;
1419 }
1420 
1421 static int
store_read_buffer_next(png_store * ps)1422 store_read_buffer_next(png_store *ps)
1423 {
1424    png_store_buffer *pbOld = ps->next;
1425    png_store_buffer *pbNew = &ps->current->data;
1426    if (pbOld != pbNew)
1427    {
1428       while (pbNew != NULL && pbNew->prev != pbOld)
1429          pbNew = pbNew->prev;
1430 
1431       if (pbNew != NULL)
1432       {
1433          ps->next = pbNew;
1434          ps->readpos = 0;
1435          return 1;
1436       }
1437 
1438       png_error(ps->pread, "buffer lost");
1439    }
1440 
1441    return 0; /* EOF or error */
1442 }
1443 
1444 /* Need separate implementation and callback to allow use of the same code
1445  * during progressive read, where the io_ptr is set internally by libpng.
1446  */
1447 static void
store_read_imp(png_store * ps,png_bytep pb,size_t st)1448 store_read_imp(png_store *ps, png_bytep pb, size_t st)
1449 {
1450    if (ps->current == NULL || ps->next == NULL)
1451       png_error(ps->pread, "store state damaged");
1452 
1453    while (st > 0)
1454    {
1455       size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
1456 
1457       if (cbAvail > 0)
1458       {
1459          if (cbAvail > st) cbAvail = st;
1460          memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
1461          st -= cbAvail;
1462          pb += cbAvail;
1463          ps->readpos += cbAvail;
1464       }
1465 
1466       else if (!store_read_buffer_next(ps))
1467          png_error(ps->pread, "read beyond end of file");
1468    }
1469 }
1470 
1471 static size_t
store_read_chunk(png_store * ps,png_bytep pb,size_t max,size_t min)1472 store_read_chunk(png_store *ps, png_bytep pb, size_t max, size_t min)
1473 {
1474    png_uint_32 chunklen = ps->chunklen;
1475    png_uint_32 chunktype = ps->chunktype;
1476    png_uint_32 chunkpos = ps->chunkpos;
1477    size_t st = max;
1478 
1479    if (st > 0) do
1480    {
1481       if (chunkpos >= chunklen) /* end of last chunk */
1482       {
1483          png_byte buffer[8];
1484 
1485          /* Read the header of the next chunk: */
1486          store_read_imp(ps, buffer, 8U);
1487          chunklen = png_get_uint_32(buffer) + 12U;
1488          chunktype = png_get_uint_32(buffer+4U);
1489          chunkpos = 0U; /* Position read so far */
1490       }
1491 
1492       if (chunktype == CHUNK_IDAT)
1493       {
1494          png_uint_32 IDAT_pos = ps->IDAT_pos;
1495          png_uint_32 IDAT_len = ps->IDAT_len;
1496          png_uint_32 IDAT_size = ps->IDAT_size;
1497 
1498          /* The IDAT headers are constructed here; skip the input header. */
1499          if (chunkpos < 8U)
1500             chunkpos = 8U;
1501 
1502          if (IDAT_pos == IDAT_len)
1503          {
1504             png_byte random = random_byte();
1505 
1506             /* Make a new IDAT chunk, if IDAT_len is 0 this is the first IDAT,
1507              * if IDAT_size is 0 this is the end.  At present this is set up
1508              * using a random number so that there is a 25% chance before
1509              * the start of the first IDAT chunk being 0 length.
1510              */
1511             if (IDAT_len == 0U) /* First IDAT */
1512             {
1513                switch (random & 3U)
1514                {
1515                   case 0U: IDAT_len = 12U; break; /* 0 bytes */
1516                   case 1U: IDAT_len = 13U; break; /* 1 byte */
1517                   default: IDAT_len = random_u32();
1518                            IDAT_len %= IDAT_size;
1519                            IDAT_len += 13U; /* 1..IDAT_size bytes */
1520                            break;
1521                }
1522             }
1523 
1524             else if (IDAT_size == 0U) /* all IDAT data read */
1525             {
1526                /* The last (IDAT) chunk should be positioned at the CRC now: */
1527                if (chunkpos != chunklen-4U)
1528                   png_error(ps->pread, "internal: IDAT size mismatch");
1529 
1530                /* The only option here is to add a zero length IDAT, this
1531                 * happens 25% of the time.  Because of the check above
1532                 * chunklen-4U-chunkpos must be zero, we just need to skip the
1533                 * CRC now.
1534                 */
1535                if ((random & 3U) == 0U)
1536                   IDAT_len = 12U; /* Output another 0 length IDAT */
1537 
1538                else
1539                {
1540                   /* End of IDATs, skip the CRC to make the code above load the
1541                    * next chunk header next time round.
1542                    */
1543                   png_byte buffer[4];
1544 
1545                   store_read_imp(ps, buffer, 4U);
1546                   chunkpos += 4U;
1547                   ps->IDAT_pos = IDAT_pos;
1548                   ps->IDAT_len = IDAT_len;
1549                   ps->IDAT_size = 0U;
1550                   continue; /* Read the next chunk */
1551                }
1552             }
1553 
1554             else
1555             {
1556                /* Middle of IDATs, use 'random' to determine the number of bits
1557                 * to use in the IDAT length.
1558                 */
1559                IDAT_len = random_u32();
1560                IDAT_len &= (1U << (1U + random % ps->IDAT_bits)) - 1U;
1561                if (IDAT_len > IDAT_size)
1562                   IDAT_len = IDAT_size;
1563                IDAT_len += 12U; /* zero bytes may occur */
1564             }
1565 
1566             IDAT_pos = 0U;
1567             ps->IDAT_crc = 0x35af061e; /* Ie: crc32(0UL, "IDAT", 4) */
1568          } /* IDAT_pos == IDAT_len */
1569 
1570          if (IDAT_pos < 8U) /* Return the header */ do
1571          {
1572             png_uint_32 b;
1573             unsigned int shift;
1574 
1575             if (IDAT_pos < 4U)
1576                b = IDAT_len - 12U;
1577 
1578             else
1579                b = CHUNK_IDAT;
1580 
1581             shift = 3U & IDAT_pos;
1582             ++IDAT_pos;
1583 
1584             if (shift < 3U)
1585                b >>= 8U*(3U-shift);
1586 
1587             *pb++ = 0xffU & b;
1588          }
1589          while (--st > 0 && IDAT_pos < 8);
1590 
1591          else if (IDAT_pos < IDAT_len - 4U) /* I.e not the CRC */
1592          {
1593             if (chunkpos < chunklen-4U)
1594             {
1595                uInt avail = (uInt)-1;
1596 
1597                if (avail > (IDAT_len-4U) - IDAT_pos)
1598                   avail = (uInt)/*SAFE*/((IDAT_len-4U) - IDAT_pos);
1599 
1600                if (avail > st)
1601                   avail = (uInt)/*SAFE*/st;
1602 
1603                if (avail > (chunklen-4U) - chunkpos)
1604                   avail = (uInt)/*SAFE*/((chunklen-4U) - chunkpos);
1605 
1606                store_read_imp(ps, pb, avail);
1607                ps->IDAT_crc = crc32(ps->IDAT_crc, pb, avail);
1608                pb += (size_t)/*SAFE*/avail;
1609                st -= (size_t)/*SAFE*/avail;
1610                chunkpos += (png_uint_32)/*SAFE*/avail;
1611                IDAT_size -= (png_uint_32)/*SAFE*/avail;
1612                IDAT_pos += (png_uint_32)/*SAFE*/avail;
1613             }
1614 
1615             else /* skip the input CRC */
1616             {
1617                png_byte buffer[4];
1618 
1619                store_read_imp(ps, buffer, 4U);
1620                chunkpos += 4U;
1621             }
1622          }
1623 
1624          else /* IDAT crc */ do
1625          {
1626             uLong b = ps->IDAT_crc;
1627             unsigned int shift = (IDAT_len - IDAT_pos); /* 4..1 */
1628             ++IDAT_pos;
1629 
1630             if (shift > 1U)
1631                b >>= 8U*(shift-1U);
1632 
1633             *pb++ = 0xffU & b;
1634          }
1635          while (--st > 0 && IDAT_pos < IDAT_len);
1636 
1637          ps->IDAT_pos = IDAT_pos;
1638          ps->IDAT_len = IDAT_len;
1639          ps->IDAT_size = IDAT_size;
1640       }
1641 
1642       else /* !IDAT */
1643       {
1644          /* If there is still some pending IDAT data after the IDAT chunks have
1645           * been processed there is a problem:
1646           */
1647          if (ps->IDAT_len > 0 && ps->IDAT_size > 0)
1648             png_error(ps->pread, "internal: missing IDAT data");
1649 
1650          if (chunktype == CHUNK_IEND && ps->IDAT_len == 0U)
1651             png_error(ps->pread, "internal: missing IDAT");
1652 
1653          if (chunkpos < 8U) /* Return the header */ do
1654          {
1655             png_uint_32 b;
1656             unsigned int shift;
1657 
1658             if (chunkpos < 4U)
1659                b = chunklen - 12U;
1660 
1661             else
1662                b = chunktype;
1663 
1664             shift = 3U & chunkpos;
1665             ++chunkpos;
1666 
1667             if (shift < 3U)
1668                b >>= 8U*(3U-shift);
1669 
1670             *pb++ = 0xffU & b;
1671          }
1672          while (--st > 0 && chunkpos < 8);
1673 
1674          else /* Return chunk bytes, including the CRC */
1675          {
1676             size_t avail = st;
1677 
1678             if (avail > chunklen - chunkpos)
1679                avail = (size_t)/*SAFE*/(chunklen - chunkpos);
1680 
1681             store_read_imp(ps, pb, avail);
1682             pb += avail;
1683             st -= avail;
1684             chunkpos += (png_uint_32)/*SAFE*/avail;
1685 
1686             /* Check for end of chunk and end-of-file; don't try to read a new
1687              * chunk header at this point unless instructed to do so by 'min'.
1688              */
1689             if (chunkpos >= chunklen && max-st >= min &&
1690                      store_read_buffer_avail(ps) == 0)
1691                break;
1692          }
1693       } /* !IDAT */
1694    }
1695    while (st > 0);
1696 
1697    ps->chunklen = chunklen;
1698    ps->chunktype = chunktype;
1699    ps->chunkpos = chunkpos;
1700 
1701    return st; /* space left */
1702 }
1703 
1704 static void PNGCBAPI
store_read(png_structp ppIn,png_bytep pb,size_t st)1705 store_read(png_structp ppIn, png_bytep pb, size_t st)
1706 {
1707    png_const_structp pp = ppIn;
1708    png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1709 
1710    if (ps == NULL || ps->pread != pp)
1711       png_error(pp, "bad store read call");
1712 
1713    store_read_chunk(ps, pb, st, st);
1714 }
1715 
1716 static void
store_progressive_read(png_store * ps,png_structp pp,png_infop pi)1717 store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
1718 {
1719    if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
1720       png_error(pp, "store state damaged (progressive)");
1721 
1722    /* This is another Horowitz and Hill random noise generator.  In this case
1723     * the aim is to stress the progressive reader with truly horrible variable
1724     * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
1725     * is generated.  We could probably just count from 1 to 32767 and get as
1726     * good a result.
1727     */
1728    while (store_read_buffer_avail(ps) > 0)
1729    {
1730       static png_uint_32 noise = 2;
1731       size_t cb;
1732       png_byte buffer[512];
1733 
1734       /* Generate 15 more bits of stuff: */
1735       noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
1736       cb = noise & 0x1ff;
1737       cb -= store_read_chunk(ps, buffer, cb, 1);
1738       png_process_data(pp, pi, buffer, cb);
1739    }
1740 }
1741 #endif /* PNG_READ_SUPPORTED */
1742 
1743 /* The caller must fill this in: */
1744 static store_palette_entry *
store_write_palette(png_store * ps,int npalette)1745 store_write_palette(png_store *ps, int npalette)
1746 {
1747    if (ps->pwrite == NULL)
1748       store_log(ps, NULL, "attempt to write palette without write stream", 1);
1749 
1750    if (ps->palette != NULL)
1751       png_error(ps->pwrite, "multiple store_write_palette calls");
1752 
1753    /* This function can only return NULL if called with '0'! */
1754    if (npalette > 0)
1755    {
1756       ps->palette = voidcast(store_palette_entry*, malloc(npalette *
1757          sizeof *ps->palette));
1758 
1759       if (ps->palette == NULL)
1760          png_error(ps->pwrite, "store new palette: OOM");
1761 
1762       ps->npalette = npalette;
1763    }
1764 
1765    return ps->palette;
1766 }
1767 
1768 #ifdef PNG_READ_SUPPORTED
1769 static store_palette_entry *
store_current_palette(png_store * ps,int * npalette)1770 store_current_palette(png_store *ps, int *npalette)
1771 {
1772    /* This is an internal error (the call has been made outside a read
1773     * operation.)
1774     */
1775    if (ps->current == NULL)
1776    {
1777       store_log(ps, ps->pread, "no current stream for palette", 1);
1778       return NULL;
1779    }
1780 
1781    /* The result may be null if there is no palette. */
1782    *npalette = ps->current->npalette;
1783    return ps->current->palette;
1784 }
1785 #endif /* PNG_READ_SUPPORTED */
1786 
1787 /***************************** MEMORY MANAGEMENT*** ***************************/
1788 #ifdef PNG_USER_MEM_SUPPORTED
1789 /* A store_memory is simply the header for an allocated block of memory.  The
1790  * pointer returned to libpng is just after the end of the header block, the
1791  * allocated memory is followed by a second copy of the 'mark'.
1792  */
1793 typedef struct store_memory
1794 {
1795    store_pool          *pool;    /* Originating pool */
1796    struct store_memory *next;    /* Singly linked list */
1797    png_alloc_size_t     size;    /* Size of memory allocated */
1798    png_byte             mark[4]; /* ID marker */
1799 } store_memory;
1800 
1801 /* Handle a fatal error in memory allocation.  This calls png_error if the
1802  * libpng struct is non-NULL, else it outputs a message and returns.  This means
1803  * that a memory problem while libpng is running will abort (png_error) the
1804  * handling of particular file while one in cleanup (after the destroy of the
1805  * struct has returned) will simply keep going and free (or attempt to free)
1806  * all the memory.
1807  */
1808 static void
store_pool_error(png_store * ps,png_const_structp pp,const char * msg)1809 store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
1810 {
1811    if (pp != NULL)
1812       png_error(pp, msg);
1813 
1814    /* Else we have to do it ourselves.  png_error eventually calls store_log,
1815     * above.  store_log accepts a NULL png_structp - it just changes what gets
1816     * output by store_message.
1817     */
1818    store_log(ps, pp, msg, 1 /* error */);
1819 }
1820 
1821 static void
store_memory_free(png_const_structp pp,store_pool * pool,store_memory * memory)1822 store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
1823 {
1824    /* Note that pp may be NULL (see store_pool_delete below), the caller has
1825     * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
1826     * pointer (for sure), but the contents may have been trashed.
1827     */
1828    if (memory->pool != pool)
1829       store_pool_error(pool->store, pp, "memory corrupted (pool)");
1830 
1831    else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
1832       store_pool_error(pool->store, pp, "memory corrupted (start)");
1833 
1834    /* It should be safe to read the size field now. */
1835    else
1836    {
1837       png_alloc_size_t cb = memory->size;
1838 
1839       if (cb > pool->max)
1840          store_pool_error(pool->store, pp, "memory corrupted (size)");
1841 
1842       else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
1843          != 0)
1844          store_pool_error(pool->store, pp, "memory corrupted (end)");
1845 
1846       /* Finally give the library a chance to find problems too: */
1847       else
1848          {
1849          pool->current -= cb;
1850          free(memory);
1851          }
1852    }
1853 }
1854 
1855 static void
store_pool_delete(png_store * ps,store_pool * pool)1856 store_pool_delete(png_store *ps, store_pool *pool)
1857 {
1858    if (pool->list != NULL)
1859    {
1860       fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
1861          pool == &ps->read_memory_pool ? "read" : "write",
1862          pool == &ps->read_memory_pool ? (ps->current != NULL ?
1863             ps->current->name : "unknown file") : ps->wname);
1864       ++ps->nerrors;
1865 
1866       do
1867       {
1868          store_memory *next = pool->list;
1869          pool->list = next->next;
1870          next->next = NULL;
1871 
1872          fprintf(stderr, "\t%lu bytes @ %p\n",
1873              (unsigned long)next->size, (const void*)(next+1));
1874          /* The NULL means this will always return, even if the memory is
1875           * corrupted.
1876           */
1877          store_memory_free(NULL, pool, next);
1878       }
1879       while (pool->list != NULL);
1880    }
1881 
1882    /* And reset the other fields too for the next time. */
1883    if (pool->max > pool->max_max) pool->max_max = pool->max;
1884    pool->max = 0;
1885    if (pool->current != 0) /* unexpected internal error */
1886       fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
1887          ps->test, pool == &ps->read_memory_pool ? "read" : "write",
1888          pool == &ps->read_memory_pool ? (ps->current != NULL ?
1889             ps->current->name : "unknown file") : ps->wname);
1890    pool->current = 0;
1891 
1892    if (pool->limit > pool->max_limit)
1893       pool->max_limit = pool->limit;
1894 
1895    pool->limit = 0;
1896 
1897    if (pool->total > pool->max_total)
1898       pool->max_total = pool->total;
1899 
1900    pool->total = 0;
1901 
1902    /* Get a new mark too. */
1903    store_pool_mark(pool->mark);
1904 }
1905 
1906 /* The memory callbacks: */
1907 static png_voidp PNGCBAPI
store_malloc(png_structp ppIn,png_alloc_size_t cb)1908 store_malloc(png_structp ppIn, png_alloc_size_t cb)
1909 {
1910    png_const_structp pp = ppIn;
1911    store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1912    store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
1913       (sizeof pool->mark)));
1914 
1915    if (new != NULL)
1916    {
1917       if (cb > pool->max)
1918          pool->max = cb;
1919 
1920       pool->current += cb;
1921 
1922       if (pool->current > pool->limit)
1923          pool->limit = pool->current;
1924 
1925       pool->total += cb;
1926 
1927       new->size = cb;
1928       memcpy(new->mark, pool->mark, sizeof new->mark);
1929       memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
1930       new->pool = pool;
1931       new->next = pool->list;
1932       pool->list = new;
1933       ++new;
1934    }
1935 
1936    else
1937    {
1938       /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
1939        * other than to retrieve the allocation pointer!  libpng calls the
1940        * store_malloc callback in two basic cases:
1941        *
1942        * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
1943        *    returned.
1944        * 2) From png_struct or png_info structure creation; png_malloc is
1945        *    to return so cleanup can be performed.
1946        *
1947        * To handle this store_malloc can log a message, but can't do anything
1948        * else.
1949        */
1950       store_log(pool->store, pp, "out of memory", 1 /* is_error */);
1951    }
1952 
1953    return new;
1954 }
1955 
1956 static void PNGCBAPI
store_free(png_structp ppIn,png_voidp memory)1957 store_free(png_structp ppIn, png_voidp memory)
1958 {
1959    png_const_structp pp = ppIn;
1960    store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1961    store_memory *this = voidcast(store_memory*, memory), **test;
1962 
1963    /* Because libpng calls store_free with a dummy png_struct when deleting
1964     * png_struct or png_info via png_destroy_struct_2 it is necessary to check
1965     * the passed in png_structp to ensure it is valid, and not pass it to
1966     * png_error if it is not.
1967     */
1968    if (pp != pool->store->pread && pp != pool->store->pwrite)
1969       pp = NULL;
1970 
1971    /* First check that this 'memory' really is valid memory - it must be in the
1972     * pool list.  If it is, use the shared memory_free function to free it.
1973     */
1974    --this;
1975    for (test = &pool->list; *test != this; test = &(*test)->next)
1976    {
1977       if (*test == NULL)
1978       {
1979          store_pool_error(pool->store, pp, "bad pointer to free");
1980          return;
1981       }
1982    }
1983 
1984    /* Unlink this entry, *test == this. */
1985    *test = this->next;
1986    this->next = NULL;
1987    store_memory_free(pp, pool, this);
1988 }
1989 #endif /* PNG_USER_MEM_SUPPORTED */
1990 
1991 /* Setup functions. */
1992 /* Cleanup when aborting a write or after storing the new file. */
1993 static void
store_write_reset(png_store * ps)1994 store_write_reset(png_store *ps)
1995 {
1996    if (ps->pwrite != NULL)
1997    {
1998       anon_context(ps);
1999 
2000       Try
2001          png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
2002 
2003       Catch_anonymous
2004       {
2005          /* memory corruption: continue. */
2006       }
2007 
2008       ps->pwrite = NULL;
2009       ps->piwrite = NULL;
2010    }
2011 
2012    /* And make sure that all the memory has been freed - this will output
2013     * spurious errors in the case of memory corruption above, but this is safe.
2014     */
2015 #  ifdef PNG_USER_MEM_SUPPORTED
2016       store_pool_delete(ps, &ps->write_memory_pool);
2017 #  endif
2018 
2019    store_freenew(ps);
2020 }
2021 
2022 /* The following is the main write function, it returns a png_struct and,
2023  * optionally, a png_info suitable for writiing a new PNG file.  Use
2024  * store_storefile above to record this file after it has been written.  The
2025  * returned libpng structures as destroyed by store_write_reset above.
2026  */
2027 static png_structp
set_store_for_write(png_store * ps,png_infopp ppi,const char * name)2028 set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
2029 {
2030    anon_context(ps);
2031 
2032    Try
2033    {
2034       if (ps->pwrite != NULL)
2035          png_error(ps->pwrite, "write store already in use");
2036 
2037       store_write_reset(ps);
2038       safecat(ps->wname, sizeof ps->wname, 0, name);
2039 
2040       /* Don't do the slow memory checks if doing a speed test, also if user
2041        * memory is not supported we can't do it anyway.
2042        */
2043 #     ifdef PNG_USER_MEM_SUPPORTED
2044          if (!ps->speed)
2045             ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
2046                ps, store_error, store_warning, &ps->write_memory_pool,
2047                store_malloc, store_free);
2048 
2049          else
2050 #     endif
2051          ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2052             ps, store_error, store_warning);
2053 
2054       png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
2055 
2056 #     ifdef PNG_SET_OPTION_SUPPORTED
2057          {
2058             int opt;
2059             for (opt=0; opt<ps->noptions; ++opt)
2060                if (png_set_option(ps->pwrite, ps->options[opt].option,
2061                   ps->options[opt].setting) == PNG_OPTION_INVALID)
2062                   png_error(ps->pwrite, "png option invalid");
2063          }
2064 #     endif
2065 
2066       if (ppi != NULL)
2067          *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
2068    }
2069 
2070    Catch_anonymous
2071       return NULL;
2072 
2073    return ps->pwrite;
2074 }
2075 
2076 /* Cleanup when finished reading (either due to error or in the success case).
2077  * This routine exists even when there is no read support to make the code
2078  * tidier (avoid a mass of ifdefs) and so easier to maintain.
2079  */
2080 static void
store_read_reset(png_store * ps)2081 store_read_reset(png_store *ps)
2082 {
2083 #  ifdef PNG_READ_SUPPORTED
2084       if (ps->pread != NULL)
2085       {
2086          anon_context(ps);
2087 
2088          Try
2089             png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
2090 
2091          Catch_anonymous
2092          {
2093             /* error already output: continue */
2094          }
2095 
2096          ps->pread = NULL;
2097          ps->piread = NULL;
2098       }
2099 #  endif
2100 
2101 #  ifdef PNG_USER_MEM_SUPPORTED
2102       /* Always do this to be safe. */
2103       store_pool_delete(ps, &ps->read_memory_pool);
2104 #  endif
2105 
2106    ps->current = NULL;
2107    ps->next = NULL;
2108    ps->readpos = 0;
2109    ps->validated = 0;
2110 
2111    ps->chunkpos = 8;
2112    ps->chunktype = 0;
2113    ps->chunklen = 16;
2114    ps->IDAT_size = 0;
2115 }
2116 
2117 #ifdef PNG_READ_SUPPORTED
2118 static void
store_read_set(png_store * ps,png_uint_32 id)2119 store_read_set(png_store *ps, png_uint_32 id)
2120 {
2121    png_store_file *pf = ps->saved;
2122 
2123    while (pf != NULL)
2124    {
2125       if (pf->id == id)
2126       {
2127          ps->current = pf;
2128          ps->next = NULL;
2129          ps->IDAT_size = pf->IDAT_size;
2130          ps->IDAT_bits = pf->IDAT_bits; /* just a cache */
2131          ps->IDAT_len = 0;
2132          ps->IDAT_pos = 0;
2133          ps->IDAT_crc = 0UL;
2134          store_read_buffer_next(ps);
2135          return;
2136       }
2137 
2138       pf = pf->next;
2139    }
2140 
2141    {
2142       size_t pos;
2143       char msg[FILE_NAME_SIZE+64];
2144 
2145       pos = standard_name_from_id(msg, sizeof msg, 0, id);
2146       pos = safecat(msg, sizeof msg, pos, ": file not found");
2147       png_error(ps->pread, msg);
2148    }
2149 }
2150 
2151 /* The main interface for reading a saved file - pass the id number of the file
2152  * to retrieve.  Ids must be unique or the earlier file will be hidden.  The API
2153  * returns a png_struct and, optionally, a png_info.  Both of these will be
2154  * destroyed by store_read_reset above.
2155  */
2156 static png_structp
set_store_for_read(png_store * ps,png_infopp ppi,png_uint_32 id,const char * name)2157 set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
2158    const char *name)
2159 {
2160    /* Set the name for png_error */
2161    safecat(ps->test, sizeof ps->test, 0, name);
2162 
2163    if (ps->pread != NULL)
2164       png_error(ps->pread, "read store already in use");
2165 
2166    store_read_reset(ps);
2167 
2168    /* Both the create APIs can return NULL if used in their default mode
2169     * (because there is no other way of handling an error because the jmp_buf
2170     * by default is stored in png_struct and that has not been allocated!)
2171     * However, given that store_error works correctly in these circumstances
2172     * we don't ever expect NULL in this program.
2173     */
2174 #  ifdef PNG_USER_MEM_SUPPORTED
2175       if (!ps->speed)
2176          ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
2177              store_error, store_warning, &ps->read_memory_pool, store_malloc,
2178              store_free);
2179 
2180       else
2181 #  endif
2182    ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
2183       store_warning);
2184 
2185    if (ps->pread == NULL)
2186    {
2187       struct exception_context *the_exception_context = &ps->exception_context;
2188 
2189       store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
2190          1 /*error*/);
2191 
2192       Throw ps;
2193    }
2194 
2195 #  ifdef PNG_SET_OPTION_SUPPORTED
2196       {
2197          int opt;
2198          for (opt=0; opt<ps->noptions; ++opt)
2199             if (png_set_option(ps->pread, ps->options[opt].option,
2200                ps->options[opt].setting) == PNG_OPTION_INVALID)
2201                   png_error(ps->pread, "png option invalid");
2202       }
2203 #  endif
2204 
2205    store_read_set(ps, id);
2206 
2207    if (ppi != NULL)
2208       *ppi = ps->piread = png_create_info_struct(ps->pread);
2209 
2210    return ps->pread;
2211 }
2212 #endif /* PNG_READ_SUPPORTED */
2213 
2214 /* The overall cleanup of a store simply calls the above then removes all the
2215  * saved files.  This does not delete the store itself.
2216  */
2217 static void
store_delete(png_store * ps)2218 store_delete(png_store *ps)
2219 {
2220    store_write_reset(ps);
2221    store_read_reset(ps);
2222    store_freefile(&ps->saved);
2223    store_image_free(ps, NULL);
2224 }
2225 
2226 /*********************** PNG FILE MODIFICATION ON READ ************************/
2227 /* Files may be modified on read.  The following structure contains a complete
2228  * png_store together with extra members to handle modification and a special
2229  * read callback for libpng.  To use this the 'modifications' field must be set
2230  * to a list of png_modification structures that actually perform the
2231  * modification, otherwise a png_modifier is functionally equivalent to a
2232  * png_store.  There is a special read function, set_modifier_for_read, which
2233  * replaces set_store_for_read.
2234  */
2235 typedef enum modifier_state
2236 {
2237    modifier_start,                        /* Initial value */
2238    modifier_signature,                    /* Have a signature */
2239    modifier_IHDR                          /* Have an IHDR */
2240 } modifier_state;
2241 
2242 typedef struct CIE_color
2243 {
2244    /* A single CIE tristimulus value, representing the unique response of a
2245     * standard observer to a variety of light spectra.  The observer recognizes
2246     * all spectra that produce this response as the same color, therefore this
2247     * is effectively a description of a color.
2248     */
2249    double X, Y, Z;
2250 } CIE_color;
2251 
2252 typedef struct color_encoding
2253 {
2254    /* A description of an (R,G,B) encoding of color (as defined above); this
2255     * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
2256     * (0,0,1) plus an encoding value that is used to encode the linear
2257     * components R, G and B to give the actual values R^gamma, G^gamma and
2258     * B^gamma that are stored.
2259     */
2260    double    gamma;            /* Encoding (file) gamma of space */
2261    CIE_color red, green, blue; /* End points */
2262 } color_encoding;
2263 
2264 #ifdef PNG_READ_SUPPORTED
2265 #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
2266 static double
chromaticity_x(CIE_color c)2267 chromaticity_x(CIE_color c)
2268 {
2269    return c.X / (c.X + c.Y + c.Z);
2270 }
2271 
2272 static double
chromaticity_y(CIE_color c)2273 chromaticity_y(CIE_color c)
2274 {
2275    return c.Y / (c.X + c.Y + c.Z);
2276 }
2277 
2278 static CIE_color
white_point(const color_encoding * encoding)2279 white_point(const color_encoding *encoding)
2280 {
2281    CIE_color white;
2282 
2283    white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
2284    white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
2285    white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
2286 
2287    return white;
2288 }
2289 #endif /* READ_TRANSFORMS && READ_cHRM */
2290 
2291 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2292 static void
normalize_color_encoding(color_encoding * encoding)2293 normalize_color_encoding(color_encoding *encoding)
2294 {
2295    const double whiteY = encoding->red.Y + encoding->green.Y +
2296       encoding->blue.Y;
2297 
2298    if (whiteY != 1)
2299    {
2300       encoding->red.X /= whiteY;
2301       encoding->red.Y /= whiteY;
2302       encoding->red.Z /= whiteY;
2303       encoding->green.X /= whiteY;
2304       encoding->green.Y /= whiteY;
2305       encoding->green.Z /= whiteY;
2306       encoding->blue.X /= whiteY;
2307       encoding->blue.Y /= whiteY;
2308       encoding->blue.Z /= whiteY;
2309    }
2310 }
2311 #endif
2312 
2313 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
2314 static size_t
safecat_color_encoding(char * buffer,size_t bufsize,size_t pos,const color_encoding * e,double encoding_gamma)2315 safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
2316    const color_encoding *e, double encoding_gamma)
2317 {
2318    if (e != 0)
2319    {
2320       if (encoding_gamma != 0)
2321          pos = safecat(buffer, bufsize, pos, "(");
2322       pos = safecat(buffer, bufsize, pos, "R(");
2323       pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
2324       pos = safecat(buffer, bufsize, pos, ",");
2325       pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
2326       pos = safecat(buffer, bufsize, pos, ",");
2327       pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
2328       pos = safecat(buffer, bufsize, pos, "),G(");
2329       pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
2330       pos = safecat(buffer, bufsize, pos, ",");
2331       pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
2332       pos = safecat(buffer, bufsize, pos, ",");
2333       pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
2334       pos = safecat(buffer, bufsize, pos, "),B(");
2335       pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
2336       pos = safecat(buffer, bufsize, pos, ",");
2337       pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
2338       pos = safecat(buffer, bufsize, pos, ",");
2339       pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
2340       pos = safecat(buffer, bufsize, pos, ")");
2341       if (encoding_gamma != 0)
2342          pos = safecat(buffer, bufsize, pos, ")");
2343    }
2344 
2345    if (encoding_gamma != 0)
2346    {
2347       pos = safecat(buffer, bufsize, pos, "^");
2348       pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
2349    }
2350 
2351    return pos;
2352 }
2353 #endif /* READ_TRANSFORMS */
2354 #endif /* PNG_READ_SUPPORTED */
2355 
2356 typedef struct png_modifier
2357 {
2358    png_store               this;             /* I am a png_store */
2359    struct png_modification *modifications;   /* Changes to make */
2360 
2361    modifier_state           state;           /* My state */
2362 
2363    /* Information from IHDR: */
2364    png_byte                 bit_depth;       /* From IHDR */
2365    png_byte                 colour_type;     /* From IHDR */
2366 
2367    /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
2368     * other chunks to be inserted.
2369     */
2370    png_uint_32              pending_len;
2371    png_uint_32              pending_chunk;
2372 
2373    /* Test values */
2374    double                   *gammas;
2375    unsigned int              ngammas;
2376    unsigned int              ngamma_tests;     /* Number of gamma tests to run*/
2377    double                    current_gamma;    /* 0 if not set */
2378    const color_encoding *encodings;
2379    unsigned int              nencodings;
2380    const color_encoding *current_encoding; /* If an encoding has been set */
2381    unsigned int              encoding_counter; /* For iteration */
2382    int                       encoding_ignored; /* Something overwrote it */
2383 
2384    /* Control variables used to iterate through possible encodings, the
2385     * following must be set to 0 and tested by the function that uses the
2386     * png_modifier because the modifier only sets it to 1 (true.)
2387     */
2388    unsigned int              repeat :1;   /* Repeat this transform test. */
2389    unsigned int              test_uses_encoding :1;
2390 
2391    /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
2392    png_byte                 sbitlow;
2393 
2394    /* Error control - these are the limits on errors accepted by the gamma tests
2395     * below.
2396     */
2397    double                   maxout8;  /* Maximum output value error */
2398    double                   maxabs8;  /* Absolute sample error 0..1 */
2399    double                   maxcalc8; /* Absolute sample error 0..1 */
2400    double                   maxpc8;   /* Percentage sample error 0..100% */
2401    double                   maxout16; /* Maximum output value error */
2402    double                   maxabs16; /* Absolute sample error 0..1 */
2403    double                   maxcalc16;/* Absolute sample error 0..1 */
2404    double                   maxcalcG; /* Absolute sample error 0..1 */
2405    double                   maxpc16;  /* Percentage sample error 0..100% */
2406 
2407    /* This is set by transforms that need to allow a higher limit, it is an
2408     * internal check on pngvalid to ensure that the calculated error limits are
2409     * not ridiculous; without this it is too easy to make a mistake in pngvalid
2410     * that allows any value through.
2411     *
2412     * NOTE: this is not checked in release builds.
2413     */
2414    double                   limit;    /* limit on error values, normally 4E-3 */
2415 
2416    /* Log limits - values above this are logged, but not necessarily
2417     * warned.
2418     */
2419    double                   log8;     /* Absolute error in 8 bits to log */
2420    double                   log16;    /* Absolute error in 16 bits to log */
2421 
2422    /* Logged 8 and 16 bit errors ('output' values): */
2423    double                   error_gray_2;
2424    double                   error_gray_4;
2425    double                   error_gray_8;
2426    double                   error_gray_16;
2427    double                   error_color_8;
2428    double                   error_color_16;
2429    double                   error_indexed;
2430 
2431    /* Flags: */
2432    /* Whether to call png_read_update_info, not png_read_start_image, and how
2433     * many times to call it.
2434     */
2435    int                      use_update_info;
2436 
2437    /* Whether or not to interlace. */
2438    int                      interlace_type :9; /* int, but must store '1' */
2439 
2440    /* Run the standard tests? */
2441    unsigned int             test_standard :1;
2442 
2443    /* Run the odd-sized image and interlace read/write tests? */
2444    unsigned int             test_size :1;
2445 
2446    /* Run tests on reading with a combination of transforms, */
2447    unsigned int             test_transform :1;
2448    unsigned int             test_tRNS :1; /* Includes tRNS images */
2449 
2450    /* When to use the use_input_precision option, this controls the gamma
2451     * validation code checks.  If set any value that is within the transformed
2452     * range input-.5 to input+.5 will be accepted, otherwise the value must be
2453     * within the normal limits.  It should not be necessary to set this; the
2454     * result should always be exact within the permitted error limits.
2455     */
2456    unsigned int             use_input_precision :1;
2457    unsigned int             use_input_precision_sbit :1;
2458    unsigned int             use_input_precision_16to8 :1;
2459 
2460    /* If set assume that the calculation bit depth is set by the input
2461     * precision, not the output precision.
2462     */
2463    unsigned int             calculations_use_input_precision :1;
2464 
2465    /* If set assume that the calculations are done in 16 bits even if the sample
2466     * depth is 8 bits.
2467     */
2468    unsigned int             assume_16_bit_calculations :1;
2469 
2470    /* Which gamma tests to run: */
2471    unsigned int             test_gamma_threshold :1;
2472    unsigned int             test_gamma_transform :1; /* main tests */
2473    unsigned int             test_gamma_sbit :1;
2474    unsigned int             test_gamma_scale16 :1;
2475    unsigned int             test_gamma_background :1;
2476    unsigned int             test_gamma_alpha_mode :1;
2477    unsigned int             test_gamma_expand16 :1;
2478    unsigned int             test_exhaustive :1;
2479 
2480    /* Whether or not to run the low-bit-depth grayscale tests.  This fails on
2481     * gamma images in some cases because of gross inaccuracies in the grayscale
2482     * gamma handling for low bit depth.
2483     */
2484    unsigned int             test_lbg :1;
2485    unsigned int             test_lbg_gamma_threshold :1;
2486    unsigned int             test_lbg_gamma_transform :1;
2487    unsigned int             test_lbg_gamma_sbit :1;
2488    unsigned int             test_lbg_gamma_composition :1;
2489 
2490    unsigned int             log :1;   /* Log max error */
2491 
2492    /* Buffer information, the buffer size limits the size of the chunks that can
2493     * be modified - they must fit (including header and CRC) into the buffer!
2494     */
2495    size_t                   flush;           /* Count of bytes to flush */
2496    size_t                   buffer_count;    /* Bytes in buffer */
2497    size_t                   buffer_position; /* Position in buffer */
2498    png_byte                 buffer[1024];
2499 } png_modifier;
2500 
2501 /* This returns true if the test should be stopped now because it has already
2502  * failed and it is running silently.
2503   */
fail(png_modifier * pm)2504 static int fail(png_modifier *pm)
2505 {
2506    return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
2507        (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
2508 }
2509 
2510 static void
modifier_init(png_modifier * pm)2511 modifier_init(png_modifier *pm)
2512 {
2513    memset(pm, 0, sizeof *pm);
2514    store_init(&pm->this);
2515    pm->modifications = NULL;
2516    pm->state = modifier_start;
2517    pm->sbitlow = 1U;
2518    pm->ngammas = 0;
2519    pm->ngamma_tests = 0;
2520    pm->gammas = 0;
2521    pm->current_gamma = 0;
2522    pm->encodings = 0;
2523    pm->nencodings = 0;
2524    pm->current_encoding = 0;
2525    pm->encoding_counter = 0;
2526    pm->encoding_ignored = 0;
2527    pm->repeat = 0;
2528    pm->test_uses_encoding = 0;
2529    pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
2530    pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
2531    pm->maxcalcG = 0;
2532    pm->limit = 4E-3;
2533    pm->log8 = pm->log16 = 0; /* Means 'off' */
2534    pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
2535    pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
2536    pm->error_indexed = 0;
2537    pm->use_update_info = 0;
2538    pm->interlace_type = PNG_INTERLACE_NONE;
2539    pm->test_standard = 0;
2540    pm->test_size = 0;
2541    pm->test_transform = 0;
2542 #  ifdef PNG_WRITE_tRNS_SUPPORTED
2543       pm->test_tRNS = 1;
2544 #  else
2545       pm->test_tRNS = 0;
2546 #  endif
2547    pm->use_input_precision = 0;
2548    pm->use_input_precision_sbit = 0;
2549    pm->use_input_precision_16to8 = 0;
2550    pm->calculations_use_input_precision = 0;
2551    pm->assume_16_bit_calculations = 0;
2552    pm->test_gamma_threshold = 0;
2553    pm->test_gamma_transform = 0;
2554    pm->test_gamma_sbit = 0;
2555    pm->test_gamma_scale16 = 0;
2556    pm->test_gamma_background = 0;
2557    pm->test_gamma_alpha_mode = 0;
2558    pm->test_gamma_expand16 = 0;
2559    pm->test_lbg = 1;
2560    pm->test_lbg_gamma_threshold = 1;
2561    pm->test_lbg_gamma_transform = 1;
2562    pm->test_lbg_gamma_sbit = 1;
2563    pm->test_lbg_gamma_composition = 1;
2564    pm->test_exhaustive = 0;
2565    pm->log = 0;
2566 
2567    /* Rely on the memset for all the other fields - there are no pointers */
2568 }
2569 
2570 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
2571 
2572 /* This controls use of checks that explicitly know how libpng digitizes the
2573  * samples in calculations; setting this circumvents simple error limit checking
2574  * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
2575  * algorithm.
2576  */
2577 #define DIGITIZE PNG_LIBPNG_VER < 10700
2578 
2579 /* If pm->calculations_use_input_precision is set then operations will happen
2580  * with the precision of the input, not the precision of the output depth.
2581  *
2582  * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
2583  * bit precision.  This only affects those of the following limits that pertain
2584  * to a calculation - not a digitization operation - unless the following API is
2585  * called directly.
2586  */
2587 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2588 #if DIGITIZE
digitize(double value,int depth,int do_round)2589 static double digitize(double value, int depth, int do_round)
2590 {
2591    /* 'value' is in the range 0 to 1, the result is the same value rounded to a
2592     * multiple of the digitization factor - 8 or 16 bits depending on both the
2593     * sample depth and the 'assume' setting.  Digitization is normally by
2594     * rounding and 'do_round' should be 1, if it is 0 the digitized value will
2595     * be truncated.
2596     */
2597    unsigned int digitization_factor = (1U << depth) - 1;
2598 
2599    /* Limiting the range is done as a convenience to the caller - it's easier to
2600     * do it once here than every time at the call site.
2601     */
2602    if (value <= 0)
2603       value = 0;
2604 
2605    else if (value >= 1)
2606       value = 1;
2607 
2608    value *= digitization_factor;
2609    if (do_round) value += .5;
2610    return floor(value)/digitization_factor;
2611 }
2612 #endif
2613 #endif /* RGB_TO_GRAY */
2614 
2615 #ifdef PNG_READ_GAMMA_SUPPORTED
abserr(const png_modifier * pm,int in_depth,int out_depth)2616 static double abserr(const png_modifier *pm, int in_depth, int out_depth)
2617 {
2618    /* Absolute error permitted in linear values - affected by the bit depth of
2619     * the calculations.
2620     */
2621    if (pm->assume_16_bit_calculations ||
2622       (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2623       return pm->maxabs16;
2624    else
2625       return pm->maxabs8;
2626 }
2627 
calcerr(const png_modifier * pm,int in_depth,int out_depth)2628 static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
2629 {
2630    /* Error in the linear composition arithmetic - only relevant when
2631     * composition actually happens (0 < alpha < 1).
2632     */
2633    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2634       return pm->maxcalc16;
2635    else if (pm->assume_16_bit_calculations)
2636       return pm->maxcalcG;
2637    else
2638       return pm->maxcalc8;
2639 }
2640 
pcerr(const png_modifier * pm,int in_depth,int out_depth)2641 static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
2642 {
2643    /* Percentage error permitted in the linear values.  Note that the specified
2644     * value is a percentage but this routine returns a simple number.
2645     */
2646    if (pm->assume_16_bit_calculations ||
2647       (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2648       return pm->maxpc16 * .01;
2649    else
2650       return pm->maxpc8 * .01;
2651 }
2652 
2653 /* Output error - the error in the encoded value.  This is determined by the
2654  * digitization of the output so can be +/-0.5 in the actual output value.  In
2655  * the expand_16 case with the current code in libpng the expand happens after
2656  * all the calculations are done in 8 bit arithmetic, so even though the output
2657  * depth is 16 the output error is determined by the 8 bit calculation.
2658  *
2659  * This limit is not determined by the bit depth of internal calculations.
2660  *
2661  * The specified parameter does *not* include the base .5 digitization error but
2662  * it is added here.
2663  */
outerr(const png_modifier * pm,int in_depth,int out_depth)2664 static double outerr(const png_modifier *pm, int in_depth, int out_depth)
2665 {
2666    /* There is a serious error in the 2 and 4 bit grayscale transform because
2667     * the gamma table value (8 bits) is simply shifted, not rounded, so the
2668     * error in 4 bit grayscale gamma is up to the value below.  This is a hack
2669     * to allow pngvalid to succeed:
2670     *
2671     * TODO: fix this in libpng
2672     */
2673    if (out_depth == 2)
2674       return .73182-.5;
2675 
2676    if (out_depth == 4)
2677       return .90644-.5;
2678 
2679    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2680       return pm->maxout16;
2681 
2682    /* This is the case where the value was calculated at 8-bit precision then
2683     * scaled to 16 bits.
2684     */
2685    else if (out_depth == 16)
2686       return pm->maxout8 * 257;
2687 
2688    else
2689       return pm->maxout8;
2690 }
2691 
2692 /* This does the same thing as the above however it returns the value to log,
2693  * rather than raising a warning.  This is useful for debugging to track down
2694  * exactly what set of parameters cause high error values.
2695  */
outlog(const png_modifier * pm,int in_depth,int out_depth)2696 static double outlog(const png_modifier *pm, int in_depth, int out_depth)
2697 {
2698    /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
2699     * and so must be adjusted for low bit depth grayscale:
2700     */
2701    if (out_depth <= 8)
2702    {
2703       if (pm->log8 == 0) /* switched off */
2704          return 256;
2705 
2706       if (out_depth < 8)
2707          return pm->log8 / 255 * ((1<<out_depth)-1);
2708 
2709       return pm->log8;
2710    }
2711 
2712    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2713    {
2714       if (pm->log16 == 0)
2715          return 65536;
2716 
2717       return pm->log16;
2718    }
2719 
2720    /* This is the case where the value was calculated at 8-bit precision then
2721     * scaled to 16 bits.
2722     */
2723    if (pm->log8 == 0)
2724       return 65536;
2725 
2726    return pm->log8 * 257;
2727 }
2728 
2729 /* This complements the above by providing the appropriate quantization for the
2730  * final value.  Normally this would just be quantization to an integral value,
2731  * but in the 8 bit calculation case it's actually quantization to a multiple of
2732  * 257!
2733  */
output_quantization_factor(const png_modifier * pm,int in_depth,int out_depth)2734 static int output_quantization_factor(const png_modifier *pm, int in_depth,
2735    int out_depth)
2736 {
2737    if (out_depth == 16 && in_depth != 16 &&
2738       pm->calculations_use_input_precision)
2739       return 257;
2740    else
2741       return 1;
2742 }
2743 #endif /* PNG_READ_GAMMA_SUPPORTED */
2744 
2745 /* One modification structure must be provided for each chunk to be modified (in
2746  * fact more than one can be provided if multiple separate changes are desired
2747  * for a single chunk.)  Modifications include adding a new chunk when a
2748  * suitable chunk does not exist.
2749  *
2750  * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
2751  * or 'added' as appropriate if the modify_fn returns 1 (true).  If the
2752  * modify_fn is NULL the chunk is simply removed.
2753  */
2754 typedef struct png_modification
2755 {
2756    struct png_modification *next;
2757    png_uint_32              chunk;
2758 
2759    /* If the following is NULL all matching chunks will be removed: */
2760    int                    (*modify_fn)(struct png_modifier *pm,
2761                                struct png_modification *me, int add);
2762 
2763    /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
2764     * found and modified (and there is a modify_fn) the modify_fn will be called
2765     * to add the chunk before the relevant chunk.
2766     */
2767    png_uint_32              add;
2768    unsigned int             modified :1;     /* Chunk was modified */
2769    unsigned int             added    :1;     /* Chunk was added */
2770    unsigned int             removed  :1;     /* Chunk was removed */
2771 } png_modification;
2772 
2773 static void
modification_reset(png_modification * pmm)2774 modification_reset(png_modification *pmm)
2775 {
2776    if (pmm != NULL)
2777    {
2778       pmm->modified = 0;
2779       pmm->added = 0;
2780       pmm->removed = 0;
2781       modification_reset(pmm->next);
2782    }
2783 }
2784 
2785 static void
modification_init(png_modification * pmm)2786 modification_init(png_modification *pmm)
2787 {
2788    memset(pmm, 0, sizeof *pmm);
2789    pmm->next = NULL;
2790    pmm->chunk = 0;
2791    pmm->modify_fn = NULL;
2792    pmm->add = 0;
2793    modification_reset(pmm);
2794 }
2795 
2796 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2797 static void
modifier_current_encoding(const png_modifier * pm,color_encoding * ce)2798 modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
2799 {
2800    if (pm->current_encoding != 0)
2801       *ce = *pm->current_encoding;
2802 
2803    else
2804       memset(ce, 0, sizeof *ce);
2805 
2806    ce->gamma = pm->current_gamma;
2807 }
2808 #endif
2809 
2810 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
2811 static size_t
safecat_current_encoding(char * buffer,size_t bufsize,size_t pos,const png_modifier * pm)2812 safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
2813    const png_modifier *pm)
2814 {
2815    pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
2816       pm->current_gamma);
2817 
2818    if (pm->encoding_ignored)
2819       pos = safecat(buffer, bufsize, pos, "[overridden]");
2820 
2821    return pos;
2822 }
2823 #endif
2824 
2825 /* Iterate through the usefully testable color encodings.  An encoding is one
2826  * of:
2827  *
2828  * 1) Nothing (no color space, no gamma).
2829  * 2) Just a gamma value from the gamma array (including 1.0)
2830  * 3) A color space from the encodings array with the corresponding gamma.
2831  * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
2832  *
2833  * The iterator selects these in turn, the randomizer selects one at random,
2834  * which is used depends on the setting of the 'test_exhaustive' flag.  Notice
2835  * that this function changes the colour space encoding so it must only be
2836  * called on completion of the previous test.  This is what 'modifier_reset'
2837  * does, below.
2838  *
2839  * After the function has been called the 'repeat' flag will still be set; the
2840  * caller of modifier_reset must reset it at the start of each run of the test!
2841  */
2842 static unsigned int
modifier_total_encodings(const png_modifier * pm)2843 modifier_total_encodings(const png_modifier *pm)
2844 {
2845    return 1 +                 /* (1) nothing */
2846       pm->ngammas +           /* (2) gamma values to test */
2847       pm->nencodings +        /* (3) total number of encodings */
2848       /* The following test only works after the first time through the
2849        * png_modifier code because 'bit_depth' is set when the IHDR is read.
2850        * modifier_reset, below, preserves the setting until after it has called
2851        * the iterate function (also below.)
2852        *
2853        * For this reason do not rely on this function outside a call to
2854        * modifier_reset.
2855        */
2856       ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
2857          pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
2858 }
2859 
2860 static void
modifier_encoding_iterate(png_modifier * pm)2861 modifier_encoding_iterate(png_modifier *pm)
2862 {
2863    if (!pm->repeat && /* Else something needs the current encoding again. */
2864       pm->test_uses_encoding) /* Some transform is encoding dependent */
2865    {
2866       if (pm->test_exhaustive)
2867       {
2868          if (++pm->encoding_counter >= modifier_total_encodings(pm))
2869             pm->encoding_counter = 0; /* This will stop the repeat */
2870       }
2871 
2872       else
2873       {
2874          /* Not exhaustive - choose an encoding at random; generate a number in
2875           * the range 1..(max-1), so the result is always non-zero:
2876           */
2877          if (pm->encoding_counter == 0)
2878             pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
2879          else
2880             pm->encoding_counter = 0;
2881       }
2882 
2883       if (pm->encoding_counter > 0)
2884          pm->repeat = 1;
2885    }
2886 
2887    else if (!pm->repeat)
2888       pm->encoding_counter = 0;
2889 }
2890 
2891 static void
modifier_reset(png_modifier * pm)2892 modifier_reset(png_modifier *pm)
2893 {
2894    store_read_reset(&pm->this);
2895    pm->limit = 4E-3;
2896    pm->pending_len = pm->pending_chunk = 0;
2897    pm->flush = pm->buffer_count = pm->buffer_position = 0;
2898    pm->modifications = NULL;
2899    pm->state = modifier_start;
2900    modifier_encoding_iterate(pm);
2901    /* The following must be set in the next run.  In particular
2902     * test_uses_encodings must be set in the _ini function of each transform
2903     * that looks at the encodings.  (Not the 'add' function!)
2904     */
2905    pm->test_uses_encoding = 0;
2906    pm->current_gamma = 0;
2907    pm->current_encoding = 0;
2908    pm->encoding_ignored = 0;
2909    /* These only become value after IHDR is read: */
2910    pm->bit_depth = pm->colour_type = 0;
2911 }
2912 
2913 /* The following must be called before anything else to get the encoding set up
2914  * on the modifier.  In particular it must be called before the transform init
2915  * functions are called.
2916  */
2917 static void
modifier_set_encoding(png_modifier * pm)2918 modifier_set_encoding(png_modifier *pm)
2919 {
2920    /* Set the encoding to the one specified by the current encoding counter,
2921     * first clear out all the settings - this corresponds to an encoding_counter
2922     * of 0.
2923     */
2924    pm->current_gamma = 0;
2925    pm->current_encoding = 0;
2926    pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
2927 
2928    /* Now, if required, set the gamma and encoding fields. */
2929    if (pm->encoding_counter > 0)
2930    {
2931       /* The gammas[] array is an array of screen gammas, not encoding gammas,
2932        * so we need the inverse:
2933        */
2934       if (pm->encoding_counter <= pm->ngammas)
2935          pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
2936 
2937       else
2938       {
2939          unsigned int i = pm->encoding_counter - pm->ngammas;
2940 
2941          if (i >= pm->nencodings)
2942          {
2943             i %= pm->nencodings;
2944             pm->current_gamma = 1; /* Linear, only in the 16 bit case */
2945          }
2946 
2947          else
2948             pm->current_gamma = pm->encodings[i].gamma;
2949 
2950          pm->current_encoding = pm->encodings + i;
2951       }
2952    }
2953 }
2954 
2955 /* Enquiry functions to find out what is set.  Notice that there is an implicit
2956  * assumption below that the first encoding in the list is the one for sRGB.
2957  */
2958 static int
modifier_color_encoding_is_sRGB(const png_modifier * pm)2959 modifier_color_encoding_is_sRGB(const png_modifier *pm)
2960 {
2961    return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
2962       pm->current_encoding->gamma == pm->current_gamma;
2963 }
2964 
2965 static int
modifier_color_encoding_is_set(const png_modifier * pm)2966 modifier_color_encoding_is_set(const png_modifier *pm)
2967 {
2968    return pm->current_gamma != 0;
2969 }
2970 
2971 /* The guts of modification are performed during a read. */
2972 static void
modifier_crc(png_bytep buffer)2973 modifier_crc(png_bytep buffer)
2974 {
2975    /* Recalculate the chunk CRC - a complete chunk must be in
2976     * the buffer, at the start.
2977     */
2978    uInt datalen = png_get_uint_32(buffer);
2979    uLong crc = crc32(0, buffer+4, datalen+4);
2980    /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
2981     */
2982    png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
2983 }
2984 
2985 static void
modifier_setbuffer(png_modifier * pm)2986 modifier_setbuffer(png_modifier *pm)
2987 {
2988    modifier_crc(pm->buffer);
2989    pm->buffer_count = png_get_uint_32(pm->buffer)+12;
2990    pm->buffer_position = 0;
2991 }
2992 
2993 /* Separate the callback into the actual implementation (which is passed the
2994  * png_modifier explicitly) and the callback, which gets the modifier from the
2995  * png_struct.
2996  */
2997 static void
modifier_read_imp(png_modifier * pm,png_bytep pb,size_t st)2998 modifier_read_imp(png_modifier *pm, png_bytep pb, size_t st)
2999 {
3000    while (st > 0)
3001    {
3002       size_t cb;
3003       png_uint_32 len, chunk;
3004       png_modification *mod;
3005 
3006       if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
3007       {
3008          static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
3009          case modifier_start:
3010             store_read_chunk(&pm->this, pm->buffer, 8, 8); /* signature. */
3011             pm->buffer_count = 8;
3012             pm->buffer_position = 0;
3013 
3014             if (memcmp(pm->buffer, sign, 8) != 0)
3015                png_error(pm->this.pread, "invalid PNG file signature");
3016             pm->state = modifier_signature;
3017             break;
3018 
3019          case modifier_signature:
3020             store_read_chunk(&pm->this, pm->buffer, 13+12, 13+12); /* IHDR */
3021             pm->buffer_count = 13+12;
3022             pm->buffer_position = 0;
3023 
3024             if (png_get_uint_32(pm->buffer) != 13 ||
3025                 png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
3026                png_error(pm->this.pread, "invalid IHDR");
3027 
3028             /* Check the list of modifiers for modifications to the IHDR. */
3029             mod = pm->modifications;
3030             while (mod != NULL)
3031             {
3032                if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
3033                    (*mod->modify_fn)(pm, mod, 0))
3034                   {
3035                   mod->modified = 1;
3036                   modifier_setbuffer(pm);
3037                   }
3038 
3039                /* Ignore removal or add if IHDR! */
3040                mod = mod->next;
3041             }
3042 
3043             /* Cache information from the IHDR (the modified one.) */
3044             pm->bit_depth = pm->buffer[8+8];
3045             pm->colour_type = pm->buffer[8+8+1];
3046 
3047             pm->state = modifier_IHDR;
3048             pm->flush = 0;
3049             break;
3050 
3051          case modifier_IHDR:
3052          default:
3053             /* Read a new chunk and process it until we see PLTE, IDAT or
3054              * IEND.  'flush' indicates that there is still some data to
3055              * output from the preceding chunk.
3056              */
3057             if ((cb = pm->flush) > 0)
3058             {
3059                if (cb > st) cb = st;
3060                pm->flush -= cb;
3061                store_read_chunk(&pm->this, pb, cb, cb);
3062                pb += cb;
3063                st -= cb;
3064                if (st == 0) return;
3065             }
3066 
3067             /* No more bytes to flush, read a header, or handle a pending
3068              * chunk.
3069              */
3070             if (pm->pending_chunk != 0)
3071             {
3072                png_save_uint_32(pm->buffer, pm->pending_len);
3073                png_save_uint_32(pm->buffer+4, pm->pending_chunk);
3074                pm->pending_len = 0;
3075                pm->pending_chunk = 0;
3076             }
3077             else
3078                store_read_chunk(&pm->this, pm->buffer, 8, 8);
3079 
3080             pm->buffer_count = 8;
3081             pm->buffer_position = 0;
3082 
3083             /* Check for something to modify or a terminator chunk. */
3084             len = png_get_uint_32(pm->buffer);
3085             chunk = png_get_uint_32(pm->buffer+4);
3086 
3087             /* Terminators first, they may have to be delayed for added
3088              * chunks
3089              */
3090             if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
3091                 chunk == CHUNK_IEND)
3092             {
3093                mod = pm->modifications;
3094 
3095                while (mod != NULL)
3096                {
3097                   if ((mod->add == chunk ||
3098                       (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
3099                       mod->modify_fn != NULL && !mod->modified && !mod->added)
3100                   {
3101                      /* Regardless of what the modify function does do not run
3102                       * this again.
3103                       */
3104                      mod->added = 1;
3105 
3106                      if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
3107                      {
3108                         /* Reset the CRC on a new chunk */
3109                         if (pm->buffer_count > 0)
3110                            modifier_setbuffer(pm);
3111 
3112                         else
3113                            {
3114                            pm->buffer_position = 0;
3115                            mod->removed = 1;
3116                            }
3117 
3118                         /* The buffer has been filled with something (we assume)
3119                          * so output this.  Pend the current chunk.
3120                          */
3121                         pm->pending_len = len;
3122                         pm->pending_chunk = chunk;
3123                         break; /* out of while */
3124                      }
3125                   }
3126 
3127                   mod = mod->next;
3128                }
3129 
3130                /* Don't do any further processing if the buffer was modified -
3131                 * otherwise the code will end up modifying a chunk that was
3132                 * just added.
3133                 */
3134                if (mod != NULL)
3135                   break; /* out of switch */
3136             }
3137 
3138             /* If we get to here then this chunk may need to be modified.  To
3139              * do this it must be less than 1024 bytes in total size, otherwise
3140              * it just gets flushed.
3141              */
3142             if (len+12 <= sizeof pm->buffer)
3143             {
3144                size_t s = len+12-pm->buffer_count;
3145                store_read_chunk(&pm->this, pm->buffer+pm->buffer_count, s, s);
3146                pm->buffer_count = len+12;
3147 
3148                /* Check for a modification, else leave it be. */
3149                mod = pm->modifications;
3150                while (mod != NULL)
3151                {
3152                   if (mod->chunk == chunk)
3153                   {
3154                      if (mod->modify_fn == NULL)
3155                      {
3156                         /* Remove this chunk */
3157                         pm->buffer_count = pm->buffer_position = 0;
3158                         mod->removed = 1;
3159                         break; /* Terminate the while loop */
3160                      }
3161 
3162                      else if ((*mod->modify_fn)(pm, mod, 0))
3163                      {
3164                         mod->modified = 1;
3165                         /* The chunk may have been removed: */
3166                         if (pm->buffer_count == 0)
3167                         {
3168                            pm->buffer_position = 0;
3169                            break;
3170                         }
3171                         modifier_setbuffer(pm);
3172                      }
3173                   }
3174 
3175                   mod = mod->next;
3176                }
3177             }
3178 
3179             else
3180                pm->flush = len+12 - pm->buffer_count; /* data + crc */
3181 
3182             /* Take the data from the buffer (if there is any). */
3183             break;
3184       }
3185 
3186       /* Here to read from the modifier buffer (not directly from
3187        * the store, as in the flush case above.)
3188        */
3189       cb = pm->buffer_count - pm->buffer_position;
3190 
3191       if (cb > st)
3192          cb = st;
3193 
3194       memcpy(pb, pm->buffer + pm->buffer_position, cb);
3195       st -= cb;
3196       pb += cb;
3197       pm->buffer_position += cb;
3198    }
3199 }
3200 
3201 /* The callback: */
3202 static void PNGCBAPI
modifier_read(png_structp ppIn,png_bytep pb,size_t st)3203 modifier_read(png_structp ppIn, png_bytep pb, size_t st)
3204 {
3205    png_const_structp pp = ppIn;
3206    png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
3207 
3208    if (pm == NULL || pm->this.pread != pp)
3209       png_error(pp, "bad modifier_read call");
3210 
3211    modifier_read_imp(pm, pb, st);
3212 }
3213 
3214 /* Like store_progressive_read but the data is getting changed as we go so we
3215  * need a local buffer.
3216  */
3217 static void
modifier_progressive_read(png_modifier * pm,png_structp pp,png_infop pi)3218 modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
3219 {
3220    if (pm->this.pread != pp || pm->this.current == NULL ||
3221        pm->this.next == NULL)
3222       png_error(pp, "store state damaged (progressive)");
3223 
3224    /* This is another Horowitz and Hill random noise generator.  In this case
3225     * the aim is to stress the progressive reader with truly horrible variable
3226     * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
3227     * is generated.  We could probably just count from 1 to 32767 and get as
3228     * good a result.
3229     */
3230    for (;;)
3231    {
3232       static png_uint_32 noise = 1;
3233       size_t cb, cbAvail;
3234       png_byte buffer[512];
3235 
3236       /* Generate 15 more bits of stuff: */
3237       noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
3238       cb = noise & 0x1ff;
3239 
3240       /* Check that this number of bytes are available (in the current buffer.)
3241        * (This doesn't quite work - the modifier might delete a chunk; unlikely
3242        * but possible, it doesn't happen at present because the modifier only
3243        * adds chunks to standard images.)
3244        */
3245       cbAvail = store_read_buffer_avail(&pm->this);
3246       if (pm->buffer_count > pm->buffer_position)
3247          cbAvail += pm->buffer_count - pm->buffer_position;
3248 
3249       if (cb > cbAvail)
3250       {
3251          /* Check for EOF: */
3252          if (cbAvail == 0)
3253             break;
3254 
3255          cb = cbAvail;
3256       }
3257 
3258       modifier_read_imp(pm, buffer, cb);
3259       png_process_data(pp, pi, buffer, cb);
3260    }
3261 
3262    /* Check the invariants at the end (if this fails it's a problem in this
3263     * file!)
3264     */
3265    if (pm->buffer_count > pm->buffer_position ||
3266        pm->this.next != &pm->this.current->data ||
3267        pm->this.readpos < pm->this.current->datacount)
3268       png_error(pp, "progressive read implementation error");
3269 }
3270 
3271 /* Set up a modifier. */
3272 static png_structp
set_modifier_for_read(png_modifier * pm,png_infopp ppi,png_uint_32 id,const char * name)3273 set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
3274     const char *name)
3275 {
3276    /* Do this first so that the modifier fields are cleared even if an error
3277     * happens allocating the png_struct.  No allocation is done here so no
3278     * cleanup is required.
3279     */
3280    pm->state = modifier_start;
3281    pm->bit_depth = 0;
3282    pm->colour_type = 255;
3283 
3284    pm->pending_len = 0;
3285    pm->pending_chunk = 0;
3286    pm->flush = 0;
3287    pm->buffer_count = 0;
3288    pm->buffer_position = 0;
3289 
3290    return set_store_for_read(&pm->this, ppi, id, name);
3291 }
3292 
3293 
3294 /******************************** MODIFICATIONS *******************************/
3295 /* Standard modifications to add chunks.  These do not require the _SUPPORTED
3296  * macros because the chunks can be there regardless of whether this specific
3297  * libpng supports them.
3298  */
3299 typedef struct gama_modification
3300 {
3301    png_modification this;
3302    png_fixed_point  gamma;
3303 } gama_modification;
3304 
3305 static int
gama_modify(png_modifier * pm,png_modification * me,int add)3306 gama_modify(png_modifier *pm, png_modification *me, int add)
3307 {
3308    UNUSED(add)
3309    /* This simply dumps the given gamma value into the buffer. */
3310    png_save_uint_32(pm->buffer, 4);
3311    png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
3312    png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
3313    return 1;
3314 }
3315 
3316 static void
gama_modification_init(gama_modification * me,png_modifier * pm,double gammad)3317 gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
3318 {
3319    double g;
3320 
3321    modification_init(&me->this);
3322    me->this.chunk = CHUNK_gAMA;
3323    me->this.modify_fn = gama_modify;
3324    me->this.add = CHUNK_PLTE;
3325    g = fix(gammad);
3326    me->gamma = (png_fixed_point)g;
3327    me->this.next = pm->modifications;
3328    pm->modifications = &me->this;
3329 }
3330 
3331 typedef struct chrm_modification
3332 {
3333    png_modification          this;
3334    const color_encoding *encoding;
3335    png_fixed_point           wx, wy, rx, ry, gx, gy, bx, by;
3336 } chrm_modification;
3337 
3338 static int
chrm_modify(png_modifier * pm,png_modification * me,int add)3339 chrm_modify(png_modifier *pm, png_modification *me, int add)
3340 {
3341    UNUSED(add)
3342    /* As with gAMA this just adds the required cHRM chunk to the buffer. */
3343    png_save_uint_32(pm->buffer   , 32);
3344    png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
3345    png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
3346    png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
3347    png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
3348    png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
3349    png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
3350    png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
3351    png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
3352    png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
3353    return 1;
3354 }
3355 
3356 static void
chrm_modification_init(chrm_modification * me,png_modifier * pm,const color_encoding * encoding)3357 chrm_modification_init(chrm_modification *me, png_modifier *pm,
3358    const color_encoding *encoding)
3359 {
3360    CIE_color white = white_point(encoding);
3361 
3362    /* Original end points: */
3363    me->encoding = encoding;
3364 
3365    /* Chromaticities (in fixed point): */
3366    me->wx = fix(chromaticity_x(white));
3367    me->wy = fix(chromaticity_y(white));
3368 
3369    me->rx = fix(chromaticity_x(encoding->red));
3370    me->ry = fix(chromaticity_y(encoding->red));
3371    me->gx = fix(chromaticity_x(encoding->green));
3372    me->gy = fix(chromaticity_y(encoding->green));
3373    me->bx = fix(chromaticity_x(encoding->blue));
3374    me->by = fix(chromaticity_y(encoding->blue));
3375 
3376    modification_init(&me->this);
3377    me->this.chunk = CHUNK_cHRM;
3378    me->this.modify_fn = chrm_modify;
3379    me->this.add = CHUNK_PLTE;
3380    me->this.next = pm->modifications;
3381    pm->modifications = &me->this;
3382 }
3383 
3384 typedef struct srgb_modification
3385 {
3386    png_modification this;
3387    png_byte         intent;
3388 } srgb_modification;
3389 
3390 static int
srgb_modify(png_modifier * pm,png_modification * me,int add)3391 srgb_modify(png_modifier *pm, png_modification *me, int add)
3392 {
3393    UNUSED(add)
3394    /* As above, ignore add and just make a new chunk */
3395    png_save_uint_32(pm->buffer, 1);
3396    png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
3397    pm->buffer[8] = ((srgb_modification*)me)->intent;
3398    return 1;
3399 }
3400 
3401 static void
srgb_modification_init(srgb_modification * me,png_modifier * pm,png_byte intent)3402 srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
3403 {
3404    modification_init(&me->this);
3405    me->this.chunk = CHUNK_sBIT;
3406 
3407    if (intent <= 3) /* if valid, else *delete* sRGB chunks */
3408    {
3409       me->this.modify_fn = srgb_modify;
3410       me->this.add = CHUNK_PLTE;
3411       me->intent = intent;
3412    }
3413 
3414    else
3415    {
3416       me->this.modify_fn = 0;
3417       me->this.add = 0;
3418       me->intent = 0;
3419    }
3420 
3421    me->this.next = pm->modifications;
3422    pm->modifications = &me->this;
3423 }
3424 
3425 #ifdef PNG_READ_GAMMA_SUPPORTED
3426 typedef struct sbit_modification
3427 {
3428    png_modification this;
3429    png_byte         sbit;
3430 } sbit_modification;
3431 
3432 static int
sbit_modify(png_modifier * pm,png_modification * me,int add)3433 sbit_modify(png_modifier *pm, png_modification *me, int add)
3434 {
3435    png_byte sbit = ((sbit_modification*)me)->sbit;
3436    if (pm->bit_depth > sbit)
3437    {
3438       int cb = 0;
3439       switch (pm->colour_type)
3440       {
3441          case 0:
3442             cb = 1;
3443             break;
3444 
3445          case 2:
3446          case 3:
3447             cb = 3;
3448             break;
3449 
3450          case 4:
3451             cb = 2;
3452             break;
3453 
3454          case 6:
3455             cb = 4;
3456             break;
3457 
3458          default:
3459             png_error(pm->this.pread,
3460                "unexpected colour type in sBIT modification");
3461       }
3462 
3463       png_save_uint_32(pm->buffer, cb);
3464       png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
3465 
3466       while (cb > 0)
3467          (pm->buffer+8)[--cb] = sbit;
3468 
3469       return 1;
3470    }
3471    else if (!add)
3472    {
3473       /* Remove the sBIT chunk */
3474       pm->buffer_count = pm->buffer_position = 0;
3475       return 1;
3476    }
3477    else
3478       return 0; /* do nothing */
3479 }
3480 
3481 static void
sbit_modification_init(sbit_modification * me,png_modifier * pm,png_byte sbit)3482 sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
3483 {
3484    modification_init(&me->this);
3485    me->this.chunk = CHUNK_sBIT;
3486    me->this.modify_fn = sbit_modify;
3487    me->this.add = CHUNK_PLTE;
3488    me->sbit = sbit;
3489    me->this.next = pm->modifications;
3490    pm->modifications = &me->this;
3491 }
3492 #endif /* PNG_READ_GAMMA_SUPPORTED */
3493 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
3494 
3495 /***************************** STANDARD PNG FILES *****************************/
3496 /* Standard files - write and save standard files. */
3497 /* There are two basic forms of standard images.  Those which attempt to have
3498  * all the possible pixel values (not possible for 16bpp images, but a range of
3499  * values are produced) and those which have a range of image sizes.  The former
3500  * are used for testing transforms, in particular gamma correction and bit
3501  * reduction and increase.  The latter are reserved for testing the behavior of
3502  * libpng with respect to 'odd' image sizes - particularly small images where
3503  * rows become 1 byte and interlace passes disappear.
3504  *
3505  * The first, most useful, set are the 'transform' images, the second set of
3506  * small images are the 'size' images.
3507  *
3508  * The transform files are constructed with rows which fit into a 1024 byte row
3509  * buffer.  This makes allocation easier below.  Further regardless of the file
3510  * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
3511  *
3512  * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
3513  * and with an ID derived from the colour type, bit depth and interlace type
3514  * as above (FILEID).  The width (128) and height (variable) are not stored in
3515  * the FILEID - instead the fields are set to 0, indicating a transform file.
3516  *
3517  * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
3518  * a maximum width of 16 pixels (for the 64bpp case.)  They also have a maximum
3519  * height of 16 rows.  The width and height are stored in the FILEID and, being
3520  * non-zero, indicate a size file.
3521  *
3522  * Because the PNG filter code is typically the largest CPU consumer within
3523  * libpng itself there is a tendency to attempt to optimize it.  This results in
3524  * special case code which needs to be validated.  To cause this to happen the
3525  * 'size' images are made to use each possible filter, in so far as this is
3526  * possible for smaller images.
3527  *
3528  * For palette image (colour type 3) multiple transform images are stored with
3529  * the same bit depth to allow testing of more colour combinations -
3530  * particularly important for testing the gamma code because libpng uses a
3531  * different code path for palette images.  For size images a single palette is
3532  * used.
3533  */
3534 
3535 /* Make a 'standard' palette.  Because there are only 256 entries in a palette
3536  * (maximum) this actually makes a random palette in the hope that enough tests
3537  * will catch enough errors.  (Note that the same palette isn't produced every
3538  * time for the same test - it depends on what previous tests have been run -
3539  * but a given set of arguments to pngvalid will always produce the same palette
3540  * at the same test!  This is why pseudo-random number generators are useful for
3541  * testing.)
3542  *
3543  * The store must be open for write when this is called, otherwise an internal
3544  * error will occur.  This routine contains its own magic number seed, so the
3545  * palettes generated don't change if there are intervening errors (changing the
3546  * calls to the store_mark seed.)
3547  */
3548 static store_palette_entry *
make_standard_palette(png_store * ps,int npalette,int do_tRNS)3549 make_standard_palette(png_store* ps, int npalette, int do_tRNS)
3550 {
3551    static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
3552 
3553    int i = 0;
3554    png_byte values[256][4];
3555 
3556    /* Always put in black and white plus the six primary and secondary colors.
3557     */
3558    for (; i<8; ++i)
3559    {
3560       values[i][1] = (png_byte)((i&1) ? 255U : 0U);
3561       values[i][2] = (png_byte)((i&2) ? 255U : 0U);
3562       values[i][3] = (png_byte)((i&4) ? 255U : 0U);
3563    }
3564 
3565    /* Then add 62 grays (one quarter of the remaining 256 slots). */
3566    {
3567       int j = 0;
3568       png_byte random_bytes[4];
3569       png_byte need[256];
3570 
3571       need[0] = 0; /*got black*/
3572       memset(need+1, 1, (sizeof need)-2); /*need these*/
3573       need[255] = 0; /*but not white*/
3574 
3575       while (i<70)
3576       {
3577          png_byte b;
3578 
3579          if (j==0)
3580          {
3581             make_four_random_bytes(palette_seed, random_bytes);
3582             j = 4;
3583          }
3584 
3585          b = random_bytes[--j];
3586          if (need[b])
3587          {
3588             values[i][1] = b;
3589             values[i][2] = b;
3590             values[i++][3] = b;
3591          }
3592       }
3593    }
3594 
3595    /* Finally add 192 colors at random - don't worry about matches to things we
3596     * already have, chance is less than 1/65536.  Don't worry about grays,
3597     * chance is the same, so we get a duplicate or extra gray less than 1 time
3598     * in 170.
3599     */
3600    for (; i<256; ++i)
3601       make_four_random_bytes(palette_seed, values[i]);
3602 
3603    /* Fill in the alpha values in the first byte.  Just use all possible values
3604     * (0..255) in an apparently random order:
3605     */
3606    {
3607       store_palette_entry *palette;
3608       png_byte selector[4];
3609 
3610       make_four_random_bytes(palette_seed, selector);
3611 
3612       if (do_tRNS)
3613          for (i=0; i<256; ++i)
3614             values[i][0] = (png_byte)(i ^ selector[0]);
3615 
3616       else
3617          for (i=0; i<256; ++i)
3618             values[i][0] = 255; /* no transparency/tRNS chunk */
3619 
3620       /* 'values' contains 256 ARGB values, but we only need 'npalette'.
3621        * 'npalette' will always be a power of 2: 2, 4, 16 or 256.  In the low
3622        * bit depth cases select colors at random, else it is difficult to have
3623        * a set of low bit depth palette test with any chance of a reasonable
3624        * range of colors.  Do this by randomly permuting values into the low
3625        * 'npalette' entries using an XOR mask generated here.  This also
3626        * permutes the npalette == 256 case in a potentially useful way (there is
3627        * no relationship between palette index and the color value therein!)
3628        */
3629       palette = store_write_palette(ps, npalette);
3630 
3631       for (i=0; i<npalette; ++i)
3632       {
3633          palette[i].alpha = values[i ^ selector[1]][0];
3634          palette[i].red   = values[i ^ selector[1]][1];
3635          palette[i].green = values[i ^ selector[1]][2];
3636          palette[i].blue  = values[i ^ selector[1]][3];
3637       }
3638 
3639       return palette;
3640    }
3641 }
3642 
3643 /* Initialize a standard palette on a write stream.  The 'do_tRNS' argument
3644  * indicates whether or not to also set the tRNS chunk.
3645  */
3646 /* TODO: the png_structp here can probably be 'const' in the future */
3647 static void
init_standard_palette(png_store * ps,png_structp pp,png_infop pi,int npalette,int do_tRNS)3648 init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
3649    int do_tRNS)
3650 {
3651    store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
3652 
3653    {
3654       int i;
3655       png_color palette[256];
3656 
3657       /* Set all entries to detect overread errors. */
3658       for (i=0; i<npalette; ++i)
3659       {
3660          palette[i].red = ppal[i].red;
3661          palette[i].green = ppal[i].green;
3662          palette[i].blue = ppal[i].blue;
3663       }
3664 
3665       /* Just in case fill in the rest with detectable values: */
3666       for (; i<256; ++i)
3667          palette[i].red = palette[i].green = palette[i].blue = 42;
3668 
3669       png_set_PLTE(pp, pi, palette, npalette);
3670    }
3671 
3672    if (do_tRNS)
3673    {
3674       int i, j;
3675       png_byte tRNS[256];
3676 
3677       /* Set all the entries, but skip trailing opaque entries */
3678       for (i=j=0; i<npalette; ++i)
3679          if ((tRNS[i] = ppal[i].alpha) < 255)
3680             j = i+1;
3681 
3682       /* Fill in the remainder with a detectable value: */
3683       for (; i<256; ++i)
3684          tRNS[i] = 24;
3685 
3686 #ifdef PNG_WRITE_tRNS_SUPPORTED
3687       if (j > 0)
3688          png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
3689 #endif
3690    }
3691 }
3692 
3693 #ifdef PNG_WRITE_tRNS_SUPPORTED
3694 static void
set_random_tRNS(png_structp pp,png_infop pi,png_byte colour_type,int bit_depth)3695 set_random_tRNS(png_structp pp, png_infop pi, png_byte colour_type,
3696    int bit_depth)
3697 {
3698    /* To make this useful the tRNS color needs to match at least one pixel.
3699     * Random values are fine for gray, including the 16-bit case where we know
3700     * that the test image contains all the gray values.  For RGB we need more
3701     * method as only 65536 different RGB values are generated.
3702     */
3703    png_color_16 tRNS;
3704    png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
3705 
3706    R8(tRNS); /* makes unset fields random */
3707 
3708    if (colour_type & 2/*RGB*/)
3709    {
3710       if (bit_depth == 8)
3711       {
3712          tRNS.red = random_u16();
3713          tRNS.green = random_u16();
3714          tRNS.blue = tRNS.red ^ tRNS.green;
3715          tRNS.red &= mask;
3716          tRNS.green &= mask;
3717          tRNS.blue &= mask;
3718       }
3719 
3720       else /* bit_depth == 16 */
3721       {
3722          tRNS.red = random_u16();
3723          tRNS.green = (png_uint_16)(tRNS.red * 257);
3724          tRNS.blue = (png_uint_16)(tRNS.green * 17);
3725       }
3726    }
3727 
3728    else
3729    {
3730       tRNS.gray = random_u16();
3731       tRNS.gray &= mask;
3732    }
3733 
3734    png_set_tRNS(pp, pi, NULL, 0, &tRNS);
3735 }
3736 #endif
3737 
3738 /* The number of passes is related to the interlace type. There was no libpng
3739  * API to determine this prior to 1.5, so we need an inquiry function:
3740  */
3741 static int
npasses_from_interlace_type(png_const_structp pp,int interlace_type)3742 npasses_from_interlace_type(png_const_structp pp, int interlace_type)
3743 {
3744    switch (interlace_type)
3745    {
3746    default:
3747       png_error(pp, "invalid interlace type");
3748 
3749    case PNG_INTERLACE_NONE:
3750       return 1;
3751 
3752    case PNG_INTERLACE_ADAM7:
3753       return PNG_INTERLACE_ADAM7_PASSES;
3754    }
3755 }
3756 
3757 static unsigned int
bit_size(png_const_structp pp,png_byte colour_type,png_byte bit_depth)3758 bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3759 {
3760    switch (colour_type)
3761    {
3762       default: png_error(pp, "invalid color type");
3763 
3764       case 0:  return bit_depth;
3765 
3766       case 2:  return 3*bit_depth;
3767 
3768       case 3:  return bit_depth;
3769 
3770       case 4:  return 2*bit_depth;
3771 
3772       case 6:  return 4*bit_depth;
3773    }
3774 }
3775 
3776 #define TRANSFORM_WIDTH  128U
3777 #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
3778 #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
3779 #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
3780 #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
3781 
3782 static size_t
transform_rowsize(png_const_structp pp,png_byte colour_type,png_byte bit_depth)3783 transform_rowsize(png_const_structp pp, png_byte colour_type,
3784    png_byte bit_depth)
3785 {
3786    return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
3787 }
3788 
3789 /* transform_width(pp, colour_type, bit_depth) current returns the same number
3790  * every time, so just use a macro:
3791  */
3792 #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
3793 
3794 static png_uint_32
transform_height(png_const_structp pp,png_byte colour_type,png_byte bit_depth)3795 transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3796 {
3797    switch (bit_size(pp, colour_type, bit_depth))
3798    {
3799       case 1:
3800       case 2:
3801       case 4:
3802          return 1;   /* Total of 128 pixels */
3803 
3804       case 8:
3805          return 2;   /* Total of 256 pixels/bytes */
3806 
3807       case 16:
3808          return 512; /* Total of 65536 pixels */
3809 
3810       case 24:
3811       case 32:
3812          return 512; /* 65536 pixels */
3813 
3814       case 48:
3815       case 64:
3816          return 2048;/* 4 x 65536 pixels. */
3817 #        define TRANSFORM_HEIGHTMAX 2048
3818 
3819       default:
3820          return 0;   /* Error, will be caught later */
3821    }
3822 }
3823 
3824 #ifdef PNG_READ_SUPPORTED
3825 /* The following can only be defined here, now we have the definitions
3826  * of the transform image sizes.
3827  */
3828 static png_uint_32
standard_width(png_const_structp pp,png_uint_32 id)3829 standard_width(png_const_structp pp, png_uint_32 id)
3830 {
3831    png_uint_32 width = WIDTH_FROM_ID(id);
3832    UNUSED(pp)
3833 
3834    if (width == 0)
3835       width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3836 
3837    return width;
3838 }
3839 
3840 static png_uint_32
standard_height(png_const_structp pp,png_uint_32 id)3841 standard_height(png_const_structp pp, png_uint_32 id)
3842 {
3843    png_uint_32 height = HEIGHT_FROM_ID(id);
3844 
3845    if (height == 0)
3846       height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3847 
3848    return height;
3849 }
3850 
3851 static png_uint_32
standard_rowsize(png_const_structp pp,png_uint_32 id)3852 standard_rowsize(png_const_structp pp, png_uint_32 id)
3853 {
3854    png_uint_32 width = standard_width(pp, id);
3855 
3856    /* This won't overflow: */
3857    width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3858    return (width + 7) / 8;
3859 }
3860 #endif /* PNG_READ_SUPPORTED */
3861 
3862 static void
transform_row(png_const_structp pp,png_byte buffer[TRANSFORM_ROWMAX],png_byte colour_type,png_byte bit_depth,png_uint_32 y)3863 transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
3864    png_byte colour_type, png_byte bit_depth, png_uint_32 y)
3865 {
3866    png_uint_32 v = y << 7;
3867    png_uint_32 i = 0;
3868 
3869    switch (bit_size(pp, colour_type, bit_depth))
3870    {
3871       case 1:
3872          while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
3873          return;
3874 
3875       case 2:
3876          while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
3877          return;
3878 
3879       case 4:
3880          while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
3881          return;
3882 
3883       case 8:
3884          /* 256 bytes total, 128 bytes in each row set as follows: */
3885          while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
3886          return;
3887 
3888       case 16:
3889          /* Generate all 65536 pixel values in order, which includes the 8 bit
3890           * GA case as well as the 16 bit G case.
3891           */
3892          while (i<128)
3893          {
3894             buffer[2*i] = (png_byte)((v>>8) & 0xff);
3895             buffer[2*i+1] = (png_byte)(v & 0xff);
3896             ++v;
3897             ++i;
3898          }
3899 
3900          return;
3901 
3902       case 24:
3903          /* 65535 pixels, but rotate the values. */
3904          while (i<128)
3905          {
3906             /* Three bytes per pixel, r, g, b, make b by r^g */
3907             buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
3908             buffer[3*i+1] = (png_byte)(v & 0xff);
3909             buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
3910             ++v;
3911             ++i;
3912          }
3913 
3914          return;
3915 
3916       case 32:
3917          /* 65535 pixels, r, g, b, a; just replicate */
3918          while (i<128)
3919          {
3920             buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
3921             buffer[4*i+1] = (png_byte)(v & 0xff);
3922             buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
3923             buffer[4*i+3] = (png_byte)(v & 0xff);
3924             ++v;
3925             ++i;
3926          }
3927 
3928          return;
3929 
3930       case 48:
3931          /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
3932           * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
3933           */
3934          while (i<128)
3935          {
3936             png_uint_32 t = v++;
3937             buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
3938             buffer[6*i+1] = (png_byte)(t & 0xff);
3939             t *= 257;
3940             buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
3941             buffer[6*i+3] = (png_byte)(t & 0xff);
3942             t *= 17;
3943             buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
3944             buffer[6*i+5] = (png_byte)(t & 0xff);
3945             ++i;
3946          }
3947 
3948          return;
3949 
3950       case 64:
3951          /* As above in the 32 bit case. */
3952          while (i<128)
3953          {
3954             png_uint_32 t = v++;
3955             buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
3956             buffer[8*i+1] = (png_byte)(t & 0xff);
3957             buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
3958             buffer[8*i+5] = (png_byte)(t & 0xff);
3959             t *= 257;
3960             buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
3961             buffer[8*i+3] = (png_byte)(t & 0xff);
3962             buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
3963             buffer[8*i+7] = (png_byte)(t & 0xff);
3964             ++i;
3965          }
3966          return;
3967 
3968       default:
3969          break;
3970    }
3971 
3972    png_error(pp, "internal error");
3973 }
3974 
3975 /* This is just to do the right cast - could be changed to a function to check
3976  * 'bd' but there isn't much point.
3977  */
3978 #define DEPTH(bd) ((png_byte)(1U << (bd)))
3979 
3980 /* This is just a helper for compiling on minimal systems with no write
3981  * interlacing support.  If there is no write interlacing we can't generate test
3982  * cases with interlace:
3983  */
3984 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
3985 #  define INTERLACE_LAST PNG_INTERLACE_LAST
3986 #  define check_interlace_type(type) ((void)(type))
3987 #  define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
3988 #  define do_own_interlace 0
3989 #elif PNG_LIBPNG_VER < 10700
3990 #  define set_write_interlace_handling(pp,type) (1)
3991 static void
check_interlace_type(int const interlace_type)3992 check_interlace_type(int const interlace_type)
3993 {
3994    /* Prior to 1.7.0 libpng does not support the write of an interlaced image
3995     * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
3996     * code here does the pixel interlace itself, so:
3997     */
3998    if (interlace_type != PNG_INTERLACE_NONE)
3999    {
4000       /* This is an internal error - --interlace tests should be skipped, not
4001        * attempted.
4002        */
4003       fprintf(stderr, "pngvalid: no interlace support\n");
4004       exit(99);
4005    }
4006 }
4007 #  define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
4008 #  define do_own_interlace 0
4009 #else /* libpng 1.7+ */
4010 #  define set_write_interlace_handling(pp,type)\
4011       npasses_from_interlace_type(pp,type)
4012 #  define check_interlace_type(type) ((void)(type))
4013 #  define INTERLACE_LAST PNG_INTERLACE_LAST
4014 #  define do_own_interlace 1
4015 #endif /* WRITE_INTERLACING tests */
4016 
4017 #if PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
4018 #   define CAN_WRITE_INTERLACE 1
4019 #else
4020 #   define CAN_WRITE_INTERLACE 0
4021 #endif
4022 
4023 /* Do the same thing for read interlacing; this controls whether read tests do
4024  * their own de-interlace or use libpng.
4025  */
4026 #ifdef PNG_READ_INTERLACING_SUPPORTED
4027 #  define do_read_interlace 0
4028 #else /* no libpng read interlace support */
4029 #  define do_read_interlace 1
4030 #endif
4031 /* The following two routines use the PNG interlace support macros from
4032  * png.h to interlace or deinterlace rows.
4033  */
4034 static void
interlace_row(png_bytep buffer,png_const_bytep imageRow,unsigned int pixel_size,png_uint_32 w,int pass,int littleendian)4035 interlace_row(png_bytep buffer, png_const_bytep imageRow,
4036    unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
4037 {
4038    png_uint_32 xin, xout, xstep;
4039 
4040    /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
4041     * code is presented this way to make it easier to understand.  In practice
4042     * consult the code in the libpng source to see other ways of doing this.
4043     *
4044     * It is OK for buffer and imageRow to be identical, because 'xin' moves
4045     * faster than 'xout' and we copy up.
4046     */
4047    xin = PNG_PASS_START_COL(pass);
4048    xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
4049 
4050    for (xout=0; xin<w; xin+=xstep)
4051    {
4052       pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
4053       ++xout;
4054    }
4055 }
4056 
4057 #ifdef PNG_READ_SUPPORTED
4058 static void
deinterlace_row(png_bytep buffer,png_const_bytep row,unsigned int pixel_size,png_uint_32 w,int pass,int littleendian)4059 deinterlace_row(png_bytep buffer, png_const_bytep row,
4060    unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
4061 {
4062    /* The inverse of the above, 'row' is part of row 'y' of the output image,
4063     * in 'buffer'.  The image is 'w' wide and this is pass 'pass', distribute
4064     * the pixels of row into buffer and return the number written (to allow
4065     * this to be checked).
4066     */
4067    png_uint_32 xin, xout, xstep;
4068 
4069    xout = PNG_PASS_START_COL(pass);
4070    xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
4071 
4072    for (xin=0; xout<w; xout+=xstep)
4073    {
4074       pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
4075       ++xin;
4076    }
4077 }
4078 #endif /* PNG_READ_SUPPORTED */
4079 
4080 /* Make a standardized image given an image colour type, bit depth and
4081  * interlace type.  The standard images have a very restricted range of
4082  * rows and heights and are used for testing transforms rather than image
4083  * layout details.  See make_size_images below for a way to make images
4084  * that test odd sizes along with the libpng interlace handling.
4085  */
4086 #ifdef PNG_WRITE_FILTER_SUPPORTED
4087 static void
choose_random_filter(png_structp pp,int start)4088 choose_random_filter(png_structp pp, int start)
4089 {
4090    /* Choose filters randomly except that on the very first row ensure that
4091     * there is at least one previous row filter.
4092     */
4093    int filters = PNG_ALL_FILTERS & random_mod(256U);
4094 
4095    /* There may be no filters; skip the setting. */
4096    if (filters != 0)
4097    {
4098       if (start && filters < PNG_FILTER_UP)
4099          filters |= PNG_FILTER_UP;
4100 
4101       png_set_filter(pp, 0/*method*/, filters);
4102    }
4103 }
4104 #else /* !WRITE_FILTER */
4105 #  define choose_random_filter(pp, start) ((void)0)
4106 #endif /* !WRITE_FILTER */
4107 
4108 static void
make_transform_image(png_store * const ps,png_byte const colour_type,png_byte const bit_depth,unsigned int palette_number,int interlace_type,png_const_charp name)4109 make_transform_image(png_store* const ps, png_byte const colour_type,
4110     png_byte const bit_depth, unsigned int palette_number,
4111     int interlace_type, png_const_charp name)
4112 {
4113    context(ps, fault);
4114 
4115    check_interlace_type(interlace_type);
4116 
4117    Try
4118    {
4119       png_infop pi;
4120       png_structp pp = set_store_for_write(ps, &pi, name);
4121       png_uint_32 h, w;
4122 
4123       /* In the event of a problem return control to the Catch statement below
4124        * to do the clean up - it is not possible to 'return' directly from a Try
4125        * block.
4126        */
4127       if (pp == NULL)
4128          Throw ps;
4129 
4130       w = transform_width(pp, colour_type, bit_depth);
4131       h = transform_height(pp, colour_type, bit_depth);
4132 
4133       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4134          PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4135 
4136 #ifdef PNG_TEXT_SUPPORTED
4137 #  if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
4138 #     define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
4139 #  else
4140 #     define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
4141 #  endif
4142       {
4143          static char key[] = "image name"; /* must be writeable */
4144          size_t pos;
4145          png_text text;
4146          char copy[FILE_NAME_SIZE];
4147 
4148          /* Use a compressed text string to test the correct interaction of text
4149           * compression and IDAT compression.
4150           */
4151          text.compression = TEXT_COMPRESSION;
4152          text.key = key;
4153          /* Yuck: the text must be writable! */
4154          pos = safecat(copy, sizeof copy, 0, ps->wname);
4155          text.text = copy;
4156          text.text_length = pos;
4157          text.itxt_length = 0;
4158          text.lang = 0;
4159          text.lang_key = 0;
4160 
4161          png_set_text(pp, pi, &text, 1);
4162       }
4163 #endif
4164 
4165       if (colour_type == 3) /* palette */
4166          init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
4167 
4168 #     ifdef PNG_WRITE_tRNS_SUPPORTED
4169          else if (palette_number)
4170             set_random_tRNS(pp, pi, colour_type, bit_depth);
4171 #     endif
4172 
4173       png_write_info(pp, pi);
4174 
4175       if (png_get_rowbytes(pp, pi) !=
4176           transform_rowsize(pp, colour_type, bit_depth))
4177          png_error(pp, "transform row size incorrect");
4178 
4179       else
4180       {
4181          /* Somewhat confusingly this must be called *after* png_write_info
4182           * because if it is called before, the information in *pp has not been
4183           * updated to reflect the interlaced image.
4184           */
4185          int npasses = set_write_interlace_handling(pp, interlace_type);
4186          int pass;
4187 
4188          if (npasses != npasses_from_interlace_type(pp, interlace_type))
4189             png_error(pp, "write: png_set_interlace_handling failed");
4190 
4191          for (pass=0; pass<npasses; ++pass)
4192          {
4193             png_uint_32 y;
4194 
4195             /* do_own_interlace is a pre-defined boolean (a #define) which is
4196              * set if we have to work out the interlaced rows here.
4197              */
4198             for (y=0; y<h; ++y)
4199             {
4200                png_byte buffer[TRANSFORM_ROWMAX];
4201 
4202                transform_row(pp, buffer, colour_type, bit_depth, y);
4203 
4204 #              if do_own_interlace
4205                   /* If do_own_interlace *and* the image is interlaced we need a
4206                    * reduced interlace row; this may be reduced to empty.
4207                    */
4208                   if (interlace_type == PNG_INTERLACE_ADAM7)
4209                   {
4210                      /* The row must not be written if it doesn't exist, notice
4211                       * that there are two conditions here, either the row isn't
4212                       * ever in the pass or the row would be but isn't wide
4213                       * enough to contribute any pixels.  In fact the wPass test
4214                       * can be used to skip the whole y loop in this case.
4215                       */
4216                      if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4217                          PNG_PASS_COLS(w, pass) > 0)
4218                         interlace_row(buffer, buffer,
4219                               bit_size(pp, colour_type, bit_depth), w, pass,
4220                               0/*data always bigendian*/);
4221                      else
4222                         continue;
4223                   }
4224 #              endif /* do_own_interlace */
4225 
4226                choose_random_filter(pp, pass == 0 && y == 0);
4227                png_write_row(pp, buffer);
4228             }
4229          }
4230       }
4231 
4232 #ifdef PNG_TEXT_SUPPORTED
4233       {
4234          static char key[] = "end marker";
4235          static char comment[] = "end";
4236          png_text text;
4237 
4238          /* Use a compressed text string to test the correct interaction of text
4239           * compression and IDAT compression.
4240           */
4241          text.compression = TEXT_COMPRESSION;
4242          text.key = key;
4243          text.text = comment;
4244          text.text_length = (sizeof comment)-1;
4245          text.itxt_length = 0;
4246          text.lang = 0;
4247          text.lang_key = 0;
4248 
4249          png_set_text(pp, pi, &text, 1);
4250       }
4251 #endif
4252 
4253       png_write_end(pp, pi);
4254 
4255       /* And store this under the appropriate id, then clean up. */
4256       store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
4257          interlace_type, 0, 0, 0));
4258 
4259       store_write_reset(ps);
4260    }
4261 
4262    Catch(fault)
4263    {
4264       /* Use the png_store returned by the exception. This may help the compiler
4265        * because 'ps' is not used in this branch of the setjmp.  Note that fault
4266        * and ps will always be the same value.
4267        */
4268       store_write_reset(fault);
4269    }
4270 }
4271 
4272 static void
make_transform_images(png_modifier * pm)4273 make_transform_images(png_modifier *pm)
4274 {
4275    png_byte colour_type = 0;
4276    png_byte bit_depth = 0;
4277    unsigned int palette_number = 0;
4278 
4279    /* This is in case of errors. */
4280    safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
4281 
4282    /* Use next_format to enumerate all the combinations we test, including
4283     * generating multiple low bit depth palette images. Non-A images (palette
4284     * and direct) are created with and without tRNS chunks.
4285     */
4286    while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
4287    {
4288       int interlace_type;
4289 
4290       for (interlace_type = PNG_INTERLACE_NONE;
4291            interlace_type < INTERLACE_LAST; ++interlace_type)
4292       {
4293          char name[FILE_NAME_SIZE];
4294 
4295          standard_name(name, sizeof name, 0, colour_type, bit_depth,
4296             palette_number, interlace_type, 0, 0, do_own_interlace);
4297          make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
4298             interlace_type, name);
4299       }
4300    }
4301 }
4302 
4303 /* Build a single row for the 'size' test images; this fills in only the
4304  * first bit_width bits of the sample row.
4305  */
4306 static void
size_row(png_byte buffer[SIZE_ROWMAX],png_uint_32 bit_width,png_uint_32 y)4307 size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
4308 {
4309    /* height is in the range 1 to 16, so: */
4310    y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
4311    /* the following ensures bits are set in small images: */
4312    y ^= 0xA5;
4313 
4314    while (bit_width >= 8)
4315       *buffer++ = (png_byte)y++, bit_width -= 8;
4316 
4317    /* There may be up to 7 remaining bits, these go in the most significant
4318     * bits of the byte.
4319     */
4320    if (bit_width > 0)
4321    {
4322       png_uint_32 mask = (1U<<(8-bit_width))-1;
4323       *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
4324    }
4325 }
4326 
4327 static void
make_size_image(png_store * const ps,png_byte const colour_type,png_byte const bit_depth,int const interlace_type,png_uint_32 const w,png_uint_32 const h,int const do_interlace)4328 make_size_image(png_store* const ps, png_byte const colour_type,
4329     png_byte const bit_depth, int const interlace_type,
4330     png_uint_32 const w, png_uint_32 const h,
4331     int const do_interlace)
4332 {
4333    context(ps, fault);
4334 
4335    check_interlace_type(interlace_type);
4336 
4337    Try
4338    {
4339       png_infop pi;
4340       png_structp pp;
4341       unsigned int pixel_size;
4342 
4343       /* Make a name and get an appropriate id for the store: */
4344       char name[FILE_NAME_SIZE];
4345       png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
4346          interlace_type, w, h, do_interlace);
4347 
4348       standard_name_from_id(name, sizeof name, 0, id);
4349       pp = set_store_for_write(ps, &pi, name);
4350 
4351       /* In the event of a problem return control to the Catch statement below
4352        * to do the clean up - it is not possible to 'return' directly from a Try
4353        * block.
4354        */
4355       if (pp == NULL)
4356          Throw ps;
4357 
4358       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4359          PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4360 
4361 #ifdef PNG_TEXT_SUPPORTED
4362       {
4363          static char key[] = "image name"; /* must be writeable */
4364          size_t pos;
4365          png_text text;
4366          char copy[FILE_NAME_SIZE];
4367 
4368          /* Use a compressed text string to test the correct interaction of text
4369           * compression and IDAT compression.
4370           */
4371          text.compression = TEXT_COMPRESSION;
4372          text.key = key;
4373          /* Yuck: the text must be writable! */
4374          pos = safecat(copy, sizeof copy, 0, ps->wname);
4375          text.text = copy;
4376          text.text_length = pos;
4377          text.itxt_length = 0;
4378          text.lang = 0;
4379          text.lang_key = 0;
4380 
4381          png_set_text(pp, pi, &text, 1);
4382       }
4383 #endif
4384 
4385       if (colour_type == 3) /* palette */
4386          init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4387 
4388       png_write_info(pp, pi);
4389 
4390       /* Calculate the bit size, divide by 8 to get the byte size - this won't
4391        * overflow because we know the w values are all small enough even for
4392        * a system where 'unsigned int' is only 16 bits.
4393        */
4394       pixel_size = bit_size(pp, colour_type, bit_depth);
4395       if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
4396          png_error(pp, "size row size incorrect");
4397 
4398       else
4399       {
4400          int npasses = npasses_from_interlace_type(pp, interlace_type);
4401          png_uint_32 y;
4402          int pass;
4403          png_byte image[16][SIZE_ROWMAX];
4404 
4405          /* To help consistent error detection make the parts of this buffer
4406           * that aren't set below all '1':
4407           */
4408          memset(image, 0xff, sizeof image);
4409 
4410          if (!do_interlace &&
4411              npasses != set_write_interlace_handling(pp, interlace_type))
4412             png_error(pp, "write: png_set_interlace_handling failed");
4413 
4414          /* Prepare the whole image first to avoid making it 7 times: */
4415          for (y=0; y<h; ++y)
4416             size_row(image[y], w * pixel_size, y);
4417 
4418          for (pass=0; pass<npasses; ++pass)
4419          {
4420             /* The following two are for checking the macros: */
4421             png_uint_32 wPass = PNG_PASS_COLS(w, pass);
4422 
4423             /* If do_interlace is set we don't call png_write_row for every
4424              * row because some of them are empty.  In fact, for a 1x1 image,
4425              * most of them are empty!
4426              */
4427             for (y=0; y<h; ++y)
4428             {
4429                png_const_bytep row = image[y];
4430                png_byte tempRow[SIZE_ROWMAX];
4431 
4432                /* If do_interlace *and* the image is interlaced we
4433                 * need a reduced interlace row; this may be reduced
4434                 * to empty.
4435                 */
4436                if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
4437                {
4438                   /* The row must not be written if it doesn't exist, notice
4439                    * that there are two conditions here, either the row isn't
4440                    * ever in the pass or the row would be but isn't wide
4441                    * enough to contribute any pixels.  In fact the wPass test
4442                    * can be used to skip the whole y loop in this case.
4443                    */
4444                   if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
4445                   {
4446                      /* Set to all 1's for error detection (libpng tends to
4447                       * set unset things to 0).
4448                       */
4449                      memset(tempRow, 0xff, sizeof tempRow);
4450                      interlace_row(tempRow, row, pixel_size, w, pass,
4451                            0/*data always bigendian*/);
4452                      row = tempRow;
4453                   }
4454                   else
4455                      continue;
4456                }
4457 
4458 #           ifdef PNG_WRITE_FILTER_SUPPORTED
4459                /* Only get to here if the row has some pixels in it, set the
4460                 * filters to 'all' for the very first row and thereafter to a
4461                 * single filter.  It isn't well documented, but png_set_filter
4462                 * does accept a filter number (per the spec) as well as a bit
4463                 * mask.
4464                 *
4465                 * The code now uses filters at random, except that on the first
4466                 * row of an image it ensures that a previous row filter is in
4467                 * the set so that libpng allocates the row buffer.
4468                 */
4469                {
4470                   int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST);
4471 
4472                   if (pass == 0 && y == 0 &&
4473                       (filters < PNG_FILTER_UP || w == 1U))
4474                      filters |= PNG_FILTER_UP;
4475 
4476                   png_set_filter(pp, 0/*method*/, filters);
4477                }
4478 #           endif
4479 
4480                png_write_row(pp, row);
4481             }
4482          }
4483       }
4484 
4485 #ifdef PNG_TEXT_SUPPORTED
4486       {
4487          static char key[] = "end marker";
4488          static char comment[] = "end";
4489          png_text text;
4490 
4491          /* Use a compressed text string to test the correct interaction of text
4492           * compression and IDAT compression.
4493           */
4494          text.compression = TEXT_COMPRESSION;
4495          text.key = key;
4496          text.text = comment;
4497          text.text_length = (sizeof comment)-1;
4498          text.itxt_length = 0;
4499          text.lang = 0;
4500          text.lang_key = 0;
4501 
4502          png_set_text(pp, pi, &text, 1);
4503       }
4504 #endif
4505 
4506       png_write_end(pp, pi);
4507 
4508       /* And store this under the appropriate id, then clean up. */
4509       store_storefile(ps, id);
4510 
4511       store_write_reset(ps);
4512    }
4513 
4514    Catch(fault)
4515    {
4516       /* Use the png_store returned by the exception. This may help the compiler
4517        * because 'ps' is not used in this branch of the setjmp.  Note that fault
4518        * and ps will always be the same value.
4519        */
4520       store_write_reset(fault);
4521    }
4522 }
4523 
4524 static void
make_size(png_store * const ps,png_byte const colour_type,int bdlo,int const bdhi)4525 make_size(png_store* const ps, png_byte const colour_type, int bdlo,
4526     int const bdhi)
4527 {
4528    for (; bdlo <= bdhi; ++bdlo)
4529    {
4530       png_uint_32 width;
4531 
4532       for (width = 1; width <= 16; ++width)
4533       {
4534          png_uint_32 height;
4535 
4536          for (height = 1; height <= 16; ++height)
4537          {
4538             /* The four combinations of DIY interlace and interlace or not -
4539              * no interlace + DIY should be identical to no interlace with
4540              * libpng doing it.
4541              */
4542             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4543                width, height, 0);
4544             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4545                width, height, 1);
4546 #        ifdef PNG_WRITE_INTERLACING_SUPPORTED
4547             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4548                width, height, 0);
4549 #        endif
4550 #        if CAN_WRITE_INTERLACE
4551             /* 1.7.0 removes the hack that prevented app write of an interlaced
4552              * image if WRITE_INTERLACE was not supported
4553              */
4554             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4555                width, height, 1);
4556 #        endif
4557          }
4558       }
4559    }
4560 }
4561 
4562 static void
make_size_images(png_store * ps)4563 make_size_images(png_store *ps)
4564 {
4565    /* This is in case of errors. */
4566    safecat(ps->test, sizeof ps->test, 0, "make size images");
4567 
4568    /* Arguments are colour_type, low bit depth, high bit depth
4569     */
4570    make_size(ps, 0, 0, WRITE_BDHI);
4571    make_size(ps, 2, 3, WRITE_BDHI);
4572    make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
4573    make_size(ps, 4, 3, WRITE_BDHI);
4574    make_size(ps, 6, 3, WRITE_BDHI);
4575 }
4576 
4577 #ifdef PNG_READ_SUPPORTED
4578 /* Return a row based on image id and 'y' for checking: */
4579 static void
standard_row(png_const_structp pp,png_byte std[STANDARD_ROWMAX],png_uint_32 id,png_uint_32 y)4580 standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
4581    png_uint_32 id, png_uint_32 y)
4582 {
4583    if (WIDTH_FROM_ID(id) == 0)
4584       transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
4585    else
4586       size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
4587          DEPTH_FROM_ID(id)), y);
4588 }
4589 #endif /* PNG_READ_SUPPORTED */
4590 
4591 /* Tests - individual test cases */
4592 /* Like 'make_standard' but errors are deliberately introduced into the calls
4593  * to ensure that they get detected - it should not be possible to write an
4594  * invalid image with libpng!
4595  */
4596 /* TODO: the 'set' functions can probably all be made to take a
4597  * png_const_structp rather than a modifiable one.
4598  */
4599 #ifdef PNG_WARNINGS_SUPPORTED
4600 static void
sBIT0_error_fn(png_structp pp,png_infop pi)4601 sBIT0_error_fn(png_structp pp, png_infop pi)
4602 {
4603    /* 0 is invalid... */
4604    png_color_8 bad;
4605    bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
4606    png_set_sBIT(pp, pi, &bad);
4607 }
4608 
4609 static void
sBIT_error_fn(png_structp pp,png_infop pi)4610 sBIT_error_fn(png_structp pp, png_infop pi)
4611 {
4612    png_byte bit_depth;
4613    png_color_8 bad;
4614 
4615    if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
4616       bit_depth = 8;
4617 
4618    else
4619       bit_depth = png_get_bit_depth(pp, pi);
4620 
4621    /* Now we know the bit depth we can easily generate an invalid sBIT entry */
4622    bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
4623       (png_byte)(bit_depth+1);
4624    png_set_sBIT(pp, pi, &bad);
4625 }
4626 
4627 static const struct
4628 {
4629    void          (*fn)(png_structp, png_infop);
4630    const char *msg;
4631    unsigned int    warning :1; /* the error is a warning... */
4632 } error_test[] =
4633     {
4634        /* no warnings makes these errors undetectable prior to 1.7.0 */
4635        { sBIT0_error_fn, "sBIT(0): failed to detect error",
4636          PNG_LIBPNG_VER < 10700 },
4637 
4638        { sBIT_error_fn, "sBIT(too big): failed to detect error",
4639          PNG_LIBPNG_VER < 10700 },
4640     };
4641 
4642 static void
make_error(png_store * const ps,png_byte const colour_type,png_byte bit_depth,int interlace_type,int test,png_const_charp name)4643 make_error(png_store* const ps, png_byte const colour_type,
4644     png_byte bit_depth, int interlace_type, int test, png_const_charp name)
4645 {
4646    context(ps, fault);
4647 
4648    check_interlace_type(interlace_type);
4649 
4650    Try
4651    {
4652       png_infop pi;
4653       png_structp pp = set_store_for_write(ps, &pi, name);
4654       png_uint_32 w, h;
4655       gnu_volatile(pp)
4656 
4657       if (pp == NULL)
4658          Throw ps;
4659 
4660       w = transform_width(pp, colour_type, bit_depth);
4661       gnu_volatile(w)
4662       h = transform_height(pp, colour_type, bit_depth);
4663       gnu_volatile(h)
4664       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4665             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4666 
4667       if (colour_type == 3) /* palette */
4668          init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4669 
4670       /* Time for a few errors; these are in various optional chunks, the
4671        * standard tests test the standard chunks pretty well.
4672        */
4673 #     define exception__prev exception_prev_1
4674 #     define exception__env exception_env_1
4675       Try
4676       {
4677          gnu_volatile(exception__prev)
4678 
4679          /* Expect this to throw: */
4680          ps->expect_error = !error_test[test].warning;
4681          ps->expect_warning = error_test[test].warning;
4682          ps->saw_warning = 0;
4683          error_test[test].fn(pp, pi);
4684 
4685          /* Normally the error is only detected here: */
4686          png_write_info(pp, pi);
4687 
4688          /* And handle the case where it was only a warning: */
4689          if (ps->expect_warning && ps->saw_warning)
4690             Throw ps;
4691 
4692          /* If we get here there is a problem, we have success - no error or
4693           * no warning - when we shouldn't have success.  Log an error.
4694           */
4695          store_log(ps, pp, error_test[test].msg, 1 /*error*/);
4696       }
4697 
4698       Catch (fault)
4699       { /* expected exit */
4700       }
4701 #undef exception__prev
4702 #undef exception__env
4703 
4704       /* And clear these flags */
4705       ps->expect_warning = 0;
4706 
4707       if (ps->expect_error)
4708          ps->expect_error = 0;
4709 
4710       else
4711       {
4712          /* Now write the whole image, just to make sure that the detected, or
4713           * undetected, error has not created problems inside libpng.  This
4714           * doesn't work if there was a png_error in png_write_info because that
4715           * can abort before PLTE was written.
4716           */
4717          if (png_get_rowbytes(pp, pi) !=
4718              transform_rowsize(pp, colour_type, bit_depth))
4719             png_error(pp, "row size incorrect");
4720 
4721          else
4722          {
4723             int npasses = set_write_interlace_handling(pp, interlace_type);
4724             int pass;
4725 
4726             if (npasses != npasses_from_interlace_type(pp, interlace_type))
4727                png_error(pp, "write: png_set_interlace_handling failed");
4728 
4729             for (pass=0; pass<npasses; ++pass)
4730             {
4731                png_uint_32 y;
4732 
4733                for (y=0; y<h; ++y)
4734                {
4735                   png_byte buffer[TRANSFORM_ROWMAX];
4736 
4737                   transform_row(pp, buffer, colour_type, bit_depth, y);
4738 
4739 #                 if do_own_interlace
4740                      /* If do_own_interlace *and* the image is interlaced we
4741                       * need a reduced interlace row; this may be reduced to
4742                       * empty.
4743                       */
4744                      if (interlace_type == PNG_INTERLACE_ADAM7)
4745                      {
4746                         /* The row must not be written if it doesn't exist,
4747                          * notice that there are two conditions here, either the
4748                          * row isn't ever in the pass or the row would be but
4749                          * isn't wide enough to contribute any pixels.  In fact
4750                          * the wPass test can be used to skip the whole y loop
4751                          * in this case.
4752                          */
4753                         if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4754                             PNG_PASS_COLS(w, pass) > 0)
4755                            interlace_row(buffer, buffer,
4756                                  bit_size(pp, colour_type, bit_depth), w, pass,
4757                                  0/*data always bigendian*/);
4758                         else
4759                            continue;
4760                      }
4761 #                 endif /* do_own_interlace */
4762 
4763                   png_write_row(pp, buffer);
4764                }
4765             }
4766          } /* image writing */
4767 
4768          png_write_end(pp, pi);
4769       }
4770 
4771       /* The following deletes the file that was just written. */
4772       store_write_reset(ps);
4773    }
4774 
4775    Catch(fault)
4776    {
4777       store_write_reset(fault);
4778    }
4779 }
4780 
4781 static int
make_errors(png_modifier * const pm,png_byte const colour_type,int bdlo,int const bdhi)4782 make_errors(png_modifier* const pm, png_byte const colour_type,
4783     int bdlo, int const bdhi)
4784 {
4785    for (; bdlo <= bdhi; ++bdlo)
4786    {
4787       int interlace_type;
4788 
4789       for (interlace_type = PNG_INTERLACE_NONE;
4790            interlace_type < INTERLACE_LAST; ++interlace_type)
4791       {
4792          unsigned int test;
4793          char name[FILE_NAME_SIZE];
4794 
4795          standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
4796             interlace_type, 0, 0, do_own_interlace);
4797 
4798          for (test=0; test<ARRAY_SIZE(error_test); ++test)
4799          {
4800             make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
4801                test, name);
4802 
4803             if (fail(pm))
4804                return 0;
4805          }
4806       }
4807    }
4808 
4809    return 1; /* keep going */
4810 }
4811 #endif /* PNG_WARNINGS_SUPPORTED */
4812 
4813 static void
perform_error_test(png_modifier * pm)4814 perform_error_test(png_modifier *pm)
4815 {
4816 #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
4817    /* Need to do this here because we just write in this test. */
4818    safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
4819 
4820    if (!make_errors(pm, 0, 0, WRITE_BDHI))
4821       return;
4822 
4823    if (!make_errors(pm, 2, 3, WRITE_BDHI))
4824       return;
4825 
4826    if (!make_errors(pm, 3, 0, 3))
4827       return;
4828 
4829    if (!make_errors(pm, 4, 3, WRITE_BDHI))
4830       return;
4831 
4832    if (!make_errors(pm, 6, 3, WRITE_BDHI))
4833       return;
4834 #else
4835    UNUSED(pm)
4836 #endif
4837 }
4838 
4839 /* This is just to validate the internal PNG formatting code - if this fails
4840  * then the warning messages the library outputs will probably be garbage.
4841  */
4842 static void
perform_formatting_test(png_store * ps)4843 perform_formatting_test(png_store *ps)
4844 {
4845 #ifdef PNG_TIME_RFC1123_SUPPORTED
4846    /* The handle into the formatting code is the RFC1123 support; this test does
4847     * nothing if that is compiled out.
4848     */
4849    context(ps, fault);
4850 
4851    Try
4852    {
4853       png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
4854       png_const_charp result;
4855 #     if PNG_LIBPNG_VER >= 10600
4856          char timestring[29];
4857 #     endif
4858       png_structp pp;
4859       png_time pt;
4860 
4861       pp = set_store_for_write(ps, NULL, "libpng formatting test");
4862 
4863       if (pp == NULL)
4864          Throw ps;
4865 
4866 
4867       /* Arbitrary settings: */
4868       pt.year = 2079;
4869       pt.month = 8;
4870       pt.day = 29;
4871       pt.hour = 13;
4872       pt.minute = 53;
4873       pt.second = 60; /* a leap second */
4874 
4875 #     if PNG_LIBPNG_VER < 10600
4876          result = png_convert_to_rfc1123(pp, &pt);
4877 #     else
4878          if (png_convert_to_rfc1123_buffer(timestring, &pt))
4879             result = timestring;
4880 
4881          else
4882             result = NULL;
4883 #     endif
4884 
4885       if (result == NULL)
4886          png_error(pp, "png_convert_to_rfc1123 failed");
4887 
4888       if (strcmp(result, correct) != 0)
4889       {
4890          size_t pos = 0;
4891          char msg[128];
4892 
4893          pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
4894          pos = safecat(msg, sizeof msg, pos, correct);
4895          pos = safecat(msg, sizeof msg, pos, ") returned: '");
4896          pos = safecat(msg, sizeof msg, pos, result);
4897          pos = safecat(msg, sizeof msg, pos, "'");
4898 
4899          png_error(pp, msg);
4900       }
4901 
4902       store_write_reset(ps);
4903    }
4904 
4905    Catch(fault)
4906    {
4907       store_write_reset(fault);
4908    }
4909 #else
4910    UNUSED(ps)
4911 #endif
4912 }
4913 
4914 #ifdef PNG_READ_SUPPORTED
4915 /* Because we want to use the same code in both the progressive reader and the
4916  * sequential reader it is necessary to deal with the fact that the progressive
4917  * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
4918  * must contain all the test parameters and all the local variables directly
4919  * accessible to the sequential reader implementation.
4920  *
4921  * The technique adopted is to reinvent part of what Dijkstra termed a
4922  * 'display'; an array of pointers to the stack frames of enclosing functions so
4923  * that a nested function definition can access the local (C auto) variables of
4924  * the functions that contain its definition.  In fact C provides the first
4925  * pointer (the local variables - the stack frame pointer) and the last (the
4926  * global variables - the BCPL global vector typically implemented as global
4927  * addresses), this code requires one more pointer to make the display - the
4928  * local variables (and function call parameters) of the function that actually
4929  * invokes either the progressive or sequential reader.
4930  *
4931  * Perhaps confusingly this technique is confounded with classes - the
4932  * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
4933  * A gamma_display is a standard_display, taking advantage of the ANSI-C
4934  * requirement that the pointer to the first member of a structure must be the
4935  * same as the pointer to the structure.  This allows us to reuse standard_
4936  * functions in the gamma test code; something that could not be done with
4937  * nested functions!
4938  */
4939 typedef struct standard_display
4940 {
4941    png_store*  ps;             /* Test parameters (passed to the function) */
4942    png_byte    colour_type;
4943    png_byte    bit_depth;
4944    png_byte    red_sBIT;       /* Input data sBIT values. */
4945    png_byte    green_sBIT;
4946    png_byte    blue_sBIT;
4947    png_byte    alpha_sBIT;
4948    png_byte    interlace_type;
4949    png_byte    filler;         /* Output has a filler */
4950    png_uint_32 id;             /* Calculated file ID */
4951    png_uint_32 w;              /* Width of image */
4952    png_uint_32 h;              /* Height of image */
4953    int         npasses;        /* Number of interlaced passes */
4954    png_uint_32 pixel_size;     /* Width of one pixel in bits */
4955    png_uint_32 bit_width;      /* Width of output row in bits */
4956    size_t      cbRow;          /* Bytes in a row of the output image */
4957    int         do_interlace;   /* Do interlacing internally */
4958    int         littleendian;   /* App (row) data is little endian */
4959    int         is_transparent; /* Transparency information was present. */
4960    int         has_tRNS;       /* color type GRAY or RGB with a tRNS chunk. */
4961    int         speed;          /* Doing a speed test */
4962    int         use_update_info;/* Call update_info, not start_image */
4963    struct
4964    {
4965       png_uint_16 red;
4966       png_uint_16 green;
4967       png_uint_16 blue;
4968    }           transparent;    /* The transparent color, if set. */
4969    int         npalette;       /* Number of entries in the palette. */
4970    store_palette
4971                palette;
4972 } standard_display;
4973 
4974 static void
standard_display_init(standard_display * dp,png_store * ps,png_uint_32 id,int do_interlace,int use_update_info)4975 standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
4976    int do_interlace, int use_update_info)
4977 {
4978    memset(dp, 0, sizeof *dp);
4979 
4980    dp->ps = ps;
4981    dp->colour_type = COL_FROM_ID(id);
4982    dp->bit_depth = DEPTH_FROM_ID(id);
4983    if (dp->bit_depth < 1 || dp->bit_depth > 16)
4984       internal_error(ps, "internal: bad bit depth");
4985    if (dp->colour_type == 3)
4986       dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
4987    else
4988       dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
4989          dp->bit_depth;
4990    dp->interlace_type = INTERLACE_FROM_ID(id);
4991    check_interlace_type(dp->interlace_type);
4992    dp->id = id;
4993    /* All the rest are filled in after the read_info: */
4994    dp->w = 0;
4995    dp->h = 0;
4996    dp->npasses = 0;
4997    dp->pixel_size = 0;
4998    dp->bit_width = 0;
4999    dp->cbRow = 0;
5000    dp->do_interlace = do_interlace;
5001    dp->littleendian = 0;
5002    dp->is_transparent = 0;
5003    dp->speed = ps->speed;
5004    dp->use_update_info = use_update_info;
5005    dp->npalette = 0;
5006    /* Preset the transparent color to black: */
5007    memset(&dp->transparent, 0, sizeof dp->transparent);
5008    /* Preset the palette to full intensity/opaque throughout: */
5009    memset(dp->palette, 0xff, sizeof dp->palette);
5010 }
5011 
5012 /* Initialize the palette fields - this must be done later because the palette
5013  * comes from the particular png_store_file that is selected.
5014  */
5015 static void
standard_palette_init(standard_display * dp)5016 standard_palette_init(standard_display *dp)
5017 {
5018    store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
5019 
5020    /* The remaining entries remain white/opaque. */
5021    if (dp->npalette > 0)
5022    {
5023       int i = dp->npalette;
5024       memcpy(dp->palette, palette, i * sizeof *palette);
5025 
5026       /* Check for a non-opaque palette entry: */
5027       while (--i >= 0)
5028          if (palette[i].alpha < 255)
5029             break;
5030 
5031 #     ifdef __GNUC__
5032          /* GCC can't handle the more obviously optimizable version. */
5033          if (i >= 0)
5034             dp->is_transparent = 1;
5035          else
5036             dp->is_transparent = 0;
5037 #     else
5038          dp->is_transparent = (i >= 0);
5039 #     endif
5040    }
5041 }
5042 
5043 /* Utility to read the palette from the PNG file and convert it into
5044  * store_palette format.  This returns 1 if there is any transparency in the
5045  * palette (it does not check for a transparent colour in the non-palette case.)
5046  */
5047 static int
read_palette(store_palette palette,int * npalette,png_const_structp pp,png_infop pi)5048 read_palette(store_palette palette, int *npalette, png_const_structp pp,
5049    png_infop pi)
5050 {
5051    png_colorp pal;
5052    png_bytep trans_alpha;
5053    int num;
5054 
5055    pal = 0;
5056    *npalette = -1;
5057 
5058    if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
5059    {
5060       int i = *npalette;
5061 
5062       if (i <= 0 || i > 256)
5063          png_error(pp, "validate: invalid PLTE count");
5064 
5065       while (--i >= 0)
5066       {
5067          palette[i].red = pal[i].red;
5068          palette[i].green = pal[i].green;
5069          palette[i].blue = pal[i].blue;
5070       }
5071 
5072       /* Mark the remainder of the entries with a flag value (other than
5073        * white/opaque which is the flag value stored above.)
5074        */
5075       memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
5076    }
5077 
5078    else /* !png_get_PLTE */
5079    {
5080       if (*npalette != (-1))
5081          png_error(pp, "validate: invalid PLTE result");
5082       /* But there is no palette, so record this: */
5083       *npalette = 0;
5084       memset(palette, 113, sizeof (store_palette));
5085    }
5086 
5087    trans_alpha = 0;
5088    num = 2; /* force error below */
5089    if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
5090       (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
5091       /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
5092        * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
5093        * so in the above call we get a success, we get a pointer (who knows what
5094        * to) and we get num_trans == 0:
5095        */
5096       !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
5097    {
5098       int i;
5099 
5100       /* Any of these are crash-worthy - given the implementation of
5101        * png_get_tRNS up to 1.5 an app won't crash if it just checks the
5102        * result above and fails to check that the variables it passed have
5103        * actually been filled in!  Note that if the app were to pass the
5104        * last, png_color_16p, variable too it couldn't rely on this.
5105        */
5106       if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
5107          png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
5108 
5109       for (i=0; i<num; ++i)
5110          palette[i].alpha = trans_alpha[i];
5111 
5112       for (num=*npalette; i<num; ++i)
5113          palette[i].alpha = 255;
5114 
5115       for (; i<256; ++i)
5116          palette[i].alpha = 33; /* flag value */
5117 
5118       return 1; /* transparency */
5119    }
5120 
5121    else
5122    {
5123       /* No palette transparency - just set the alpha channel to opaque. */
5124       int i;
5125 
5126       for (i=0, num=*npalette; i<num; ++i)
5127          palette[i].alpha = 255;
5128 
5129       for (; i<256; ++i)
5130          palette[i].alpha = 55; /* flag value */
5131 
5132       return 0; /* no transparency */
5133    }
5134 }
5135 
5136 /* Utility to validate the palette if it should not have changed (the
5137  * non-transform case).
5138  */
5139 static void
standard_palette_validate(standard_display * dp,png_const_structp pp,png_infop pi)5140 standard_palette_validate(standard_display *dp, png_const_structp pp,
5141    png_infop pi)
5142 {
5143    int npalette;
5144    store_palette palette;
5145 
5146    if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
5147       png_error(pp, "validate: palette transparency changed");
5148 
5149    if (npalette != dp->npalette)
5150    {
5151       size_t pos = 0;
5152       char msg[64];
5153 
5154       pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
5155       pos = safecatn(msg, sizeof msg, pos, dp->npalette);
5156       pos = safecat(msg, sizeof msg, pos, " -> ");
5157       pos = safecatn(msg, sizeof msg, pos, npalette);
5158       png_error(pp, msg);
5159    }
5160 
5161    {
5162       int i = npalette; /* npalette is aliased */
5163 
5164       while (--i >= 0)
5165          if (palette[i].red != dp->palette[i].red ||
5166             palette[i].green != dp->palette[i].green ||
5167             palette[i].blue != dp->palette[i].blue ||
5168             palette[i].alpha != dp->palette[i].alpha)
5169             png_error(pp, "validate: PLTE or tRNS chunk changed");
5170    }
5171 }
5172 
5173 /* By passing a 'standard_display' the progressive callbacks can be used
5174  * directly by the sequential code, the functions suffixed "_imp" are the
5175  * implementations, the functions without the suffix are the callbacks.
5176  *
5177  * The code for the info callback is split into two because this callback calls
5178  * png_read_update_info or png_start_read_image and what gets called depends on
5179  * whether the info needs updating (we want to test both calls in pngvalid.)
5180  */
5181 static void
standard_info_part1(standard_display * dp,png_structp pp,png_infop pi)5182 standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
5183 {
5184    if (png_get_bit_depth(pp, pi) != dp->bit_depth)
5185       png_error(pp, "validate: bit depth changed");
5186 
5187    if (png_get_color_type(pp, pi) != dp->colour_type)
5188       png_error(pp, "validate: color type changed");
5189 
5190    if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
5191       png_error(pp, "validate: filter type changed");
5192 
5193    if (png_get_interlace_type(pp, pi) != dp->interlace_type)
5194       png_error(pp, "validate: interlacing changed");
5195 
5196    if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
5197       png_error(pp, "validate: compression type changed");
5198 
5199    dp->w = png_get_image_width(pp, pi);
5200 
5201    if (dp->w != standard_width(pp, dp->id))
5202       png_error(pp, "validate: image width changed");
5203 
5204    dp->h = png_get_image_height(pp, pi);
5205 
5206    if (dp->h != standard_height(pp, dp->id))
5207       png_error(pp, "validate: image height changed");
5208 
5209    /* Record (but don't check at present) the input sBIT according to the colour
5210     * type information.
5211     */
5212    {
5213       png_color_8p sBIT = 0;
5214 
5215       if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
5216       {
5217          int sBIT_invalid = 0;
5218 
5219          if (sBIT == 0)
5220             png_error(pp, "validate: unexpected png_get_sBIT result");
5221 
5222          if (dp->colour_type & PNG_COLOR_MASK_COLOR)
5223          {
5224             if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
5225                sBIT_invalid = 1;
5226             else
5227                dp->red_sBIT = sBIT->red;
5228 
5229             if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
5230                sBIT_invalid = 1;
5231             else
5232                dp->green_sBIT = sBIT->green;
5233 
5234             if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
5235                sBIT_invalid = 1;
5236             else
5237                dp->blue_sBIT = sBIT->blue;
5238          }
5239 
5240          else /* !COLOR */
5241          {
5242             if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
5243                sBIT_invalid = 1;
5244             else
5245                dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
5246          }
5247 
5248          /* All 8 bits in tRNS for a palette image are significant - see the
5249           * spec.
5250           */
5251          if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
5252          {
5253             if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
5254                sBIT_invalid = 1;
5255             else
5256                dp->alpha_sBIT = sBIT->alpha;
5257          }
5258 
5259          if (sBIT_invalid)
5260             png_error(pp, "validate: sBIT value out of range");
5261       }
5262    }
5263 
5264    /* Important: this is validating the value *before* any transforms have been
5265     * put in place.  It doesn't matter for the standard tests, where there are
5266     * no transforms, but it does for other tests where rowbytes may change after
5267     * png_read_update_info.
5268     */
5269    if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
5270       png_error(pp, "validate: row size changed");
5271 
5272    /* Validate the colour type 3 palette (this can be present on other color
5273     * types.)
5274     */
5275    standard_palette_validate(dp, pp, pi);
5276 
5277    /* In any case always check for a transparent color (notice that the
5278     * colour type 3 case must not give a successful return on the get_tRNS call
5279     * with these arguments!)
5280     */
5281    {
5282       png_color_16p trans_color = 0;
5283 
5284       if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
5285       {
5286          if (trans_color == 0)
5287             png_error(pp, "validate: unexpected png_get_tRNS (color) result");
5288 
5289          switch (dp->colour_type)
5290          {
5291          case 0:
5292             dp->transparent.red = dp->transparent.green = dp->transparent.blue =
5293                trans_color->gray;
5294             dp->has_tRNS = 1;
5295             break;
5296 
5297          case 2:
5298             dp->transparent.red = trans_color->red;
5299             dp->transparent.green = trans_color->green;
5300             dp->transparent.blue = trans_color->blue;
5301             dp->has_tRNS = 1;
5302             break;
5303 
5304          case 3:
5305             /* Not expected because it should result in the array case
5306              * above.
5307              */
5308             png_error(pp, "validate: unexpected png_get_tRNS result");
5309             break;
5310 
5311          default:
5312             png_error(pp, "validate: invalid tRNS chunk with alpha image");
5313          }
5314       }
5315    }
5316 
5317    /* Read the number of passes - expected to match the value used when
5318     * creating the image (interlaced or not).  This has the side effect of
5319     * turning on interlace handling (if do_interlace is not set.)
5320     */
5321    dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
5322    if (!dp->do_interlace)
5323    {
5324 #     ifdef PNG_READ_INTERLACING_SUPPORTED
5325          if (dp->npasses != png_set_interlace_handling(pp))
5326             png_error(pp, "validate: file changed interlace type");
5327 #     else /* !READ_INTERLACING */
5328          /* This should never happen: the relevant tests (!do_interlace) should
5329           * not be run.
5330           */
5331          if (dp->npasses > 1)
5332             png_error(pp, "validate: no libpng interlace support");
5333 #     endif /* !READ_INTERLACING */
5334    }
5335 
5336    /* Caller calls png_read_update_info or png_start_read_image now, then calls
5337     * part2.
5338     */
5339 }
5340 
5341 /* This must be called *after* the png_read_update_info call to get the correct
5342  * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
5343  * image.
5344  */
5345 static void
standard_info_part2(standard_display * dp,png_const_structp pp,png_const_infop pi,int nImages)5346 standard_info_part2(standard_display *dp, png_const_structp pp,
5347     png_const_infop pi, int nImages)
5348 {
5349    /* Record cbRow now that it can be found. */
5350    {
5351       png_byte ct = png_get_color_type(pp, pi);
5352       png_byte bd = png_get_bit_depth(pp, pi);
5353 
5354       if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
5355           dp->filler)
5356           ct |= 4; /* handle filler as faked alpha channel */
5357 
5358       dp->pixel_size = bit_size(pp, ct, bd);
5359    }
5360    dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
5361    dp->cbRow = png_get_rowbytes(pp, pi);
5362 
5363    /* Validate the rowbytes here again. */
5364    if (dp->cbRow != (dp->bit_width+7)/8)
5365       png_error(pp, "bad png_get_rowbytes calculation");
5366 
5367    /* Then ensure there is enough space for the output image(s). */
5368    store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
5369 }
5370 
5371 static void
standard_info_imp(standard_display * dp,png_structp pp,png_infop pi,int nImages)5372 standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
5373     int nImages)
5374 {
5375    /* Note that the validation routine has the side effect of turning on
5376     * interlace handling in the subsequent code.
5377     */
5378    standard_info_part1(dp, pp, pi);
5379 
5380    /* And the info callback has to call this (or png_read_update_info - see
5381     * below in the png_modifier code for that variant.
5382     */
5383    if (dp->use_update_info)
5384    {
5385       /* For debugging the effect of multiple calls: */
5386       int i = dp->use_update_info;
5387       while (i-- > 0)
5388          png_read_update_info(pp, pi);
5389    }
5390 
5391    else
5392       png_start_read_image(pp);
5393 
5394    /* Validate the height, width and rowbytes plus ensure that sufficient buffer
5395     * exists for decoding the image.
5396     */
5397    standard_info_part2(dp, pp, pi, nImages);
5398 }
5399 
5400 static void PNGCBAPI
standard_info(png_structp pp,png_infop pi)5401 standard_info(png_structp pp, png_infop pi)
5402 {
5403    standard_display *dp = voidcast(standard_display*,
5404       png_get_progressive_ptr(pp));
5405 
5406    /* Call with nImages==1 because the progressive reader can only produce one
5407     * image.
5408     */
5409    standard_info_imp(dp, pp, pi, 1 /*only one image*/);
5410 }
5411 
5412 static void PNGCBAPI
progressive_row(png_structp ppIn,png_bytep new_row,png_uint_32 y,int pass)5413 progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
5414 {
5415    png_const_structp pp = ppIn;
5416    const standard_display *dp = voidcast(standard_display*,
5417       png_get_progressive_ptr(pp));
5418 
5419    /* When handling interlacing some rows will be absent in each pass, the
5420     * callback still gets called, but with a NULL pointer.  This is checked
5421     * in the 'else' clause below.  We need our own 'cbRow', but we can't call
5422     * png_get_rowbytes because we got no info structure.
5423     */
5424    if (new_row != NULL)
5425    {
5426       png_bytep row;
5427 
5428       /* In the case where the reader doesn't do the interlace it gives
5429        * us the y in the sub-image:
5430        */
5431       if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
5432       {
5433 #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
5434          /* Use this opportunity to validate the png 'current' APIs: */
5435          if (y != png_get_current_row_number(pp))
5436             png_error(pp, "png_get_current_row_number is broken");
5437 
5438          if (pass != png_get_current_pass_number(pp))
5439             png_error(pp, "png_get_current_pass_number is broken");
5440 #endif /* USER_TRANSFORM_INFO */
5441 
5442          y = PNG_ROW_FROM_PASS_ROW(y, pass);
5443       }
5444 
5445       /* Validate this just in case. */
5446       if (y >= dp->h)
5447          png_error(pp, "invalid y to progressive row callback");
5448 
5449       row = store_image_row(dp->ps, pp, 0, y);
5450 
5451       /* Combine the new row into the old: */
5452 #ifdef PNG_READ_INTERLACING_SUPPORTED
5453       if (dp->do_interlace)
5454 #endif /* READ_INTERLACING */
5455       {
5456          if (dp->interlace_type == PNG_INTERLACE_ADAM7)
5457             deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
5458                   dp->littleendian);
5459          else
5460             row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
5461       }
5462 #ifdef PNG_READ_INTERLACING_SUPPORTED
5463       else
5464          png_progressive_combine_row(pp, row, new_row);
5465 #endif /* PNG_READ_INTERLACING_SUPPORTED */
5466    }
5467 
5468    else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
5469        PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
5470        PNG_PASS_COLS(dp->w, pass) > 0)
5471       png_error(pp, "missing row in progressive de-interlacing");
5472 }
5473 
5474 static void
sequential_row(standard_display * dp,png_structp pp,png_infop pi,int iImage,int iDisplay)5475 sequential_row(standard_display *dp, png_structp pp, png_infop pi,
5476     int iImage, int iDisplay)
5477 {
5478    int npasses = dp->npasses;
5479    int do_interlace = dp->do_interlace &&
5480       dp->interlace_type == PNG_INTERLACE_ADAM7;
5481    png_uint_32 height = standard_height(pp, dp->id);
5482    png_uint_32 width = standard_width(pp, dp->id);
5483    const png_store* ps = dp->ps;
5484    int pass;
5485 
5486    for (pass=0; pass<npasses; ++pass)
5487    {
5488       png_uint_32 y;
5489       png_uint_32 wPass = PNG_PASS_COLS(width, pass);
5490 
5491       for (y=0; y<height; ++y)
5492       {
5493          if (do_interlace)
5494          {
5495             /* wPass may be zero or this row may not be in this pass.
5496              * png_read_row must not be called in either case.
5497              */
5498             if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
5499             {
5500                /* Read the row into a pair of temporary buffers, then do the
5501                 * merge here into the output rows.
5502                 */
5503                png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
5504 
5505                /* The following aids (to some extent) error detection - we can
5506                 * see where png_read_row wrote.  Use opposite values in row and
5507                 * display to make this easier.  Don't use 0xff (which is used in
5508                 * the image write code to fill unused bits) or 0 (which is a
5509                 * likely value to overwrite unused bits with).
5510                 */
5511                memset(row, 0xc5, sizeof row);
5512                memset(display, 0x5c, sizeof display);
5513 
5514                png_read_row(pp, row, display);
5515 
5516                if (iImage >= 0)
5517                   deinterlace_row(store_image_row(ps, pp, iImage, y), row,
5518                      dp->pixel_size, dp->w, pass, dp->littleendian);
5519 
5520                if (iDisplay >= 0)
5521                   deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
5522                      dp->pixel_size, dp->w, pass, dp->littleendian);
5523             }
5524          }
5525          else
5526             png_read_row(pp,
5527                iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
5528                iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
5529       }
5530    }
5531 
5532    /* And finish the read operation (only really necessary if the caller wants
5533     * to find additional data in png_info from chunks after the last IDAT.)
5534     */
5535    png_read_end(pp, pi);
5536 }
5537 
5538 #ifdef PNG_TEXT_SUPPORTED
5539 static void
standard_check_text(png_const_structp pp,png_const_textp tp,png_const_charp keyword,png_const_charp text)5540 standard_check_text(png_const_structp pp, png_const_textp tp,
5541    png_const_charp keyword, png_const_charp text)
5542 {
5543    char msg[1024];
5544    size_t pos = safecat(msg, sizeof msg, 0, "text: ");
5545    size_t ok;
5546 
5547    pos = safecat(msg, sizeof msg, pos, keyword);
5548    pos = safecat(msg, sizeof msg, pos, ": ");
5549    ok = pos;
5550 
5551    if (tp->compression != TEXT_COMPRESSION)
5552    {
5553       char buf[64];
5554 
5555       sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
5556          tp->compression);
5557       pos = safecat(msg, sizeof msg, pos, buf);
5558    }
5559 
5560    if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
5561    {
5562       pos = safecat(msg, sizeof msg, pos, "keyword \"");
5563       if (tp->key != NULL)
5564       {
5565          pos = safecat(msg, sizeof msg, pos, tp->key);
5566          pos = safecat(msg, sizeof msg, pos, "\", ");
5567       }
5568 
5569       else
5570          pos = safecat(msg, sizeof msg, pos, "null, ");
5571    }
5572 
5573    if (tp->text == NULL)
5574       pos = safecat(msg, sizeof msg, pos, "text lost, ");
5575 
5576    else
5577    {
5578       if (tp->text_length != strlen(text))
5579       {
5580          char buf[64];
5581          sprintf(buf, "text length changed[%lu->%lu], ",
5582             (unsigned long)strlen(text), (unsigned long)tp->text_length);
5583          pos = safecat(msg, sizeof msg, pos, buf);
5584       }
5585 
5586       if (strcmp(tp->text, text) != 0)
5587       {
5588          pos = safecat(msg, sizeof msg, pos, "text becomes \"");
5589          pos = safecat(msg, sizeof msg, pos, tp->text);
5590          pos = safecat(msg, sizeof msg, pos, "\" (was \"");
5591          pos = safecat(msg, sizeof msg, pos, text);
5592          pos = safecat(msg, sizeof msg, pos, "\"), ");
5593       }
5594    }
5595 
5596    if (tp->itxt_length != 0)
5597       pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
5598 
5599    if (tp->lang != NULL)
5600    {
5601       pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
5602       pos = safecat(msg, sizeof msg, pos, tp->lang);
5603       pos = safecat(msg, sizeof msg, pos, "\", ");
5604    }
5605 
5606    if (tp->lang_key != NULL)
5607    {
5608       pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
5609       pos = safecat(msg, sizeof msg, pos, tp->lang_key);
5610       pos = safecat(msg, sizeof msg, pos, "\", ");
5611    }
5612 
5613    if (pos > ok)
5614    {
5615       msg[pos-2] = '\0'; /* Remove the ", " at the end */
5616       png_error(pp, msg);
5617    }
5618 }
5619 
5620 static void
standard_text_validate(standard_display * dp,png_const_structp pp,png_infop pi,int check_end)5621 standard_text_validate(standard_display *dp, png_const_structp pp,
5622    png_infop pi, int check_end)
5623 {
5624    png_textp tp = NULL;
5625    png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
5626 
5627    if (num_text == 2 && tp != NULL)
5628    {
5629       standard_check_text(pp, tp, "image name", dp->ps->current->name);
5630 
5631       /* This exists because prior to 1.5.18 the progressive reader left the
5632        * png_struct z_stream unreset at the end of the image, so subsequent
5633        * attempts to use it simply returns Z_STREAM_END.
5634        */
5635       if (check_end)
5636          standard_check_text(pp, tp+1, "end marker", "end");
5637    }
5638 
5639    else
5640    {
5641       char msg[64];
5642 
5643       sprintf(msg, "expected two text items, got %lu",
5644          (unsigned long)num_text);
5645       png_error(pp, msg);
5646    }
5647 }
5648 #else
5649 #  define standard_text_validate(dp,pp,pi,check_end) ((void)0)
5650 #endif
5651 
5652 static void
standard_row_validate(standard_display * dp,png_const_structp pp,int iImage,int iDisplay,png_uint_32 y)5653 standard_row_validate(standard_display *dp, png_const_structp pp,
5654    int iImage, int iDisplay, png_uint_32 y)
5655 {
5656    int where;
5657    png_byte std[STANDARD_ROWMAX];
5658 
5659    /* The row must be pre-initialized to the magic number here for the size
5660     * tests to pass:
5661     */
5662    memset(std, 178, sizeof std);
5663    standard_row(pp, std, dp->id, y);
5664 
5665    /* At the end both the 'row' and 'display' arrays should end up identical.
5666     * In earlier passes 'row' will be partially filled in, with only the pixels
5667     * that have been read so far, but 'display' will have those pixels
5668     * replicated to fill the unread pixels while reading an interlaced image.
5669     */
5670    if (iImage >= 0 &&
5671       (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
5672             dp->bit_width)) != 0)
5673    {
5674       char msg[64];
5675       sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
5676          (unsigned long)y, where-1, std[where-1],
5677          store_image_row(dp->ps, pp, iImage, y)[where-1]);
5678       png_error(pp, msg);
5679    }
5680 
5681    if (iDisplay >= 0 &&
5682       (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
5683          dp->bit_width)) != 0)
5684    {
5685       char msg[64];
5686       sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
5687          (unsigned long)y, where-1, std[where-1],
5688          store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
5689       png_error(pp, msg);
5690    }
5691 }
5692 
5693 static void
standard_image_validate(standard_display * dp,png_const_structp pp,int iImage,int iDisplay)5694 standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
5695     int iDisplay)
5696 {
5697    png_uint_32 y;
5698 
5699    if (iImage >= 0)
5700       store_image_check(dp->ps, pp, iImage);
5701 
5702    if (iDisplay >= 0)
5703       store_image_check(dp->ps, pp, iDisplay);
5704 
5705    for (y=0; y<dp->h; ++y)
5706       standard_row_validate(dp, pp, iImage, iDisplay, y);
5707 
5708    /* This avoids false positives if the validation code is never called! */
5709    dp->ps->validated = 1;
5710 }
5711 
5712 static void PNGCBAPI
standard_end(png_structp ppIn,png_infop pi)5713 standard_end(png_structp ppIn, png_infop pi)
5714 {
5715    png_const_structp pp = ppIn;
5716    standard_display *dp = voidcast(standard_display*,
5717       png_get_progressive_ptr(pp));
5718 
5719    UNUSED(pi)
5720 
5721    /* Validate the image - progressive reading only produces one variant for
5722     * interlaced images.
5723     */
5724    standard_text_validate(dp, pp, pi,
5725       PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
5726    standard_image_validate(dp, pp, 0, -1);
5727 }
5728 
5729 /* A single test run checking the standard image to ensure it is not damaged. */
5730 static void
standard_test(png_store * const psIn,png_uint_32 const id,int do_interlace,int use_update_info)5731 standard_test(png_store* const psIn, png_uint_32 const id,
5732    int do_interlace, int use_update_info)
5733 {
5734    standard_display d;
5735    context(psIn, fault);
5736 
5737    /* Set up the display (stack frame) variables from the arguments to the
5738     * function and initialize the locals that are filled in later.
5739     */
5740    standard_display_init(&d, psIn, id, do_interlace, use_update_info);
5741 
5742    /* Everything is protected by a Try/Catch.  The functions called also
5743     * typically have local Try/Catch blocks.
5744     */
5745    Try
5746    {
5747       png_structp pp;
5748       png_infop pi;
5749 
5750       /* Get a png_struct for reading the image. This will throw an error if it
5751        * fails, so we don't need to check the result.
5752        */
5753       pp = set_store_for_read(d.ps, &pi, d.id,
5754          d.do_interlace ?  (d.ps->progressive ?
5755             "pngvalid progressive deinterlacer" :
5756             "pngvalid sequential deinterlacer") : (d.ps->progressive ?
5757                "progressive reader" : "sequential reader"));
5758 
5759       /* Initialize the palette correctly from the png_store_file. */
5760       standard_palette_init(&d);
5761 
5762       /* Introduce the correct read function. */
5763       if (d.ps->progressive)
5764       {
5765          png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
5766             standard_end);
5767 
5768          /* Now feed data into the reader until we reach the end: */
5769          store_progressive_read(d.ps, pp, pi);
5770       }
5771       else
5772       {
5773          /* Note that this takes the store, not the display. */
5774          png_set_read_fn(pp, d.ps, store_read);
5775 
5776          /* Check the header values: */
5777          png_read_info(pp, pi);
5778 
5779          /* The code tests both versions of the images that the sequential
5780           * reader can produce.
5781           */
5782          standard_info_imp(&d, pp, pi, 2 /*images*/);
5783 
5784          /* Need the total bytes in the image below; we can't get to this point
5785           * unless the PNG file values have been checked against the expected
5786           * values.
5787           */
5788          {
5789             sequential_row(&d, pp, pi, 0, 1);
5790 
5791             /* After the last pass loop over the rows again to check that the
5792              * image is correct.
5793              */
5794             if (!d.speed)
5795             {
5796                standard_text_validate(&d, pp, pi, 1/*check_end*/);
5797                standard_image_validate(&d, pp, 0, 1);
5798             }
5799             else
5800                d.ps->validated = 1;
5801          }
5802       }
5803 
5804       /* Check for validation. */
5805       if (!d.ps->validated)
5806          png_error(pp, "image read failed silently");
5807 
5808       /* Successful completion. */
5809    }
5810 
5811    Catch(fault)
5812       d.ps = fault; /* make sure this hasn't been clobbered. */
5813 
5814    /* In either case clean up the store. */
5815    store_read_reset(d.ps);
5816 }
5817 
5818 static int
test_standard(png_modifier * const pm,png_byte const colour_type,int bdlo,int const bdhi)5819 test_standard(png_modifier* const pm, png_byte const colour_type,
5820     int bdlo, int const bdhi)
5821 {
5822    for (; bdlo <= bdhi; ++bdlo)
5823    {
5824       int interlace_type;
5825 
5826       for (interlace_type = PNG_INTERLACE_NONE;
5827            interlace_type < INTERLACE_LAST; ++interlace_type)
5828       {
5829          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5830             0/*palette*/, interlace_type, 0, 0, 0), do_read_interlace,
5831             pm->use_update_info);
5832 
5833          if (fail(pm))
5834             return 0;
5835       }
5836    }
5837 
5838    return 1; /* keep going */
5839 }
5840 
5841 static void
perform_standard_test(png_modifier * pm)5842 perform_standard_test(png_modifier *pm)
5843 {
5844    /* Test each colour type over the valid range of bit depths (expressed as
5845     * log2(bit_depth) in turn, stop as soon as any error is detected.
5846     */
5847    if (!test_standard(pm, 0, 0, READ_BDHI))
5848       return;
5849 
5850    if (!test_standard(pm, 2, 3, READ_BDHI))
5851       return;
5852 
5853    if (!test_standard(pm, 3, 0, 3))
5854       return;
5855 
5856    if (!test_standard(pm, 4, 3, READ_BDHI))
5857       return;
5858 
5859    if (!test_standard(pm, 6, 3, READ_BDHI))
5860       return;
5861 }
5862 
5863 
5864 /********************************** SIZE TESTS ********************************/
5865 static int
test_size(png_modifier * const pm,png_byte const colour_type,int bdlo,int const bdhi)5866 test_size(png_modifier* const pm, png_byte const colour_type,
5867     int bdlo, int const bdhi)
5868 {
5869    /* Run the tests on each combination.
5870     *
5871     * NOTE: on my 32 bit x86 each of the following blocks takes
5872     * a total of 3.5 seconds if done across every combo of bit depth
5873     * width and height.  This is a waste of time in practice, hence the
5874     * hinc and winc stuff:
5875     */
5876    static const png_byte hinc[] = {1, 3, 11, 1, 5};
5877    static const png_byte winc[] = {1, 9, 5, 7, 1};
5878    int save_bdlo = bdlo;
5879 
5880    for (; bdlo <= bdhi; ++bdlo)
5881    {
5882       png_uint_32 h, w;
5883 
5884       for (h=1; h<=16; h+=hinc[bdlo])
5885       {
5886          for (w=1; w<=16; w+=winc[bdlo])
5887          {
5888             /* First test all the 'size' images against the sequential
5889             * reader using libpng to deinterlace (where required.)  This
5890             * validates the write side of libpng.  There are four possibilities
5891             * to validate.
5892             */
5893             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5894                0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
5895                pm->use_update_info);
5896 
5897             if (fail(pm))
5898                return 0;
5899 
5900             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5901                0/*palette*/, PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
5902                pm->use_update_info);
5903 
5904             if (fail(pm))
5905                return 0;
5906 
5907             /* Now validate the interlaced read side - do_interlace true,
5908             * in the progressive case this does actually make a difference
5909             * to the code used in the non-interlaced case too.
5910             */
5911             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5912                0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
5913                pm->use_update_info);
5914 
5915             if (fail(pm))
5916                return 0;
5917 
5918 #        if CAN_WRITE_INTERLACE
5919             /* Validate the pngvalid code itself: */
5920             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5921                0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
5922                pm->use_update_info);
5923 
5924             if (fail(pm))
5925                return 0;
5926 #        endif
5927          }
5928       }
5929    }
5930 
5931    /* Now do the tests of libpng interlace handling, after we have made sure
5932     * that the pngvalid version works:
5933     */
5934    for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
5935    {
5936       png_uint_32 h, w;
5937 
5938       for (h=1; h<=16; h+=hinc[bdlo])
5939       {
5940          for (w=1; w<=16; w+=winc[bdlo])
5941          {
5942 #        ifdef PNG_READ_INTERLACING_SUPPORTED
5943             /* Test with pngvalid generated interlaced images first; we have
5944             * already verify these are ok (unless pngvalid has self-consistent
5945             * read/write errors, which is unlikely), so this detects errors in
5946             * the read side first:
5947             */
5948 #        if CAN_WRITE_INTERLACE
5949             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5950                0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
5951                pm->use_update_info);
5952 
5953             if (fail(pm))
5954                return 0;
5955 #        endif
5956 #        endif /* READ_INTERLACING */
5957 
5958 #        ifdef PNG_WRITE_INTERLACING_SUPPORTED
5959             /* Test the libpng write side against the pngvalid read side: */
5960             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5961                0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
5962                pm->use_update_info);
5963 
5964             if (fail(pm))
5965                return 0;
5966 #        endif
5967 
5968 #        ifdef PNG_READ_INTERLACING_SUPPORTED
5969 #        ifdef PNG_WRITE_INTERLACING_SUPPORTED
5970             /* Test both together: */
5971             standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
5972                0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
5973                pm->use_update_info);
5974 
5975             if (fail(pm))
5976                return 0;
5977 #        endif
5978 #        endif /* READ_INTERLACING */
5979          }
5980       }
5981    }
5982 
5983    return 1; /* keep going */
5984 }
5985 
5986 static void
perform_size_test(png_modifier * pm)5987 perform_size_test(png_modifier *pm)
5988 {
5989    /* Test each colour type over the valid range of bit depths (expressed as
5990     * log2(bit_depth) in turn, stop as soon as any error is detected.
5991     */
5992    if (!test_size(pm, 0, 0, READ_BDHI))
5993       return;
5994 
5995    if (!test_size(pm, 2, 3, READ_BDHI))
5996       return;
5997 
5998    /* For the moment don't do the palette test - it's a waste of time when
5999     * compared to the grayscale test.
6000     */
6001 #if 0
6002    if (!test_size(pm, 3, 0, 3))
6003       return;
6004 #endif
6005 
6006    if (!test_size(pm, 4, 3, READ_BDHI))
6007       return;
6008 
6009    if (!test_size(pm, 6, 3, READ_BDHI))
6010       return;
6011 }
6012 
6013 
6014 /******************************* TRANSFORM TESTS ******************************/
6015 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
6016 /* A set of tests to validate libpng image transforms.  The possibilities here
6017  * are legion because the transforms can be combined in a combinatorial
6018  * fashion.  To deal with this some measure of restraint is required, otherwise
6019  * the tests would take forever.
6020  */
6021 typedef struct image_pixel
6022 {
6023    /* A local (pngvalid) representation of a PNG pixel, in all its
6024     * various forms.
6025     */
6026    unsigned int red, green, blue, alpha; /* For non-palette images. */
6027    unsigned int palette_index;           /* For a palette image. */
6028    png_byte     colour_type;             /* As in the spec. */
6029    png_byte     bit_depth;               /* Defines bit size in row */
6030    png_byte     sample_depth;            /* Scale of samples */
6031    unsigned int have_tRNS :1;            /* tRNS chunk may need processing */
6032    unsigned int swap_rgb :1;             /* RGB swapped to BGR */
6033    unsigned int alpha_first :1;          /* Alpha at start, not end */
6034    unsigned int alpha_inverted :1;       /* Alpha channel inverted */
6035    unsigned int mono_inverted :1;        /* Gray channel inverted */
6036    unsigned int swap16 :1;               /* Byte swap 16-bit components */
6037    unsigned int littleendian :1;         /* High bits on right */
6038    unsigned int sig_bits :1;             /* Pixel shifted (sig bits only) */
6039 
6040    /* For checking the code calculates double precision floating point values
6041     * along with an error value, accumulated from the transforms.  Because an
6042     * sBIT setting allows larger error bounds (indeed, by the spec, apparently
6043     * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
6044     * channel is stored.  This sBIT value is folded in to the stored error value
6045     * at the end of the application of the transforms to the pixel.
6046     *
6047     * If sig_bits is set above the red, green, blue and alpha values have been
6048     * scaled so they only contain the significant bits of the component values.
6049     */
6050    double   redf, greenf, bluef, alphaf;
6051    double   rede, greene, bluee, alphae;
6052    png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
6053 } image_pixel;
6054 
6055 /* Shared utility function, see below. */
6056 static void
image_pixel_setf(image_pixel * this,unsigned int rMax,unsigned int gMax,unsigned int bMax,unsigned int aMax)6057 image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
6058         unsigned int bMax, unsigned int aMax)
6059 {
6060    this->redf = this->red / (double)rMax;
6061    this->greenf = this->green / (double)gMax;
6062    this->bluef = this->blue / (double)bMax;
6063    this->alphaf = this->alpha / (double)aMax;
6064 
6065    if (this->red < rMax)
6066       this->rede = this->redf * DBL_EPSILON;
6067    else
6068       this->rede = 0;
6069    if (this->green < gMax)
6070       this->greene = this->greenf * DBL_EPSILON;
6071    else
6072       this->greene = 0;
6073    if (this->blue < bMax)
6074       this->bluee = this->bluef * DBL_EPSILON;
6075    else
6076       this->bluee = 0;
6077    if (this->alpha < aMax)
6078       this->alphae = this->alphaf * DBL_EPSILON;
6079    else
6080       this->alphae = 0;
6081 }
6082 
6083 /* Initialize the structure for the next pixel - call this before doing any
6084  * transforms and call it for each pixel since all the fields may need to be
6085  * reset.
6086  */
6087 static void
image_pixel_init(image_pixel * this,png_const_bytep row,png_byte colour_type,png_byte bit_depth,png_uint_32 x,store_palette palette,const image_pixel * format)6088 image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
6089     png_byte bit_depth, png_uint_32 x, store_palette palette,
6090     const image_pixel *format /*from pngvalid transform of input*/)
6091 {
6092    png_byte sample_depth =
6093       (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
6094    unsigned int max = (1U<<sample_depth)-1;
6095    int swap16 = (format != 0 && format->swap16);
6096    int littleendian = (format != 0 && format->littleendian);
6097    int sig_bits = (format != 0 && format->sig_bits);
6098 
6099    /* Initially just set everything to the same number and the alpha to opaque.
6100     * Note that this currently assumes a simple palette where entry x has colour
6101     * rgb(x,x,x)!
6102     */
6103    this->palette_index = this->red = this->green = this->blue =
6104       sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
6105    this->alpha = max;
6106    this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
6107       sample_depth;
6108 
6109    /* Then override as appropriate: */
6110    if (colour_type == 3) /* palette */
6111    {
6112       /* This permits the caller to default to the sample value. */
6113       if (palette != 0)
6114       {
6115          unsigned int i = this->palette_index;
6116 
6117          this->red = palette[i].red;
6118          this->green = palette[i].green;
6119          this->blue = palette[i].blue;
6120          this->alpha = palette[i].alpha;
6121       }
6122    }
6123 
6124    else /* not palette */
6125    {
6126       unsigned int i = 0;
6127 
6128       if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
6129       {
6130          this->alpha = this->red;
6131          /* This handles the gray case for 'AG' pixels */
6132          this->palette_index = this->red = this->green = this->blue =
6133             sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
6134          i = 1;
6135       }
6136 
6137       if (colour_type & 2)
6138       {
6139          /* Green is second for both BGR and RGB: */
6140          this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
6141                  littleendian);
6142 
6143          if (format != 0 && format->swap_rgb) /* BGR */
6144              this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
6145                      littleendian);
6146          else
6147              this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
6148                      littleendian);
6149       }
6150 
6151       else /* grayscale */ if (format != 0 && format->mono_inverted)
6152          this->red = this->green = this->blue = this->red ^ max;
6153 
6154       if ((colour_type & 4) != 0) /* alpha */
6155       {
6156          if (format == 0 || !format->alpha_first)
6157              this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
6158                      littleendian);
6159 
6160          if (format != 0 && format->alpha_inverted)
6161             this->alpha ^= max;
6162       }
6163    }
6164 
6165    /* Calculate the scaled values, these are simply the values divided by
6166     * 'max' and the error is initialized to the double precision epsilon value
6167     * from the header file.
6168     */
6169    image_pixel_setf(this,
6170       sig_bits ? (1U << format->red_sBIT)-1 : max,
6171       sig_bits ? (1U << format->green_sBIT)-1 : max,
6172       sig_bits ? (1U << format->blue_sBIT)-1 : max,
6173       sig_bits ? (1U << format->alpha_sBIT)-1 : max);
6174 
6175    /* Store the input information for use in the transforms - these will
6176     * modify the information.
6177     */
6178    this->colour_type = colour_type;
6179    this->bit_depth = bit_depth;
6180    this->sample_depth = sample_depth;
6181    this->have_tRNS = 0;
6182    this->swap_rgb = 0;
6183    this->alpha_first = 0;
6184    this->alpha_inverted = 0;
6185    this->mono_inverted = 0;
6186    this->swap16 = 0;
6187    this->littleendian = 0;
6188    this->sig_bits = 0;
6189 }
6190 
6191 #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
6192    || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
6193    || defined PNG_READ_BACKGROUND_SUPPORTED
6194 /* Convert a palette image to an rgb image.  This necessarily converts the tRNS
6195  * chunk at the same time, because the tRNS will be in palette form.  The way
6196  * palette validation works means that the original palette is never updated,
6197  * instead the image_pixel value from the row contains the RGB of the
6198  * corresponding palette entry and *this* is updated.  Consequently this routine
6199  * only needs to change the colour type information.
6200  */
6201 static void
image_pixel_convert_PLTE(image_pixel * this)6202 image_pixel_convert_PLTE(image_pixel *this)
6203 {
6204    if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
6205    {
6206       if (this->have_tRNS)
6207       {
6208          this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
6209          this->have_tRNS = 0;
6210       }
6211       else
6212          this->colour_type = PNG_COLOR_TYPE_RGB;
6213 
6214       /* The bit depth of the row changes at this point too (notice that this is
6215        * the row format, not the sample depth, which is separate.)
6216        */
6217       this->bit_depth = 8;
6218    }
6219 }
6220 
6221 /* Add an alpha channel; this will import the tRNS information because tRNS is
6222  * not valid in an alpha image.  The bit depth will invariably be set to at
6223  * least 8 prior to 1.7.0.  Palette images will be converted to alpha (using
6224  * the above API).  With png_set_background the alpha channel is never expanded
6225  * but this routine is used by pngvalid to simplify code; 'for_background'
6226  * records this.
6227  */
6228 static void
image_pixel_add_alpha(image_pixel * this,const standard_display * display,int for_background)6229 image_pixel_add_alpha(image_pixel *this, const standard_display *display,
6230    int for_background)
6231 {
6232    if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
6233       image_pixel_convert_PLTE(this);
6234 
6235    if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
6236    {
6237       if (this->colour_type == PNG_COLOR_TYPE_GRAY)
6238       {
6239 #        if PNG_LIBPNG_VER < 10700
6240             if (!for_background && this->bit_depth < 8)
6241                this->bit_depth = this->sample_depth = 8;
6242 #        endif
6243 
6244          if (this->have_tRNS)
6245          {
6246             /* After 1.7 the expansion of bit depth only happens if there is a
6247              * tRNS chunk to expand at this point.
6248              */
6249 #           if PNG_LIBPNG_VER >= 10700
6250                if (!for_background && this->bit_depth < 8)
6251                   this->bit_depth = this->sample_depth = 8;
6252 #           endif
6253 
6254             this->have_tRNS = 0;
6255 
6256             /* Check the input, original, channel value here against the
6257              * original tRNS gray chunk valie.
6258              */
6259             if (this->red == display->transparent.red)
6260                this->alphaf = 0;
6261             else
6262                this->alphaf = 1;
6263          }
6264          else
6265             this->alphaf = 1;
6266 
6267          this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
6268       }
6269 
6270       else if (this->colour_type == PNG_COLOR_TYPE_RGB)
6271       {
6272          if (this->have_tRNS)
6273          {
6274             this->have_tRNS = 0;
6275 
6276             /* Again, check the exact input values, not the current transformed
6277              * value!
6278              */
6279             if (this->red == display->transparent.red &&
6280                this->green == display->transparent.green &&
6281                this->blue == display->transparent.blue)
6282                this->alphaf = 0;
6283             else
6284                this->alphaf = 1;
6285          }
6286          else
6287             this->alphaf = 1;
6288 
6289          this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
6290       }
6291 
6292       /* The error in the alpha is zero and the sBIT value comes from the
6293        * original sBIT data (actually it will always be the original bit depth).
6294        */
6295       this->alphae = 0;
6296       this->alpha_sBIT = display->alpha_sBIT;
6297    }
6298 }
6299 #endif /* transforms that need image_pixel_add_alpha */
6300 
6301 struct transform_display;
6302 typedef struct image_transform
6303 {
6304    /* The name of this transform: a string. */
6305    const char *name;
6306 
6307    /* Each transform can be disabled from the command line: */
6308    int enable;
6309 
6310    /* The global list of transforms; read only. */
6311    struct image_transform *const list;
6312 
6313    /* The global count of the number of times this transform has been set on an
6314     * image.
6315     */
6316    unsigned int global_use;
6317 
6318    /* The local count of the number of times this transform has been set. */
6319    unsigned int local_use;
6320 
6321    /* The next transform in the list, each transform must call its own next
6322     * transform after it has processed the pixel successfully.
6323     */
6324    const struct image_transform *next;
6325 
6326    /* A single transform for the image, expressed as a series of function
6327     * callbacks and some space for values.
6328     *
6329     * First a callback to add any required modifications to the png_modifier;
6330     * this gets called just before the modifier is set up for read.
6331     */
6332    void (*ini)(const struct image_transform *this,
6333       struct transform_display *that);
6334 
6335    /* And a callback to set the transform on the current png_read_struct:
6336     */
6337    void (*set)(const struct image_transform *this,
6338       struct transform_display *that, png_structp pp, png_infop pi);
6339 
6340    /* Then a transform that takes an input pixel in one PNG format or another
6341     * and modifies it by a pngvalid implementation of the transform (thus
6342     * duplicating the libpng intent without, we hope, duplicating the bugs
6343     * in the libpng implementation!)  The png_structp is solely to allow error
6344     * reporting via png_error and png_warning.
6345     */
6346    void (*mod)(const struct image_transform *this, image_pixel *that,
6347       png_const_structp pp, const struct transform_display *display);
6348 
6349    /* Add this transform to the list and return true if the transform is
6350     * meaningful for this colour type and bit depth - if false then the
6351     * transform should have no effect on the image so there's not a lot of
6352     * point running it.
6353     */
6354    int (*add)(struct image_transform *this,
6355       const struct image_transform **that, png_byte colour_type,
6356       png_byte bit_depth);
6357 } image_transform;
6358 
6359 typedef struct transform_display
6360 {
6361    standard_display this;
6362 
6363    /* Parameters */
6364    png_modifier*              pm;
6365    const image_transform* transform_list;
6366    unsigned int max_gamma_8;
6367 
6368    /* Local variables */
6369    png_byte output_colour_type;
6370    png_byte output_bit_depth;
6371    png_byte unpacked;
6372 
6373    /* Modifications (not necessarily used.) */
6374    gama_modification gama_mod;
6375    chrm_modification chrm_mod;
6376    srgb_modification srgb_mod;
6377 } transform_display;
6378 
6379 /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
6380 static void
transform_set_encoding(transform_display * this)6381 transform_set_encoding(transform_display *this)
6382 {
6383    /* Set up the png_modifier '_current' fields then use these to determine how
6384     * to add appropriate chunks.
6385     */
6386    png_modifier *pm = this->pm;
6387 
6388    modifier_set_encoding(pm);
6389 
6390    if (modifier_color_encoding_is_set(pm))
6391    {
6392       if (modifier_color_encoding_is_sRGB(pm))
6393          srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
6394 
6395       else
6396       {
6397          /* Set gAMA and cHRM separately. */
6398          gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
6399 
6400          if (pm->current_encoding != 0)
6401             chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
6402       }
6403    }
6404 }
6405 
6406 /* Three functions to end the list: */
6407 static void
image_transform_ini_end(const image_transform * this,transform_display * that)6408 image_transform_ini_end(const image_transform *this,
6409    transform_display *that)
6410 {
6411    UNUSED(this)
6412    UNUSED(that)
6413 }
6414 
6415 static void
image_transform_set_end(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)6416 image_transform_set_end(const image_transform *this,
6417    transform_display *that, png_structp pp, png_infop pi)
6418 {
6419    UNUSED(this)
6420    UNUSED(that)
6421    UNUSED(pp)
6422    UNUSED(pi)
6423 }
6424 
6425 /* At the end of the list recalculate the output image pixel value from the
6426  * double precision values set up by the preceding 'mod' calls:
6427  */
6428 static unsigned int
sample_scale(double sample_value,unsigned int scale)6429 sample_scale(double sample_value, unsigned int scale)
6430 {
6431    sample_value = floor(sample_value * scale + .5);
6432 
6433    /* Return NaN as 0: */
6434    if (!(sample_value > 0))
6435       sample_value = 0;
6436    else if (sample_value > scale)
6437       sample_value = scale;
6438 
6439    return (unsigned int)sample_value;
6440 }
6441 
6442 static void
image_transform_mod_end(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)6443 image_transform_mod_end(const image_transform *this, image_pixel *that,
6444     png_const_structp pp, const transform_display *display)
6445 {
6446    unsigned int scale = (1U<<that->sample_depth)-1;
6447    int sig_bits = that->sig_bits;
6448 
6449    UNUSED(this)
6450    UNUSED(pp)
6451    UNUSED(display)
6452 
6453    /* At the end recalculate the digitized red green and blue values according
6454     * to the current sample_depth of the pixel.
6455     *
6456     * The sample value is simply scaled to the maximum, checking for over
6457     * and underflow (which can both happen for some image transforms,
6458     * including simple size scaling, though libpng doesn't do that at present.
6459     */
6460    that->red = sample_scale(that->redf, scale);
6461 
6462    /* This is a bit bogus; really the above calculation should use the red_sBIT
6463     * value, not sample_depth, but because libpng does png_set_shift by just
6464     * shifting the bits we get errors if we don't do it the same way.
6465     */
6466    if (sig_bits && that->red_sBIT < that->sample_depth)
6467       that->red >>= that->sample_depth - that->red_sBIT;
6468 
6469    /* The error value is increased, at the end, according to the lowest sBIT
6470     * value seen.  Common sense tells us that the intermediate integer
6471     * representations are no more accurate than +/- 0.5 in the integral values,
6472     * the sBIT allows the implementation to be worse than this.  In addition the
6473     * PNG specification actually permits any error within the range (-1..+1),
6474     * but that is ignored here.  Instead the final digitized value is compared,
6475     * below to the digitized value of the error limits - this has the net effect
6476     * of allowing (almost) +/-1 in the output value.  It's difficult to see how
6477     * any algorithm that digitizes intermediate results can be more accurate.
6478     */
6479    that->rede += 1./(2*((1U<<that->red_sBIT)-1));
6480 
6481    if (that->colour_type & PNG_COLOR_MASK_COLOR)
6482    {
6483       that->green = sample_scale(that->greenf, scale);
6484       if (sig_bits && that->green_sBIT < that->sample_depth)
6485          that->green >>= that->sample_depth - that->green_sBIT;
6486 
6487       that->blue = sample_scale(that->bluef, scale);
6488       if (sig_bits && that->blue_sBIT < that->sample_depth)
6489          that->blue >>= that->sample_depth - that->blue_sBIT;
6490 
6491       that->greene += 1./(2*((1U<<that->green_sBIT)-1));
6492       that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
6493    }
6494    else
6495    {
6496       that->blue = that->green = that->red;
6497       that->bluef = that->greenf = that->redf;
6498       that->bluee = that->greene = that->rede;
6499    }
6500 
6501    if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
6502       that->colour_type == PNG_COLOR_TYPE_PALETTE)
6503    {
6504       that->alpha = sample_scale(that->alphaf, scale);
6505       that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
6506    }
6507    else
6508    {
6509       that->alpha = scale; /* opaque */
6510       that->alphaf = 1;    /* Override this. */
6511       that->alphae = 0;    /* It's exact ;-) */
6512    }
6513 
6514    if (sig_bits && that->alpha_sBIT < that->sample_depth)
6515       that->alpha >>= that->sample_depth - that->alpha_sBIT;
6516 }
6517 
6518 /* Static 'end' structure: */
6519 static image_transform image_transform_end =
6520 {
6521    "(end)", /* name */
6522    1, /* enable */
6523    0, /* list */
6524    0, /* global_use */
6525    0, /* local_use */
6526    0, /* next */
6527    image_transform_ini_end,
6528    image_transform_set_end,
6529    image_transform_mod_end,
6530    0 /* never called, I want it to crash if it is! */
6531 };
6532 
6533 /* Reader callbacks and implementations, where they differ from the standard
6534  * ones.
6535  */
6536 static void
transform_display_init(transform_display * dp,png_modifier * pm,png_uint_32 id,const image_transform * transform_list)6537 transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
6538     const image_transform *transform_list)
6539 {
6540    memset(dp, 0, sizeof *dp);
6541 
6542    /* Standard fields */
6543    standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
6544       pm->use_update_info);
6545 
6546    /* Parameter fields */
6547    dp->pm = pm;
6548    dp->transform_list = transform_list;
6549    dp->max_gamma_8 = 16;
6550 
6551    /* Local variable fields */
6552    dp->output_colour_type = 255; /* invalid */
6553    dp->output_bit_depth = 255;  /* invalid */
6554    dp->unpacked = 0; /* not unpacked */
6555 }
6556 
6557 static void
transform_info_imp(transform_display * dp,png_structp pp,png_infop pi)6558 transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
6559 {
6560    /* Reuse the standard stuff as appropriate. */
6561    standard_info_part1(&dp->this, pp, pi);
6562 
6563    /* Now set the list of transforms. */
6564    dp->transform_list->set(dp->transform_list, dp, pp, pi);
6565 
6566    /* Update the info structure for these transforms: */
6567    {
6568       int i = dp->this.use_update_info;
6569       /* Always do one call, even if use_update_info is 0. */
6570       do
6571          png_read_update_info(pp, pi);
6572       while (--i > 0);
6573    }
6574 
6575    /* And get the output information into the standard_display */
6576    standard_info_part2(&dp->this, pp, pi, 1/*images*/);
6577 
6578    /* Plus the extra stuff we need for the transform tests: */
6579    dp->output_colour_type = png_get_color_type(pp, pi);
6580    dp->output_bit_depth = png_get_bit_depth(pp, pi);
6581 
6582    /* If png_set_filler is in action then fake the output color type to include
6583     * an alpha channel where appropriate.
6584     */
6585    if (dp->output_bit_depth >= 8 &&
6586        (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
6587         dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
6588        dp->output_colour_type |= 4;
6589 
6590    /* Validate the combination of colour type and bit depth that we are getting
6591     * out of libpng; the semantics of something not in the PNG spec are, at
6592     * best, unclear.
6593     */
6594    switch (dp->output_colour_type)
6595    {
6596    case PNG_COLOR_TYPE_PALETTE:
6597       if (dp->output_bit_depth > 8) goto error;
6598       /* FALLTHROUGH */
6599    case PNG_COLOR_TYPE_GRAY:
6600       if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
6601          dp->output_bit_depth == 4)
6602          break;
6603       /* FALLTHROUGH */
6604    default:
6605       if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
6606          break;
6607       /* FALLTHROUGH */
6608    error:
6609       {
6610          char message[128];
6611          size_t pos;
6612 
6613          pos = safecat(message, sizeof message, 0,
6614             "invalid final bit depth: colour type(");
6615          pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6616          pos = safecat(message, sizeof message, pos, ") with bit depth: ");
6617          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6618 
6619          png_error(pp, message);
6620       }
6621    }
6622 
6623    /* Use a test pixel to check that the output agrees with what we expect -
6624     * this avoids running the whole test if the output is unexpected.  This also
6625     * checks for internal errors.
6626     */
6627    {
6628       image_pixel test_pixel;
6629 
6630       memset(&test_pixel, 0, sizeof test_pixel);
6631       test_pixel.colour_type = dp->this.colour_type; /* input */
6632       test_pixel.bit_depth = dp->this.bit_depth;
6633       if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
6634          test_pixel.sample_depth = 8;
6635       else
6636          test_pixel.sample_depth = test_pixel.bit_depth;
6637       /* Don't need sBIT here, but it must be set to non-zero to avoid
6638        * arithmetic overflows.
6639        */
6640       test_pixel.have_tRNS = dp->this.is_transparent != 0;
6641       test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
6642          test_pixel.alpha_sBIT = test_pixel.sample_depth;
6643 
6644       dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
6645 
6646       if (test_pixel.colour_type != dp->output_colour_type)
6647       {
6648          char message[128];
6649          size_t pos = safecat(message, sizeof message, 0, "colour type ");
6650 
6651          pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6652          pos = safecat(message, sizeof message, pos, " expected ");
6653          pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
6654 
6655          png_error(pp, message);
6656       }
6657 
6658       if (test_pixel.bit_depth != dp->output_bit_depth)
6659       {
6660          char message[128];
6661          size_t pos = safecat(message, sizeof message, 0, "bit depth ");
6662 
6663          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6664          pos = safecat(message, sizeof message, pos, " expected ");
6665          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6666 
6667          png_error(pp, message);
6668       }
6669 
6670       /* If both bit depth and colour type are correct check the sample depth.
6671        */
6672       if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
6673           test_pixel.sample_depth != 8) /* oops - internal error! */
6674          png_error(pp, "pngvalid: internal: palette sample depth not 8");
6675       else if (dp->unpacked && test_pixel.bit_depth != 8)
6676          png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
6677       else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
6678               && test_pixel.bit_depth != test_pixel.sample_depth)
6679       {
6680          char message[128];
6681          size_t pos = safecat(message, sizeof message, 0,
6682             "internal: sample depth ");
6683 
6684          /* Because unless something has set 'unpacked' or the image is palette
6685           * mapped we expect the transform to keep sample depth and bit depth
6686           * the same.
6687           */
6688          pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
6689          pos = safecat(message, sizeof message, pos, " expected ");
6690          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6691 
6692          png_error(pp, message);
6693       }
6694       else if (test_pixel.bit_depth != dp->output_bit_depth)
6695       {
6696          /* This could be a libpng error too; libpng has not produced what we
6697           * expect for the output bit depth.
6698           */
6699          char message[128];
6700          size_t pos = safecat(message, sizeof message, 0,
6701             "internal: bit depth ");
6702 
6703          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6704          pos = safecat(message, sizeof message, pos, " expected ");
6705          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6706 
6707          png_error(pp, message);
6708       }
6709    }
6710 }
6711 
6712 static void PNGCBAPI
transform_info(png_structp pp,png_infop pi)6713 transform_info(png_structp pp, png_infop pi)
6714 {
6715    transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
6716       pp, pi);
6717 }
6718 
6719 static void
transform_range_check(png_const_structp pp,unsigned int r,unsigned int g,unsigned int b,unsigned int a,unsigned int in_digitized,double in,unsigned int out,png_byte sample_depth,double err,double limit,const char * name,double digitization_error)6720 transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
6721    unsigned int b, unsigned int a, unsigned int in_digitized, double in,
6722    unsigned int out, png_byte sample_depth, double err, double limit,
6723    const char *name, double digitization_error)
6724 {
6725    /* Compare the scaled, digitized, values of our local calculation (in+-err)
6726     * with the digitized values libpng produced;  'sample_depth' is the actual
6727     * digitization depth of the libpng output colors (the bit depth except for
6728     * palette images where it is always 8.)  The check on 'err' is to detect
6729     * internal errors in pngvalid itself.
6730     */
6731    unsigned int max = (1U<<sample_depth)-1;
6732    double in_min = ceil((in-err)*max - digitization_error);
6733    double in_max = floor((in+err)*max + digitization_error);
6734    if (debugonly(err > limit ||) !(out >= in_min && out <= in_max))
6735    {
6736       char message[256];
6737       size_t pos;
6738 
6739       pos = safecat(message, sizeof message, 0, name);
6740       pos = safecat(message, sizeof message, pos, " output value error: rgba(");
6741       pos = safecatn(message, sizeof message, pos, r);
6742       pos = safecat(message, sizeof message, pos, ",");
6743       pos = safecatn(message, sizeof message, pos, g);
6744       pos = safecat(message, sizeof message, pos, ",");
6745       pos = safecatn(message, sizeof message, pos, b);
6746       pos = safecat(message, sizeof message, pos, ",");
6747       pos = safecatn(message, sizeof message, pos, a);
6748       pos = safecat(message, sizeof message, pos, "): ");
6749       pos = safecatn(message, sizeof message, pos, out);
6750       pos = safecat(message, sizeof message, pos, " expected: ");
6751       pos = safecatn(message, sizeof message, pos, in_digitized);
6752       pos = safecat(message, sizeof message, pos, " (");
6753       pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
6754       pos = safecat(message, sizeof message, pos, "..");
6755       pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
6756       pos = safecat(message, sizeof message, pos, ")");
6757 
6758       png_error(pp, message);
6759    }
6760 
6761    UNUSED(limit)
6762 }
6763 
6764 static void
transform_image_validate(transform_display * dp,png_const_structp pp,png_infop pi)6765 transform_image_validate(transform_display *dp, png_const_structp pp,
6766    png_infop pi)
6767 {
6768    /* Constants for the loop below: */
6769    const png_store* const ps = dp->this.ps;
6770    png_byte in_ct = dp->this.colour_type;
6771    png_byte in_bd = dp->this.bit_depth;
6772    png_uint_32 w = dp->this.w;
6773    png_uint_32 h = dp->this.h;
6774    png_byte out_ct = dp->output_colour_type;
6775    png_byte out_bd = dp->output_bit_depth;
6776    png_byte sample_depth =
6777       (png_byte)(out_ct == PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
6778    png_byte red_sBIT = dp->this.red_sBIT;
6779    png_byte green_sBIT = dp->this.green_sBIT;
6780    png_byte blue_sBIT = dp->this.blue_sBIT;
6781    png_byte alpha_sBIT = dp->this.alpha_sBIT;
6782    int have_tRNS = dp->this.is_transparent;
6783    double digitization_error;
6784 
6785    store_palette out_palette;
6786    png_uint_32 y;
6787 
6788    UNUSED(pi)
6789 
6790    /* Check for row overwrite errors */
6791    store_image_check(dp->this.ps, pp, 0);
6792 
6793    /* Read the palette corresponding to the output if the output colour type
6794     * indicates a palette, otherwise set out_palette to garbage.
6795     */
6796    if (out_ct == PNG_COLOR_TYPE_PALETTE)
6797    {
6798       /* Validate that the palette count itself has not changed - this is not
6799        * expected.
6800        */
6801       int npalette = (-1);
6802 
6803       (void)read_palette(out_palette, &npalette, pp, pi);
6804       if (npalette != dp->this.npalette)
6805          png_error(pp, "unexpected change in palette size");
6806 
6807       digitization_error = .5;
6808    }
6809    else
6810    {
6811       png_byte in_sample_depth;
6812 
6813       memset(out_palette, 0x5e, sizeof out_palette);
6814 
6815       /* use-input-precision means assume that if the input has 8 bit (or less)
6816        * samples and the output has 16 bit samples the calculations will be done
6817        * with 8 bit precision, not 16.
6818        */
6819       if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
6820          in_sample_depth = 8;
6821       else
6822          in_sample_depth = in_bd;
6823 
6824       if (sample_depth != 16 || in_sample_depth > 8 ||
6825          !dp->pm->calculations_use_input_precision)
6826          digitization_error = .5;
6827 
6828       /* Else calculations are at 8 bit precision, and the output actually
6829        * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
6830        */
6831       else
6832          digitization_error = .5 * 257;
6833    }
6834 
6835    for (y=0; y<h; ++y)
6836    {
6837       png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
6838       png_uint_32 x;
6839 
6840       /* The original, standard, row pre-transforms. */
6841       png_byte std[STANDARD_ROWMAX];
6842 
6843       transform_row(pp, std, in_ct, in_bd, y);
6844 
6845       /* Go through each original pixel transforming it and comparing with what
6846        * libpng did to the same pixel.
6847        */
6848       for (x=0; x<w; ++x)
6849       {
6850          image_pixel in_pixel, out_pixel;
6851          unsigned int r, g, b, a;
6852 
6853          /* Find out what we think the pixel should be: */
6854          image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
6855                  NULL);
6856 
6857          in_pixel.red_sBIT = red_sBIT;
6858          in_pixel.green_sBIT = green_sBIT;
6859          in_pixel.blue_sBIT = blue_sBIT;
6860          in_pixel.alpha_sBIT = alpha_sBIT;
6861          in_pixel.have_tRNS = have_tRNS != 0;
6862 
6863          /* For error detection, below. */
6864          r = in_pixel.red;
6865          g = in_pixel.green;
6866          b = in_pixel.blue;
6867          a = in_pixel.alpha;
6868 
6869          /* This applies the transforms to the input data, including output
6870           * format operations which must be used when reading the output
6871           * pixel that libpng produces.
6872           */
6873          dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
6874 
6875          /* Read the output pixel and compare it to what we got, we don't
6876           * use the error field here, so no need to update sBIT.  in_pixel
6877           * says whether we expect libpng to change the output format.
6878           */
6879          image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
6880                  &in_pixel);
6881 
6882          /* We don't expect changes to the index here even if the bit depth is
6883           * changed.
6884           */
6885          if (in_ct == PNG_COLOR_TYPE_PALETTE &&
6886             out_ct == PNG_COLOR_TYPE_PALETTE)
6887          {
6888             if (in_pixel.palette_index != out_pixel.palette_index)
6889                png_error(pp, "unexpected transformed palette index");
6890          }
6891 
6892          /* Check the colours for palette images too - in fact the palette could
6893           * be separately verified itself in most cases.
6894           */
6895          if (in_pixel.red != out_pixel.red)
6896             transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
6897                out_pixel.red, sample_depth, in_pixel.rede,
6898                dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
6899                digitization_error);
6900 
6901          if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6902             in_pixel.green != out_pixel.green)
6903             transform_range_check(pp, r, g, b, a, in_pixel.green,
6904                in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
6905                dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
6906                digitization_error);
6907 
6908          if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6909             in_pixel.blue != out_pixel.blue)
6910             transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
6911                out_pixel.blue, sample_depth, in_pixel.bluee,
6912                dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
6913                digitization_error);
6914 
6915          if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
6916             in_pixel.alpha != out_pixel.alpha)
6917             transform_range_check(pp, r, g, b, a, in_pixel.alpha,
6918                in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
6919                dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
6920                digitization_error);
6921       } /* pixel (x) loop */
6922    } /* row (y) loop */
6923 
6924    /* Record that something was actually checked to avoid a false positive. */
6925    dp->this.ps->validated = 1;
6926 }
6927 
6928 static void PNGCBAPI
transform_end(png_structp ppIn,png_infop pi)6929 transform_end(png_structp ppIn, png_infop pi)
6930 {
6931    png_const_structp pp = ppIn;
6932    transform_display *dp = voidcast(transform_display*,
6933       png_get_progressive_ptr(pp));
6934 
6935    if (!dp->this.speed)
6936       transform_image_validate(dp, pp, pi);
6937    else
6938       dp->this.ps->validated = 1;
6939 }
6940 
6941 /* A single test run. */
6942 static void
transform_test(png_modifier * pmIn,png_uint_32 idIn,const image_transform * transform_listIn,const char * const name)6943 transform_test(png_modifier *pmIn, png_uint_32 idIn,
6944     const image_transform* transform_listIn, const char * const name)
6945 {
6946    transform_display d;
6947    context(&pmIn->this, fault);
6948 
6949    transform_display_init(&d, pmIn, idIn, transform_listIn);
6950 
6951    Try
6952    {
6953       size_t pos = 0;
6954       png_structp pp;
6955       png_infop pi;
6956       char full_name[256];
6957 
6958       /* Make sure the encoding fields are correct and enter the required
6959        * modifications.
6960        */
6961       transform_set_encoding(&d);
6962 
6963       /* Add any modifications required by the transform list. */
6964       d.transform_list->ini(d.transform_list, &d);
6965 
6966       /* Add the color space information, if any, to the name. */
6967       pos = safecat(full_name, sizeof full_name, pos, name);
6968       pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
6969 
6970       /* Get a png_struct for reading the image. */
6971       pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
6972       standard_palette_init(&d.this);
6973 
6974 #     if 0
6975          /* Logging (debugging only) */
6976          {
6977             char buffer[256];
6978 
6979             (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
6980                "running test");
6981 
6982             fprintf(stderr, "%s\n", buffer);
6983          }
6984 #     endif
6985 
6986       /* Introduce the correct read function. */
6987       if (d.pm->this.progressive)
6988       {
6989          /* Share the row function with the standard implementation. */
6990          png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
6991             transform_end);
6992 
6993          /* Now feed data into the reader until we reach the end: */
6994          modifier_progressive_read(d.pm, pp, pi);
6995       }
6996       else
6997       {
6998          /* modifier_read expects a png_modifier* */
6999          png_set_read_fn(pp, d.pm, modifier_read);
7000 
7001          /* Check the header values: */
7002          png_read_info(pp, pi);
7003 
7004          /* Process the 'info' requirements. Only one image is generated */
7005          transform_info_imp(&d, pp, pi);
7006 
7007          sequential_row(&d.this, pp, pi, -1, 0);
7008 
7009          if (!d.this.speed)
7010             transform_image_validate(&d, pp, pi);
7011          else
7012             d.this.ps->validated = 1;
7013       }
7014 
7015       modifier_reset(d.pm);
7016    }
7017 
7018    Catch(fault)
7019    {
7020       modifier_reset(voidcast(png_modifier*,(void*)fault));
7021    }
7022 }
7023 
7024 /* The transforms: */
7025 #define ITSTRUCT(name) image_transform_##name
7026 #define ITDATA(name) image_transform_data_##name
7027 #define image_transform_ini image_transform_default_ini
7028 #define IT(name)\
7029 static image_transform ITSTRUCT(name) =\
7030 {\
7031    #name,\
7032    1, /*enable*/\
7033    &PT, /*list*/\
7034    0, /*global_use*/\
7035    0, /*local_use*/\
7036    0, /*next*/\
7037    image_transform_ini,\
7038    image_transform_png_set_##name##_set,\
7039    image_transform_png_set_##name##_mod,\
7040    image_transform_png_set_##name##_add\
7041 }
7042 #define PT ITSTRUCT(end) /* stores the previous transform */
7043 
7044 /* To save code: */
7045 extern void image_transform_default_ini(const image_transform *this,
7046    transform_display *that); /* silence GCC warnings */
7047 
7048 void /* private, but almost always needed */
image_transform_default_ini(const image_transform * this,transform_display * that)7049 image_transform_default_ini(const image_transform *this,
7050     transform_display *that)
7051 {
7052    this->next->ini(this->next, that);
7053 }
7054 
7055 #ifdef PNG_READ_BACKGROUND_SUPPORTED
7056 static int
image_transform_default_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7057 image_transform_default_add(image_transform *this,
7058     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7059 {
7060    UNUSED(colour_type)
7061    UNUSED(bit_depth)
7062 
7063    this->next = *that;
7064    *that = this;
7065 
7066    return 1;
7067 }
7068 #endif
7069 
7070 #ifdef PNG_READ_EXPAND_SUPPORTED
7071 /* png_set_palette_to_rgb */
7072 static void
image_transform_png_set_palette_to_rgb_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7073 image_transform_png_set_palette_to_rgb_set(const image_transform *this,
7074     transform_display *that, png_structp pp, png_infop pi)
7075 {
7076    png_set_palette_to_rgb(pp);
7077    this->next->set(this->next, that, pp, pi);
7078 }
7079 
7080 static void
image_transform_png_set_palette_to_rgb_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7081 image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
7082     image_pixel *that, png_const_structp pp,
7083     const transform_display *display)
7084 {
7085    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7086       image_pixel_convert_PLTE(that);
7087 
7088    this->next->mod(this->next, that, pp, display);
7089 }
7090 
7091 static int
image_transform_png_set_palette_to_rgb_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7092 image_transform_png_set_palette_to_rgb_add(image_transform *this,
7093     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7094 {
7095    UNUSED(bit_depth)
7096 
7097    this->next = *that;
7098    *that = this;
7099 
7100    return colour_type == PNG_COLOR_TYPE_PALETTE;
7101 }
7102 
7103 IT(palette_to_rgb);
7104 #undef PT
7105 #define PT ITSTRUCT(palette_to_rgb)
7106 #endif /* PNG_READ_EXPAND_SUPPORTED */
7107 
7108 #ifdef PNG_READ_EXPAND_SUPPORTED
7109 /* png_set_tRNS_to_alpha */
7110 static void
image_transform_png_set_tRNS_to_alpha_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7111 image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
7112    transform_display *that, png_structp pp, png_infop pi)
7113 {
7114    png_set_tRNS_to_alpha(pp);
7115 
7116    /* If there was a tRNS chunk that would get expanded and add an alpha
7117     * channel is_transparent must be updated:
7118     */
7119    if (that->this.has_tRNS)
7120       that->this.is_transparent = 1;
7121 
7122    this->next->set(this->next, that, pp, pi);
7123 }
7124 
7125 static void
image_transform_png_set_tRNS_to_alpha_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7126 image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
7127    image_pixel *that, png_const_structp pp,
7128    const transform_display *display)
7129 {
7130 #if PNG_LIBPNG_VER < 10700
7131    /* LIBPNG BUG: this always forces palette images to RGB. */
7132    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7133       image_pixel_convert_PLTE(that);
7134 #endif
7135 
7136    /* This effectively does an 'expand' only if there is some transparency to
7137     * convert to an alpha channel.
7138     */
7139    if (that->have_tRNS)
7140 #     if PNG_LIBPNG_VER >= 10700
7141          if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
7142              (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
7143 #     endif
7144       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
7145 
7146 #if PNG_LIBPNG_VER < 10700
7147    /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
7148    else
7149    {
7150       if (that->bit_depth < 8)
7151          that->bit_depth =8;
7152       if (that->sample_depth < 8)
7153          that->sample_depth = 8;
7154    }
7155 #endif
7156 
7157    this->next->mod(this->next, that, pp, display);
7158 }
7159 
7160 static int
image_transform_png_set_tRNS_to_alpha_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7161 image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
7162     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7163 {
7164    UNUSED(bit_depth)
7165 
7166    this->next = *that;
7167    *that = this;
7168 
7169    /* We don't know yet whether there will be a tRNS chunk, but we know that
7170     * this transformation should do nothing if there already is an alpha
7171     * channel.  In addition, after the bug fix in 1.7.0, there is no longer
7172     * any action on a palette image.
7173     */
7174    return
7175 #  if PNG_LIBPNG_VER >= 10700
7176       colour_type != PNG_COLOR_TYPE_PALETTE &&
7177 #  endif
7178    (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
7179 }
7180 
7181 IT(tRNS_to_alpha);
7182 #undef PT
7183 #define PT ITSTRUCT(tRNS_to_alpha)
7184 #endif /* PNG_READ_EXPAND_SUPPORTED */
7185 
7186 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
7187 /* png_set_gray_to_rgb */
7188 static void
image_transform_png_set_gray_to_rgb_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7189 image_transform_png_set_gray_to_rgb_set(const image_transform *this,
7190     transform_display *that, png_structp pp, png_infop pi)
7191 {
7192    png_set_gray_to_rgb(pp);
7193    /* NOTE: this doesn't result in tRNS expansion. */
7194    this->next->set(this->next, that, pp, pi);
7195 }
7196 
7197 static void
image_transform_png_set_gray_to_rgb_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7198 image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
7199     image_pixel *that, png_const_structp pp,
7200     const transform_display *display)
7201 {
7202    /* NOTE: we can actually pend the tRNS processing at this point because we
7203     * can correctly recognize the original pixel value even though we have
7204     * mapped the one gray channel to the three RGB ones, but in fact libpng
7205     * doesn't do this, so we don't either.
7206     */
7207    if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
7208       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
7209 
7210    /* Simply expand the bit depth and alter the colour type as required. */
7211    if (that->colour_type == PNG_COLOR_TYPE_GRAY)
7212    {
7213       /* RGB images have a bit depth at least equal to '8' */
7214       if (that->bit_depth < 8)
7215          that->sample_depth = that->bit_depth = 8;
7216 
7217       /* And just changing the colour type works here because the green and blue
7218        * channels are being maintained in lock-step with the red/gray:
7219        */
7220       that->colour_type = PNG_COLOR_TYPE_RGB;
7221    }
7222 
7223    else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7224       that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
7225 
7226    this->next->mod(this->next, that, pp, display);
7227 }
7228 
7229 static int
image_transform_png_set_gray_to_rgb_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7230 image_transform_png_set_gray_to_rgb_add(image_transform *this,
7231     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7232 {
7233    UNUSED(bit_depth)
7234 
7235    this->next = *that;
7236    *that = this;
7237 
7238    return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
7239 }
7240 
7241 IT(gray_to_rgb);
7242 #undef PT
7243 #define PT ITSTRUCT(gray_to_rgb)
7244 #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
7245 
7246 #ifdef PNG_READ_EXPAND_SUPPORTED
7247 /* png_set_expand */
7248 static void
image_transform_png_set_expand_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7249 image_transform_png_set_expand_set(const image_transform *this,
7250     transform_display *that, png_structp pp, png_infop pi)
7251 {
7252    png_set_expand(pp);
7253 
7254    if (that->this.has_tRNS)
7255       that->this.is_transparent = 1;
7256 
7257    this->next->set(this->next, that, pp, pi);
7258 }
7259 
7260 static void
image_transform_png_set_expand_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7261 image_transform_png_set_expand_mod(const image_transform *this,
7262     image_pixel *that, png_const_structp pp,
7263     const transform_display *display)
7264 {
7265    /* The general expand case depends on what the colour type is: */
7266    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7267       image_pixel_convert_PLTE(that);
7268    else if (that->bit_depth < 8) /* grayscale */
7269       that->sample_depth = that->bit_depth = 8;
7270 
7271    if (that->have_tRNS)
7272       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
7273 
7274    this->next->mod(this->next, that, pp, display);
7275 }
7276 
7277 static int
image_transform_png_set_expand_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7278 image_transform_png_set_expand_add(image_transform *this,
7279     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7280 {
7281    UNUSED(bit_depth)
7282 
7283    this->next = *that;
7284    *that = this;
7285 
7286    /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
7287     * depth is at least 8 already.
7288     */
7289    return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
7290 }
7291 
7292 IT(expand);
7293 #undef PT
7294 #define PT ITSTRUCT(expand)
7295 #endif /* PNG_READ_EXPAND_SUPPORTED */
7296 
7297 #ifdef PNG_READ_EXPAND_SUPPORTED
7298 /* png_set_expand_gray_1_2_4_to_8
7299  * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
7300  */
7301 static void
image_transform_png_set_expand_gray_1_2_4_to_8_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7302 image_transform_png_set_expand_gray_1_2_4_to_8_set(
7303     const image_transform *this, transform_display *that, png_structp pp,
7304     png_infop pi)
7305 {
7306    png_set_expand_gray_1_2_4_to_8(pp);
7307    /* NOTE: don't expect this to expand tRNS */
7308    this->next->set(this->next, that, pp, pi);
7309 }
7310 
7311 static void
image_transform_png_set_expand_gray_1_2_4_to_8_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7312 image_transform_png_set_expand_gray_1_2_4_to_8_mod(
7313     const image_transform *this, image_pixel *that, png_const_structp pp,
7314     const transform_display *display)
7315 {
7316 #if PNG_LIBPNG_VER < 10700
7317    image_transform_png_set_expand_mod(this, that, pp, display);
7318 #else
7319    /* Only expand grayscale of bit depth less than 8: */
7320    if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
7321        that->bit_depth < 8)
7322       that->sample_depth = that->bit_depth = 8;
7323 
7324    this->next->mod(this->next, that, pp, display);
7325 #endif /* 1.7 or later */
7326 }
7327 
7328 static int
image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7329 image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
7330     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7331 {
7332 #if PNG_LIBPNG_VER < 10700
7333    return image_transform_png_set_expand_add(this, that, colour_type,
7334       bit_depth);
7335 #else
7336    UNUSED(bit_depth)
7337 
7338    this->next = *that;
7339    *that = this;
7340 
7341    /* This should do nothing unless the color type is gray and the bit depth is
7342     * less than 8:
7343     */
7344    return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
7345 #endif /* 1.7 or later */
7346 }
7347 
7348 IT(expand_gray_1_2_4_to_8);
7349 #undef PT
7350 #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
7351 #endif /* PNG_READ_EXPAND_SUPPORTED */
7352 
7353 #ifdef PNG_READ_EXPAND_16_SUPPORTED
7354 /* png_set_expand_16 */
7355 static void
image_transform_png_set_expand_16_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7356 image_transform_png_set_expand_16_set(const image_transform *this,
7357     transform_display *that, png_structp pp, png_infop pi)
7358 {
7359    png_set_expand_16(pp);
7360 
7361    /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
7362 #  if PNG_LIBPNG_VER < 10700
7363       if (that->this.has_tRNS)
7364          that->this.is_transparent = 1;
7365 #  endif
7366 
7367    this->next->set(this->next, that, pp, pi);
7368 }
7369 
7370 static void
image_transform_png_set_expand_16_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7371 image_transform_png_set_expand_16_mod(const image_transform *this,
7372     image_pixel *that, png_const_structp pp,
7373     const transform_display *display)
7374 {
7375    /* Expect expand_16 to expand everything to 16 bits as a result of also
7376     * causing 'expand' to happen.
7377     */
7378    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7379       image_pixel_convert_PLTE(that);
7380 
7381    if (that->have_tRNS)
7382       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
7383 
7384    if (that->bit_depth < 16)
7385       that->sample_depth = that->bit_depth = 16;
7386 
7387    this->next->mod(this->next, that, pp, display);
7388 }
7389 
7390 static int
image_transform_png_set_expand_16_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7391 image_transform_png_set_expand_16_add(image_transform *this,
7392     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7393 {
7394    UNUSED(colour_type)
7395 
7396    this->next = *that;
7397    *that = this;
7398 
7399    /* expand_16 does something unless the bit depth is already 16. */
7400    return bit_depth < 16;
7401 }
7402 
7403 IT(expand_16);
7404 #undef PT
7405 #define PT ITSTRUCT(expand_16)
7406 #endif /* PNG_READ_EXPAND_16_SUPPORTED */
7407 
7408 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED  /* API added in 1.5.4 */
7409 /* png_set_scale_16 */
7410 static void
image_transform_png_set_scale_16_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7411 image_transform_png_set_scale_16_set(const image_transform *this,
7412     transform_display *that, png_structp pp, png_infop pi)
7413 {
7414    png_set_scale_16(pp);
7415 #  if PNG_LIBPNG_VER < 10700
7416       /* libpng will limit the gamma table size: */
7417       that->max_gamma_8 = PNG_MAX_GAMMA_8;
7418 #  endif
7419    this->next->set(this->next, that, pp, pi);
7420 }
7421 
7422 static void
image_transform_png_set_scale_16_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7423 image_transform_png_set_scale_16_mod(const image_transform *this,
7424     image_pixel *that, png_const_structp pp,
7425     const transform_display *display)
7426 {
7427    if (that->bit_depth == 16)
7428    {
7429       that->sample_depth = that->bit_depth = 8;
7430       if (that->red_sBIT > 8) that->red_sBIT = 8;
7431       if (that->green_sBIT > 8) that->green_sBIT = 8;
7432       if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7433       if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7434    }
7435 
7436    this->next->mod(this->next, that, pp, display);
7437 }
7438 
7439 static int
image_transform_png_set_scale_16_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7440 image_transform_png_set_scale_16_add(image_transform *this,
7441     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7442 {
7443    UNUSED(colour_type)
7444 
7445    this->next = *that;
7446    *that = this;
7447 
7448    return bit_depth > 8;
7449 }
7450 
7451 IT(scale_16);
7452 #undef PT
7453 #define PT ITSTRUCT(scale_16)
7454 #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
7455 
7456 #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
7457 /* png_set_strip_16 */
7458 static void
image_transform_png_set_strip_16_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7459 image_transform_png_set_strip_16_set(const image_transform *this,
7460     transform_display *that, png_structp pp, png_infop pi)
7461 {
7462    png_set_strip_16(pp);
7463 #  if PNG_LIBPNG_VER < 10700
7464       /* libpng will limit the gamma table size: */
7465       that->max_gamma_8 = PNG_MAX_GAMMA_8;
7466 #  endif
7467    this->next->set(this->next, that, pp, pi);
7468 }
7469 
7470 static void
image_transform_png_set_strip_16_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7471 image_transform_png_set_strip_16_mod(const image_transform *this,
7472     image_pixel *that, png_const_structp pp,
7473     const transform_display *display)
7474 {
7475    if (that->bit_depth == 16)
7476    {
7477       that->sample_depth = that->bit_depth = 8;
7478       if (that->red_sBIT > 8) that->red_sBIT = 8;
7479       if (that->green_sBIT > 8) that->green_sBIT = 8;
7480       if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7481       if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7482 
7483       /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
7484        * configuration option is set.  From 1.5.4 the flag is never set and the
7485        * 'scale' API (above) must be used.
7486        */
7487 #     ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
7488 #        if PNG_LIBPNG_VER >= 10504
7489 #           error PNG_READ_ACCURATE_SCALE should not be set
7490 #        endif
7491 
7492          /* The strip 16 algorithm drops the low 8 bits rather than calculating
7493           * 1/257, so we need to adjust the permitted errors appropriately:
7494           * Notice that this is only relevant prior to the addition of the
7495           * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
7496           */
7497          {
7498             const double d = (255-128.5)/65535;
7499             that->rede += d;
7500             that->greene += d;
7501             that->bluee += d;
7502             that->alphae += d;
7503          }
7504 #     endif
7505    }
7506 
7507    this->next->mod(this->next, that, pp, display);
7508 }
7509 
7510 static int
image_transform_png_set_strip_16_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7511 image_transform_png_set_strip_16_add(image_transform *this,
7512     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7513 {
7514    UNUSED(colour_type)
7515 
7516    this->next = *that;
7517    *that = this;
7518 
7519    return bit_depth > 8;
7520 }
7521 
7522 IT(strip_16);
7523 #undef PT
7524 #define PT ITSTRUCT(strip_16)
7525 #endif /* PNG_READ_16_TO_8_SUPPORTED */
7526 
7527 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
7528 /* png_set_strip_alpha */
7529 static void
image_transform_png_set_strip_alpha_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7530 image_transform_png_set_strip_alpha_set(const image_transform *this,
7531     transform_display *that, png_structp pp, png_infop pi)
7532 {
7533    png_set_strip_alpha(pp);
7534    this->next->set(this->next, that, pp, pi);
7535 }
7536 
7537 static void
image_transform_png_set_strip_alpha_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7538 image_transform_png_set_strip_alpha_mod(const image_transform *this,
7539     image_pixel *that, png_const_structp pp,
7540     const transform_display *display)
7541 {
7542    if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7543       that->colour_type = PNG_COLOR_TYPE_GRAY;
7544    else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7545       that->colour_type = PNG_COLOR_TYPE_RGB;
7546 
7547    that->have_tRNS = 0;
7548    that->alphaf = 1;
7549 
7550    this->next->mod(this->next, that, pp, display);
7551 }
7552 
7553 static int
image_transform_png_set_strip_alpha_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)7554 image_transform_png_set_strip_alpha_add(image_transform *this,
7555     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7556 {
7557    UNUSED(bit_depth)
7558 
7559    this->next = *that;
7560    *that = this;
7561 
7562    return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
7563 }
7564 
7565 IT(strip_alpha);
7566 #undef PT
7567 #define PT ITSTRUCT(strip_alpha)
7568 #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
7569 
7570 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
7571 /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
7572  * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
7573  *    png_fixed_point green)
7574  * png_get_rgb_to_gray_status
7575  *
7576  * The 'default' test here uses values known to be used inside libpng prior to
7577  * 1.7.0:
7578  *
7579  *   red:    6968
7580  *   green: 23434
7581  *   blue:   2366
7582  *
7583  * These values are being retained for compatibility, along with the somewhat
7584  * broken truncation calculation in the fast-and-inaccurate code path.  Older
7585  * versions of libpng will fail the accuracy tests below because they use the
7586  * truncation algorithm everywhere.
7587  */
7588 #define data ITDATA(rgb_to_gray)
7589 static struct
7590 {
7591    double gamma;      /* File gamma to use in processing */
7592 
7593    /* The following are the parameters for png_set_rgb_to_gray: */
7594 #  ifdef PNG_FLOATING_POINT_SUPPORTED
7595       double red_to_set;
7596       double green_to_set;
7597 #  else
7598       png_fixed_point red_to_set;
7599       png_fixed_point green_to_set;
7600 #  endif
7601 
7602    /* The actual coefficients: */
7603    double red_coefficient;
7604    double green_coefficient;
7605    double blue_coefficient;
7606 
7607    /* Set if the coeefficients have been overridden. */
7608    int coefficients_overridden;
7609 } data;
7610 
7611 #undef image_transform_ini
7612 #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
7613 static void
image_transform_png_set_rgb_to_gray_ini(const image_transform * this,transform_display * that)7614 image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
7615     transform_display *that)
7616 {
7617    png_modifier *pm = that->pm;
7618    const color_encoding *e = pm->current_encoding;
7619 
7620    UNUSED(this)
7621 
7622    /* Since we check the encoding this flag must be set: */
7623    pm->test_uses_encoding = 1;
7624 
7625    /* If 'e' is not NULL chromaticity information is present and either a cHRM
7626     * or an sRGB chunk will be inserted.
7627     */
7628    if (e != 0)
7629    {
7630       /* Coefficients come from the encoding, but may need to be normalized to a
7631        * white point Y of 1.0
7632        */
7633       const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
7634 
7635       data.red_coefficient = e->red.Y;
7636       data.green_coefficient = e->green.Y;
7637       data.blue_coefficient = e->blue.Y;
7638 
7639       if (whiteY != 1)
7640       {
7641          data.red_coefficient /= whiteY;
7642          data.green_coefficient /= whiteY;
7643          data.blue_coefficient /= whiteY;
7644       }
7645    }
7646 
7647    else
7648    {
7649       /* The default (built in) coefficients, as above: */
7650 #     if PNG_LIBPNG_VER < 10700
7651          data.red_coefficient = 6968 / 32768.;
7652          data.green_coefficient = 23434 / 32768.;
7653          data.blue_coefficient = 2366 / 32768.;
7654 #     else
7655          data.red_coefficient = .2126;
7656          data.green_coefficient = .7152;
7657          data.blue_coefficient = .0722;
7658 #     endif
7659    }
7660 
7661    data.gamma = pm->current_gamma;
7662 
7663    /* If not set then the calculations assume linear encoding (implicitly): */
7664    if (data.gamma == 0)
7665       data.gamma = 1;
7666 
7667    /* The arguments to png_set_rgb_to_gray can override the coefficients implied
7668     * by the color space encoding.  If doing exhaustive checks do the override
7669     * in each case, otherwise do it randomly.
7670     */
7671    if (pm->test_exhaustive)
7672    {
7673       /* First time in coefficients_overridden is 0, the following sets it to 1,
7674        * so repeat if it is set.  If a test fails this may mean we subsequently
7675        * skip a non-override test, ignore that.
7676        */
7677       data.coefficients_overridden = !data.coefficients_overridden;
7678       pm->repeat = data.coefficients_overridden != 0;
7679    }
7680 
7681    else
7682       data.coefficients_overridden = random_choice();
7683 
7684    if (data.coefficients_overridden)
7685    {
7686       /* These values override the color encoding defaults, simply use random
7687        * numbers.
7688        */
7689       png_uint_32 ru;
7690       double total;
7691 
7692       ru = random_u32();
7693       data.green_coefficient = total = (ru & 0xffff) / 65535.;
7694       ru >>= 16;
7695       data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
7696       total += data.red_coefficient;
7697       data.blue_coefficient = 1 - total;
7698 
7699 #     ifdef PNG_FLOATING_POINT_SUPPORTED
7700          data.red_to_set = data.red_coefficient;
7701          data.green_to_set = data.green_coefficient;
7702 #     else
7703          data.red_to_set = fix(data.red_coefficient);
7704          data.green_to_set = fix(data.green_coefficient);
7705 #     endif
7706 
7707       /* The following just changes the error messages: */
7708       pm->encoding_ignored = 1;
7709    }
7710 
7711    else
7712    {
7713       data.red_to_set = -1;
7714       data.green_to_set = -1;
7715    }
7716 
7717    /* Adjust the error limit in the png_modifier because of the larger errors
7718     * produced in the digitization during the gamma handling.
7719     */
7720    if (data.gamma != 1) /* Use gamma tables */
7721    {
7722       if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
7723       {
7724          /* The computations have the form:
7725           *
7726           *    r * rc + g * gc + b * bc
7727           *
7728           *  Each component of which is +/-1/65535 from the gamma_to_1 table
7729           *  lookup, resulting in a base error of +/-6.  The gamma_from_1
7730           *  conversion adds another +/-2 in the 16-bit case and
7731           *  +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
7732           */
7733 #        if PNG_LIBPNG_VER < 10700
7734             if (that->this.bit_depth < 16)
7735                that->max_gamma_8 = PNG_MAX_GAMMA_8;
7736 #        endif
7737          that->pm->limit += pow(
7738             (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
7739                8. :
7740                6. + (1<<(15-that->max_gamma_8))
7741             )/65535, data.gamma);
7742       }
7743 
7744       else
7745       {
7746          /* Rounding to 8 bits in the linear space causes massive errors which
7747           * will trigger the error check in transform_range_check.  Fix that
7748           * here by taking the gamma encoding into account.
7749           *
7750           * When DIGITIZE is set because a pre-1.7 version of libpng is being
7751           * tested allow a bigger slack.
7752           *
7753           * NOTE: this number only affects the internal limit check in pngvalid,
7754           * it has no effect on the limits applied to the libpng values.
7755           */
7756 #if DIGITIZE
7757           that->pm->limit += pow( 2.0/255, data.gamma);
7758 #else
7759           that->pm->limit += pow( 1.0/255, data.gamma);
7760 #endif
7761       }
7762    }
7763 
7764    else
7765    {
7766       /* With no gamma correction a large error comes from the truncation of the
7767        * calculation in the 8 bit case, allow for that here.
7768        */
7769       if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
7770          that->pm->limit += 4E-3;
7771    }
7772 }
7773 
7774 static void
image_transform_png_set_rgb_to_gray_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)7775 image_transform_png_set_rgb_to_gray_set(const image_transform *this,
7776     transform_display *that, png_structp pp, png_infop pi)
7777 {
7778    int error_action = 1; /* no error, no defines in png.h */
7779 
7780 #  ifdef PNG_FLOATING_POINT_SUPPORTED
7781       png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
7782 #  else
7783       png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
7784          data.green_to_set);
7785 #  endif
7786 
7787 #  ifdef PNG_READ_cHRM_SUPPORTED
7788       if (that->pm->current_encoding != 0)
7789       {
7790          /* We have an encoding so a cHRM chunk may have been set; if so then
7791           * check that the libpng APIs give the correct (X,Y,Z) values within
7792           * some margin of error for the round trip through the chromaticity
7793           * form.
7794           */
7795 #        ifdef PNG_FLOATING_POINT_SUPPORTED
7796 #           define API_function png_get_cHRM_XYZ
7797 #           define API_form "FP"
7798 #           define API_type double
7799 #           define API_cvt(x) (x)
7800 #        else
7801 #           define API_function png_get_cHRM_XYZ_fixed
7802 #           define API_form "fixed"
7803 #           define API_type png_fixed_point
7804 #           define API_cvt(x) ((double)(x)/PNG_FP_1)
7805 #        endif
7806 
7807          API_type rX, gX, bX;
7808          API_type rY, gY, bY;
7809          API_type rZ, gZ, bZ;
7810 
7811          if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
7812                & PNG_INFO_cHRM) != 0)
7813          {
7814             double maxe;
7815             const char *el;
7816             color_encoding e, o;
7817 
7818             /* Expect libpng to return a normalized result, but the original
7819              * color space encoding may not be normalized.
7820              */
7821             modifier_current_encoding(that->pm, &o);
7822             normalize_color_encoding(&o);
7823 
7824             /* Sanity check the pngvalid code - the coefficients should match
7825              * the normalized Y values of the encoding unless they were
7826              * overridden.
7827              */
7828             if (data.red_to_set == -1 && data.green_to_set == -1 &&
7829                (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
7830                fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
7831                fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
7832                png_error(pp, "internal pngvalid cHRM coefficient error");
7833 
7834             /* Generate a colour space encoding. */
7835             e.gamma = o.gamma; /* not used */
7836             e.red.X = API_cvt(rX);
7837             e.red.Y = API_cvt(rY);
7838             e.red.Z = API_cvt(rZ);
7839             e.green.X = API_cvt(gX);
7840             e.green.Y = API_cvt(gY);
7841             e.green.Z = API_cvt(gZ);
7842             e.blue.X = API_cvt(bX);
7843             e.blue.Y = API_cvt(bY);
7844             e.blue.Z = API_cvt(bZ);
7845 
7846             /* This should match the original one from the png_modifier, within
7847              * the range permitted by the libpng fixed point representation.
7848              */
7849             maxe = 0;
7850             el = "-"; /* Set to element name with error */
7851 
7852 #           define CHECK(col,x)\
7853             {\
7854                double err = fabs(o.col.x - e.col.x);\
7855                if (err > maxe)\
7856                {\
7857                   maxe = err;\
7858                   el = #col "(" #x ")";\
7859                }\
7860             }
7861 
7862             CHECK(red,X)
7863             CHECK(red,Y)
7864             CHECK(red,Z)
7865             CHECK(green,X)
7866             CHECK(green,Y)
7867             CHECK(green,Z)
7868             CHECK(blue,X)
7869             CHECK(blue,Y)
7870             CHECK(blue,Z)
7871 
7872             /* Here in both fixed and floating cases to check the values read
7873              * from the cHRm chunk.  PNG uses fixed point in the cHRM chunk, so
7874              * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
7875              */
7876             if (maxe >= 1E-5)
7877             {
7878                size_t pos = 0;
7879                char buffer[256];
7880 
7881                pos = safecat(buffer, sizeof buffer, pos, API_form);
7882                pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
7883                pos = safecat(buffer, sizeof buffer, pos, el);
7884                pos = safecat(buffer, sizeof buffer, pos, " error: ");
7885                pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
7886                pos = safecat(buffer, sizeof buffer, pos, " ");
7887                /* Print the color space without the gamma value: */
7888                pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
7889                pos = safecat(buffer, sizeof buffer, pos, " -> ");
7890                pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
7891 
7892                png_error(pp, buffer);
7893             }
7894          }
7895       }
7896 #  endif /* READ_cHRM */
7897 
7898    this->next->set(this->next, that, pp, pi);
7899 }
7900 
7901 static void
image_transform_png_set_rgb_to_gray_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)7902 image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
7903     image_pixel *that, png_const_structp pp,
7904     const transform_display *display)
7905 {
7906    if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
7907    {
7908       double gray, err;
7909 
7910 #     if PNG_LIBPNG_VER < 10700
7911          if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7912             image_pixel_convert_PLTE(that);
7913 #     endif
7914 
7915       /* Image now has RGB channels... */
7916 #  if DIGITIZE
7917       {
7918          png_modifier *pm = display->pm;
7919          unsigned int sample_depth = that->sample_depth;
7920          unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
7921             sample_depth);
7922          unsigned int gamma_depth =
7923             (sample_depth == 16 ?
7924                display->max_gamma_8 :
7925                (pm->assume_16_bit_calculations ?
7926                   display->max_gamma_8 :
7927                   sample_depth));
7928          int isgray;
7929          double r, g, b;
7930          double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
7931 
7932          /* Do this using interval arithmetic, otherwise it is too difficult to
7933           * handle the errors correctly.
7934           *
7935           * To handle the gamma correction work out the upper and lower bounds
7936           * of the digitized value.  Assume rounding here - normally the values
7937           * will be identical after this operation if there is only one
7938           * transform, feel free to delete the png_error checks on this below in
7939           * the future (this is just me trying to ensure it works!)
7940           *
7941           * Interval arithmetic is exact, but to implement it it must be
7942           * possible to control the floating point implementation rounding mode.
7943           * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
7944           * by DBL_EPSILON and increase the 'hi' values by the same.
7945           */
7946 #        define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
7947 #        define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
7948 
7949          r = rlo = rhi = that->redf;
7950          rlo -= that->rede;
7951          rlo = DD(rlo, calc_depth, 1/*round*/);
7952          rhi += that->rede;
7953          rhi = DU(rhi, calc_depth, 1/*round*/);
7954 
7955          g = glo = ghi = that->greenf;
7956          glo -= that->greene;
7957          glo = DD(glo, calc_depth, 1/*round*/);
7958          ghi += that->greene;
7959          ghi = DU(ghi, calc_depth, 1/*round*/);
7960 
7961          b = blo = bhi = that->bluef;
7962          blo -= that->bluee;
7963          blo = DD(blo, calc_depth, 1/*round*/);
7964          bhi += that->bluee;
7965          bhi = DU(bhi, calc_depth, 1/*round*/);
7966 
7967          isgray = r==g && g==b;
7968 
7969          if (data.gamma != 1)
7970          {
7971             const double power = 1/data.gamma;
7972             const double abse = .5/(sample_depth == 16 ? 65535 : 255);
7973 
7974             /* If a gamma calculation is done it is done using lookup tables of
7975              * precision gamma_depth, so the already digitized value above may
7976              * need to be further digitized here.
7977              */
7978             if (gamma_depth != calc_depth)
7979             {
7980                rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7981                rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7982                glo = DD(glo, gamma_depth, 0/*truncate*/);
7983                ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7984                blo = DD(blo, gamma_depth, 0/*truncate*/);
7985                bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7986             }
7987 
7988             /* 'abse' is the error in the gamma table calculation itself. */
7989             r = pow(r, power);
7990             rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
7991             rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
7992 
7993             g = pow(g, power);
7994             glo = DD(pow(glo, power)-abse, calc_depth, 1);
7995             ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
7996 
7997             b = pow(b, power);
7998             blo = DD(pow(blo, power)-abse, calc_depth, 1);
7999             bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
8000          }
8001 
8002          /* Now calculate the actual gray values.  Although the error in the
8003           * coefficients depends on whether they were specified on the command
8004           * line (in which case truncation to 15 bits happened) or not (rounding
8005           * was used) the maximum error in an individual coefficient is always
8006           * 2/32768, because even in the rounding case the requirement that
8007           * coefficients add up to 32768 can cause a larger rounding error.
8008           *
8009           * The only time when rounding doesn't occur in 1.5.5 and later is when
8010           * the non-gamma code path is used for less than 16 bit data.
8011           */
8012          gray = r * data.red_coefficient + g * data.green_coefficient +
8013             b * data.blue_coefficient;
8014 
8015          {
8016             int do_round = data.gamma != 1 || calc_depth == 16;
8017             const double ce = 2. / 32768;
8018 
8019             graylo = DD(rlo * (data.red_coefficient-ce) +
8020                glo * (data.green_coefficient-ce) +
8021                blo * (data.blue_coefficient-ce), calc_depth, do_round);
8022             if (graylo > gray) /* always accept the right answer */
8023                graylo = gray;
8024 
8025             grayhi = DU(rhi * (data.red_coefficient+ce) +
8026                ghi * (data.green_coefficient+ce) +
8027                bhi * (data.blue_coefficient+ce), calc_depth, do_round);
8028             if (grayhi < gray)
8029                grayhi = gray;
8030          }
8031 
8032          /* And invert the gamma. */
8033          if (data.gamma != 1)
8034          {
8035             const double power = data.gamma;
8036 
8037             /* And this happens yet again, shifting the values once more. */
8038             if (gamma_depth != sample_depth)
8039             {
8040                rlo = DD(rlo, gamma_depth, 0/*truncate*/);
8041                rhi = DU(rhi, gamma_depth, 0/*truncate*/);
8042                glo = DD(glo, gamma_depth, 0/*truncate*/);
8043                ghi = DU(ghi, gamma_depth, 0/*truncate*/);
8044                blo = DD(blo, gamma_depth, 0/*truncate*/);
8045                bhi = DU(bhi, gamma_depth, 0/*truncate*/);
8046             }
8047 
8048             gray = pow(gray, power);
8049             graylo = DD(pow(graylo, power), sample_depth, 1);
8050             grayhi = DU(pow(grayhi, power), sample_depth, 1);
8051          }
8052 
8053 #        undef DD
8054 #        undef DU
8055 
8056          /* Now the error can be calculated.
8057           *
8058           * If r==g==b because there is no overall gamma correction libpng
8059           * currently preserves the original value.
8060           */
8061          if (isgray)
8062             err = (that->rede + that->greene + that->bluee)/3;
8063 
8064          else
8065          {
8066             err = fabs(grayhi-gray);
8067 
8068             if (fabs(gray - graylo) > err)
8069                err = fabs(graylo-gray);
8070 
8071 #if !RELEASE_BUILD
8072             /* Check that this worked: */
8073             if (err > pm->limit)
8074             {
8075                size_t pos = 0;
8076                char buffer[128];
8077 
8078                pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
8079                pos = safecatd(buffer, sizeof buffer, pos, err, 6);
8080                pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
8081                pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
8082                png_warning(pp, buffer);
8083                pm->limit = err;
8084             }
8085 #endif /* !RELEASE_BUILD */
8086          }
8087       }
8088 #  else  /* !DIGITIZE */
8089       {
8090          double r = that->redf;
8091          double re = that->rede;
8092          double g = that->greenf;
8093          double ge = that->greene;
8094          double b = that->bluef;
8095          double be = that->bluee;
8096 
8097 #        if PNG_LIBPNG_VER < 10700
8098             /* The true gray case involves no math in earlier versions (not
8099              * true, there was some if gamma correction was happening too.)
8100              */
8101             if (r == g && r == b)
8102             {
8103                gray = r;
8104                err = re;
8105                if (err < ge) err = ge;
8106                if (err < be) err = be;
8107             }
8108 
8109             else
8110 #        endif /* before 1.7 */
8111          if (data.gamma == 1)
8112          {
8113             /* There is no need to do the conversions to and from linear space,
8114              * so the calculation should be a lot more accurate.  There is a
8115              * built in error in the coefficients because they only have 15 bits
8116              * and are adjusted to make sure they add up to 32768.  This
8117              * involves a integer calculation with truncation of the form:
8118              *
8119              *     ((int)(coefficient * 100000) * 32768)/100000
8120              *
8121              * This is done to the red and green coefficients (the ones
8122              * provided to the API) then blue is calculated from them so the
8123              * result adds up to 32768.  In the worst case this can result in
8124              * a -1 error in red and green and a +2 error in blue.  Consequently
8125              * the worst case in the calculation below is 2/32768 error.
8126              *
8127              * TODO: consider fixing this in libpng by rounding the calculation
8128              * limiting the error to 1/32768.
8129              *
8130              * Handling this by adding 2/32768 here avoids needing to increase
8131              * the global error limits to take this into account.)
8132              */
8133             gray = r * data.red_coefficient + g * data.green_coefficient +
8134                b * data.blue_coefficient;
8135             err = re * data.red_coefficient + ge * data.green_coefficient +
8136                be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
8137          }
8138 
8139          else
8140          {
8141             /* The calculation happens in linear space, and this produces much
8142              * wider errors in the encoded space.  These are handled here by
8143              * factoring the errors in to the calculation.  There are two table
8144              * lookups in the calculation and each introduces a quantization
8145              * error defined by the table size.
8146              */
8147             png_modifier *pm = display->pm;
8148             double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
8149             double out_qe = (that->sample_depth > 8 ? .5/65535 :
8150                (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
8151                .5/255));
8152             double rhi, ghi, bhi, grayhi;
8153             double g1 = 1/data.gamma;
8154 
8155             rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
8156             r -= re + in_qe; if (r < 0) r = 0;
8157             ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
8158             g -= ge + in_qe; if (g < 0) g = 0;
8159             bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
8160             b -= be + in_qe; if (b < 0) b = 0;
8161 
8162             r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
8163             g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
8164             b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
8165 
8166             /* Work out the lower and upper bounds for the gray value in the
8167              * encoded space, then work out an average and error.  Remove the
8168              * previously added input quantization error at this point.
8169              */
8170             gray = r * data.red_coefficient + g * data.green_coefficient +
8171                b * data.blue_coefficient - 2./32768 - out_qe;
8172             if (gray <= 0)
8173                gray = 0;
8174             else
8175             {
8176                gray *= (1 - 6 * DBL_EPSILON);
8177                gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
8178             }
8179 
8180             grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
8181                bhi * data.blue_coefficient + 2./32768 + out_qe;
8182             grayhi *= (1 + 6 * DBL_EPSILON);
8183             if (grayhi >= 1)
8184                grayhi = 1;
8185             else
8186                grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
8187 
8188             err = (grayhi - gray) / 2;
8189             gray = (grayhi + gray) / 2;
8190 
8191             if (err <= in_qe)
8192                err = gray * DBL_EPSILON;
8193 
8194             else
8195                err -= in_qe;
8196 
8197 #if !RELEASE_BUILD
8198             /* Validate that the error is within limits (this has caused
8199              * problems before, it's much easier to detect them here.)
8200              */
8201             if (err > pm->limit)
8202             {
8203                size_t pos = 0;
8204                char buffer[128];
8205 
8206                pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
8207                pos = safecatd(buffer, sizeof buffer, pos, err, 6);
8208                pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
8209                pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
8210                png_warning(pp, buffer);
8211                pm->limit = err;
8212             }
8213 #endif /* !RELEASE_BUILD */
8214          }
8215       }
8216 #  endif /* !DIGITIZE */
8217 
8218       that->bluef = that->greenf = that->redf = gray;
8219       that->bluee = that->greene = that->rede = err;
8220 
8221       /* The sBIT is the minimum of the three colour channel sBITs. */
8222       if (that->red_sBIT > that->green_sBIT)
8223          that->red_sBIT = that->green_sBIT;
8224       if (that->red_sBIT > that->blue_sBIT)
8225          that->red_sBIT = that->blue_sBIT;
8226       that->blue_sBIT = that->green_sBIT = that->red_sBIT;
8227 
8228       /* And remove the colour bit in the type: */
8229       if (that->colour_type == PNG_COLOR_TYPE_RGB)
8230          that->colour_type = PNG_COLOR_TYPE_GRAY;
8231       else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
8232          that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
8233    }
8234 
8235    this->next->mod(this->next, that, pp, display);
8236 }
8237 
8238 static int
image_transform_png_set_rgb_to_gray_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8239 image_transform_png_set_rgb_to_gray_add(image_transform *this,
8240     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8241 {
8242    UNUSED(bit_depth)
8243 
8244    this->next = *that;
8245    *that = this;
8246 
8247    return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
8248 }
8249 
8250 #undef data
8251 IT(rgb_to_gray);
8252 #undef PT
8253 #define PT ITSTRUCT(rgb_to_gray)
8254 #undef image_transform_ini
8255 #define image_transform_ini image_transform_default_ini
8256 #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
8257 
8258 #ifdef PNG_READ_BACKGROUND_SUPPORTED
8259 /* png_set_background(png_structp, png_const_color_16p background_color,
8260  *    int background_gamma_code, int need_expand, double background_gamma)
8261  * png_set_background_fixed(png_structp, png_const_color_16p background_color,
8262  *    int background_gamma_code, int need_expand,
8263  *    png_fixed_point background_gamma)
8264  *
8265  * This ignores the gamma (at present.)
8266 */
8267 #define data ITDATA(background)
8268 static image_pixel data;
8269 
8270 static void
image_transform_png_set_background_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8271 image_transform_png_set_background_set(const image_transform *this,
8272     transform_display *that, png_structp pp, png_infop pi)
8273 {
8274    png_byte colour_type, bit_depth;
8275    png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
8276    int expand;
8277    png_color_16 back;
8278 
8279    /* We need a background colour, because we don't know exactly what transforms
8280     * have been set we have to supply the colour in the original file format and
8281     * so we need to know what that is!  The background colour is stored in the
8282     * transform_display.
8283     */
8284    R8(random_bytes);
8285 
8286    /* Read the random value, for colour type 3 the background colour is actually
8287     * expressed as a 24bit rgb, not an index.
8288     */
8289    colour_type = that->this.colour_type;
8290    if (colour_type == 3)
8291    {
8292       colour_type = PNG_COLOR_TYPE_RGB;
8293       bit_depth = 8;
8294       expand = 0; /* passing in an RGB not a pixel index */
8295    }
8296 
8297    else
8298    {
8299       if (that->this.has_tRNS)
8300          that->this.is_transparent = 1;
8301 
8302       bit_depth = that->this.bit_depth;
8303       expand = 1;
8304    }
8305 
8306    image_pixel_init(&data, random_bytes, colour_type,
8307       bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
8308 
8309    /* Extract the background colour from this image_pixel, but make sure the
8310     * unused fields of 'back' are garbage.
8311     */
8312    R8(back);
8313 
8314    if (colour_type & PNG_COLOR_MASK_COLOR)
8315    {
8316       back.red = (png_uint_16)data.red;
8317       back.green = (png_uint_16)data.green;
8318       back.blue = (png_uint_16)data.blue;
8319    }
8320 
8321    else
8322       back.gray = (png_uint_16)data.red;
8323 
8324 #ifdef PNG_FLOATING_POINT_SUPPORTED
8325    png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
8326 #else
8327    png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
8328 #endif
8329 
8330    this->next->set(this->next, that, pp, pi);
8331 }
8332 
8333 static void
image_transform_png_set_background_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8334 image_transform_png_set_background_mod(const image_transform *this,
8335     image_pixel *that, png_const_structp pp,
8336     const transform_display *display)
8337 {
8338    /* Check for tRNS first: */
8339    if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
8340       image_pixel_add_alpha(that, &display->this, 1/*for background*/);
8341 
8342    /* This is only necessary if the alpha value is less than 1. */
8343    if (that->alphaf < 1)
8344    {
8345       /* Now we do the background calculation without any gamma correction. */
8346       if (that->alphaf <= 0)
8347       {
8348          that->redf = data.redf;
8349          that->greenf = data.greenf;
8350          that->bluef = data.bluef;
8351 
8352          that->rede = data.rede;
8353          that->greene = data.greene;
8354          that->bluee = data.bluee;
8355 
8356          that->red_sBIT= data.red_sBIT;
8357          that->green_sBIT= data.green_sBIT;
8358          that->blue_sBIT= data.blue_sBIT;
8359       }
8360 
8361       else /* 0 < alpha < 1 */
8362       {
8363          double alf = 1 - that->alphaf;
8364 
8365          that->redf = that->redf * that->alphaf + data.redf * alf;
8366          that->rede = that->rede * that->alphaf + data.rede * alf +
8367             DBL_EPSILON;
8368          that->greenf = that->greenf * that->alphaf + data.greenf * alf;
8369          that->greene = that->greene * that->alphaf + data.greene * alf +
8370             DBL_EPSILON;
8371          that->bluef = that->bluef * that->alphaf + data.bluef * alf;
8372          that->bluee = that->bluee * that->alphaf + data.bluee * alf +
8373             DBL_EPSILON;
8374       }
8375 
8376       /* Remove the alpha type and set the alpha (not in that order.) */
8377       that->alphaf = 1;
8378       that->alphae = 0;
8379    }
8380 
8381    if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
8382       that->colour_type = PNG_COLOR_TYPE_RGB;
8383    else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
8384       that->colour_type = PNG_COLOR_TYPE_GRAY;
8385    /* PNG_COLOR_TYPE_PALETTE is not changed */
8386 
8387    this->next->mod(this->next, that, pp, display);
8388 }
8389 
8390 #define image_transform_png_set_background_add image_transform_default_add
8391 
8392 #undef data
8393 IT(background);
8394 #undef PT
8395 #define PT ITSTRUCT(background)
8396 #endif /* PNG_READ_BACKGROUND_SUPPORTED */
8397 
8398 /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
8399  *    int maximum_colors, png_const_uint_16p histogram, int full_quantize)
8400  *
8401  * Very difficult to validate this!
8402  */
8403 /*NOTE: TBD NYI */
8404 
8405 /* The data layout transforms are handled by swapping our own channel data,
8406  * necessarily these need to happen at the end of the transform list because the
8407  * semantic of the channels changes after these are executed.  Some of these,
8408  * like set_shift and set_packing, can't be done at present because they change
8409  * the layout of the data at the sub-sample level so sample() won't get the
8410  * right answer.
8411  */
8412 /* png_set_invert_alpha */
8413 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
8414 /* Invert the alpha channel
8415  *
8416  *  png_set_invert_alpha(png_structrp png_ptr)
8417  */
8418 static void
image_transform_png_set_invert_alpha_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8419 image_transform_png_set_invert_alpha_set(const image_transform *this,
8420     transform_display *that, png_structp pp, png_infop pi)
8421 {
8422    png_set_invert_alpha(pp);
8423    this->next->set(this->next, that, pp, pi);
8424 }
8425 
8426 static void
image_transform_png_set_invert_alpha_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8427 image_transform_png_set_invert_alpha_mod(const image_transform *this,
8428     image_pixel *that, png_const_structp pp,
8429     const transform_display *display)
8430 {
8431    if (that->colour_type & 4)
8432       that->alpha_inverted = 1;
8433 
8434    this->next->mod(this->next, that, pp, display);
8435 }
8436 
8437 static int
image_transform_png_set_invert_alpha_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8438 image_transform_png_set_invert_alpha_add(image_transform *this,
8439     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8440 {
8441    UNUSED(bit_depth)
8442 
8443    this->next = *that;
8444    *that = this;
8445 
8446    /* Only has an effect on pixels with alpha: */
8447    return (colour_type & 4) != 0;
8448 }
8449 
8450 IT(invert_alpha);
8451 #undef PT
8452 #define PT ITSTRUCT(invert_alpha)
8453 
8454 #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
8455 
8456 /* png_set_bgr */
8457 #ifdef PNG_READ_BGR_SUPPORTED
8458 /* Swap R,G,B channels to order B,G,R.
8459  *
8460  *  png_set_bgr(png_structrp png_ptr)
8461  *
8462  * This only has an effect on RGB and RGBA pixels.
8463  */
8464 static void
image_transform_png_set_bgr_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8465 image_transform_png_set_bgr_set(const image_transform *this,
8466     transform_display *that, png_structp pp, png_infop pi)
8467 {
8468    png_set_bgr(pp);
8469    this->next->set(this->next, that, pp, pi);
8470 }
8471 
8472 static void
image_transform_png_set_bgr_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8473 image_transform_png_set_bgr_mod(const image_transform *this,
8474     image_pixel *that, png_const_structp pp,
8475     const transform_display *display)
8476 {
8477    if (that->colour_type == PNG_COLOR_TYPE_RGB ||
8478        that->colour_type == PNG_COLOR_TYPE_RGBA)
8479        that->swap_rgb = 1;
8480 
8481    this->next->mod(this->next, that, pp, display);
8482 }
8483 
8484 static int
image_transform_png_set_bgr_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8485 image_transform_png_set_bgr_add(image_transform *this,
8486     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8487 {
8488    UNUSED(bit_depth)
8489 
8490    this->next = *that;
8491    *that = this;
8492 
8493    return colour_type == PNG_COLOR_TYPE_RGB ||
8494        colour_type == PNG_COLOR_TYPE_RGBA;
8495 }
8496 
8497 IT(bgr);
8498 #undef PT
8499 #define PT ITSTRUCT(bgr)
8500 
8501 #endif /* PNG_READ_BGR_SUPPORTED */
8502 
8503 /* png_set_swap_alpha */
8504 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
8505 /* Put the alpha channel first.
8506  *
8507  *  png_set_swap_alpha(png_structrp png_ptr)
8508  *
8509  * This only has an effect on GA and RGBA pixels.
8510  */
8511 static void
image_transform_png_set_swap_alpha_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8512 image_transform_png_set_swap_alpha_set(const image_transform *this,
8513     transform_display *that, png_structp pp, png_infop pi)
8514 {
8515    png_set_swap_alpha(pp);
8516    this->next->set(this->next, that, pp, pi);
8517 }
8518 
8519 static void
image_transform_png_set_swap_alpha_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8520 image_transform_png_set_swap_alpha_mod(const image_transform *this,
8521     image_pixel *that, png_const_structp pp,
8522     const transform_display *display)
8523 {
8524    if (that->colour_type == PNG_COLOR_TYPE_GA ||
8525        that->colour_type == PNG_COLOR_TYPE_RGBA)
8526       that->alpha_first = 1;
8527 
8528    this->next->mod(this->next, that, pp, display);
8529 }
8530 
8531 static int
image_transform_png_set_swap_alpha_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8532 image_transform_png_set_swap_alpha_add(image_transform *this,
8533     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8534 {
8535    UNUSED(bit_depth)
8536 
8537    this->next = *that;
8538    *that = this;
8539 
8540    return colour_type == PNG_COLOR_TYPE_GA ||
8541        colour_type == PNG_COLOR_TYPE_RGBA;
8542 }
8543 
8544 IT(swap_alpha);
8545 #undef PT
8546 #define PT ITSTRUCT(swap_alpha)
8547 
8548 #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
8549 
8550 /* png_set_swap */
8551 #ifdef PNG_READ_SWAP_SUPPORTED
8552 /* Byte swap 16-bit components.
8553  *
8554  *  png_set_swap(png_structrp png_ptr)
8555  */
8556 static void
image_transform_png_set_swap_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8557 image_transform_png_set_swap_set(const image_transform *this,
8558     transform_display *that, png_structp pp, png_infop pi)
8559 {
8560    png_set_swap(pp);
8561    this->next->set(this->next, that, pp, pi);
8562 }
8563 
8564 static void
image_transform_png_set_swap_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8565 image_transform_png_set_swap_mod(const image_transform *this,
8566     image_pixel *that, png_const_structp pp,
8567     const transform_display *display)
8568 {
8569    if (that->bit_depth == 16)
8570       that->swap16 = 1;
8571 
8572    this->next->mod(this->next, that, pp, display);
8573 }
8574 
8575 static int
image_transform_png_set_swap_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8576 image_transform_png_set_swap_add(image_transform *this,
8577     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8578 {
8579    UNUSED(colour_type)
8580 
8581    this->next = *that;
8582    *that = this;
8583 
8584    return bit_depth == 16;
8585 }
8586 
8587 IT(swap);
8588 #undef PT
8589 #define PT ITSTRUCT(swap)
8590 
8591 #endif /* PNG_READ_SWAP_SUPPORTED */
8592 
8593 #ifdef PNG_READ_FILLER_SUPPORTED
8594 /* Add a filler byte to 8-bit Gray or 24-bit RGB images.
8595  *
8596  *  png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
8597  *
8598  * Flags:
8599  *
8600  *  PNG_FILLER_BEFORE
8601  *  PNG_FILLER_AFTER
8602  */
8603 #define data ITDATA(filler)
8604 static struct
8605 {
8606    png_uint_32 filler;
8607    int         flags;
8608 } data;
8609 
8610 static void
image_transform_png_set_filler_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8611 image_transform_png_set_filler_set(const image_transform *this,
8612     transform_display *that, png_structp pp, png_infop pi)
8613 {
8614    /* Need a random choice for 'before' and 'after' as well as for the
8615     * filler.  The 'filler' value has all 32 bits set, but only bit_depth
8616     * will be used.  At this point we don't know bit_depth.
8617     */
8618    data.filler = random_u32();
8619    data.flags = random_choice();
8620 
8621    png_set_filler(pp, data.filler, data.flags);
8622 
8623    /* The standard display handling stuff also needs to know that
8624     * there is a filler, so set that here.
8625     */
8626    that->this.filler = 1;
8627 
8628    this->next->set(this->next, that, pp, pi);
8629 }
8630 
8631 static void
image_transform_png_set_filler_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8632 image_transform_png_set_filler_mod(const image_transform *this,
8633     image_pixel *that, png_const_structp pp,
8634     const transform_display *display)
8635 {
8636    if (that->bit_depth >= 8 &&
8637        (that->colour_type == PNG_COLOR_TYPE_RGB ||
8638         that->colour_type == PNG_COLOR_TYPE_GRAY))
8639    {
8640       unsigned int max = (1U << that->bit_depth)-1;
8641       that->alpha = data.filler & max;
8642       that->alphaf = ((double)that->alpha) / max;
8643       that->alphae = 0;
8644 
8645       /* The filler has been stored in the alpha channel, we must record
8646        * that this has been done for the checking later on, the color
8647        * type is faked to have an alpha channel, but libpng won't report
8648        * this; the app has to know the extra channel is there and this
8649        * was recording in standard_display::filler above.
8650        */
8651       that->colour_type |= 4; /* alpha added */
8652       that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8653    }
8654 
8655    this->next->mod(this->next, that, pp, display);
8656 }
8657 
8658 static int
image_transform_png_set_filler_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8659 image_transform_png_set_filler_add(image_transform *this,
8660     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8661 {
8662    this->next = *that;
8663    *that = this;
8664 
8665    return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8666            colour_type == PNG_COLOR_TYPE_GRAY);
8667 }
8668 
8669 #undef data
8670 IT(filler);
8671 #undef PT
8672 #define PT ITSTRUCT(filler)
8673 
8674 /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
8675 /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
8676 #define data ITDATA(add_alpha)
8677 static struct
8678 {
8679    png_uint_32 filler;
8680    int         flags;
8681 } data;
8682 
8683 static void
image_transform_png_set_add_alpha_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8684 image_transform_png_set_add_alpha_set(const image_transform *this,
8685     transform_display *that, png_structp pp, png_infop pi)
8686 {
8687    /* Need a random choice for 'before' and 'after' as well as for the
8688     * filler.  The 'filler' value has all 32 bits set, but only bit_depth
8689     * will be used.  At this point we don't know bit_depth.
8690     */
8691    data.filler = random_u32();
8692    data.flags = random_choice();
8693 
8694    png_set_add_alpha(pp, data.filler, data.flags);
8695    this->next->set(this->next, that, pp, pi);
8696 }
8697 
8698 static void
image_transform_png_set_add_alpha_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8699 image_transform_png_set_add_alpha_mod(const image_transform *this,
8700     image_pixel *that, png_const_structp pp,
8701     const transform_display *display)
8702 {
8703    if (that->bit_depth >= 8 &&
8704        (that->colour_type == PNG_COLOR_TYPE_RGB ||
8705         that->colour_type == PNG_COLOR_TYPE_GRAY))
8706    {
8707       unsigned int max = (1U << that->bit_depth)-1;
8708       that->alpha = data.filler & max;
8709       that->alphaf = ((double)that->alpha) / max;
8710       that->alphae = 0;
8711 
8712       that->colour_type |= 4; /* alpha added */
8713       that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8714    }
8715 
8716    this->next->mod(this->next, that, pp, display);
8717 }
8718 
8719 static int
image_transform_png_set_add_alpha_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8720 image_transform_png_set_add_alpha_add(image_transform *this,
8721     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8722 {
8723    this->next = *that;
8724    *that = this;
8725 
8726    return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8727            colour_type == PNG_COLOR_TYPE_GRAY);
8728 }
8729 
8730 #undef data
8731 IT(add_alpha);
8732 #undef PT
8733 #define PT ITSTRUCT(add_alpha)
8734 
8735 #endif /* PNG_READ_FILLER_SUPPORTED */
8736 
8737 /* png_set_packing */
8738 #ifdef PNG_READ_PACK_SUPPORTED
8739 /* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
8740  *
8741  *  png_set_packing(png_structrp png_ptr)
8742  *
8743  * This should only affect grayscale and palette images with less than 8 bits
8744  * per pixel.
8745  */
8746 static void
image_transform_png_set_packing_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8747 image_transform_png_set_packing_set(const image_transform *this,
8748     transform_display *that, png_structp pp, png_infop pi)
8749 {
8750    png_set_packing(pp);
8751    that->unpacked = 1;
8752    this->next->set(this->next, that, pp, pi);
8753 }
8754 
8755 static void
image_transform_png_set_packing_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8756 image_transform_png_set_packing_mod(const image_transform *this,
8757     image_pixel *that, png_const_structp pp,
8758     const transform_display *display)
8759 {
8760    /* The general expand case depends on what the colour type is,
8761     * low bit-depth pixel values are unpacked into bytes without
8762     * scaling, so sample_depth is not changed.
8763     */
8764    if (that->bit_depth < 8) /* grayscale or palette */
8765       that->bit_depth = 8;
8766 
8767    this->next->mod(this->next, that, pp, display);
8768 }
8769 
8770 static int
image_transform_png_set_packing_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8771 image_transform_png_set_packing_add(image_transform *this,
8772     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8773 {
8774    UNUSED(colour_type)
8775 
8776    this->next = *that;
8777    *that = this;
8778 
8779    /* Nothing should happen unless the bit depth is less than 8: */
8780    return bit_depth < 8;
8781 }
8782 
8783 IT(packing);
8784 #undef PT
8785 #define PT ITSTRUCT(packing)
8786 
8787 #endif /* PNG_READ_PACK_SUPPORTED */
8788 
8789 /* png_set_packswap */
8790 #ifdef PNG_READ_PACKSWAP_SUPPORTED
8791 /* Swap pixels packed into bytes; reverses the order on screen so that
8792  * the high order bits correspond to the rightmost pixels.
8793  *
8794  *  png_set_packswap(png_structrp png_ptr)
8795  */
8796 static void
image_transform_png_set_packswap_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8797 image_transform_png_set_packswap_set(const image_transform *this,
8798     transform_display *that, png_structp pp, png_infop pi)
8799 {
8800    png_set_packswap(pp);
8801    that->this.littleendian = 1;
8802    this->next->set(this->next, that, pp, pi);
8803 }
8804 
8805 static void
image_transform_png_set_packswap_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8806 image_transform_png_set_packswap_mod(const image_transform *this,
8807     image_pixel *that, png_const_structp pp,
8808     const transform_display *display)
8809 {
8810    if (that->bit_depth < 8)
8811       that->littleendian = 1;
8812 
8813    this->next->mod(this->next, that, pp, display);
8814 }
8815 
8816 static int
image_transform_png_set_packswap_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8817 image_transform_png_set_packswap_add(image_transform *this,
8818     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8819 {
8820    UNUSED(colour_type)
8821 
8822    this->next = *that;
8823    *that = this;
8824 
8825    return bit_depth < 8;
8826 }
8827 
8828 IT(packswap);
8829 #undef PT
8830 #define PT ITSTRUCT(packswap)
8831 
8832 #endif /* PNG_READ_PACKSWAP_SUPPORTED */
8833 
8834 
8835 /* png_set_invert_mono */
8836 #ifdef PNG_READ_INVERT_MONO_SUPPORTED
8837 /* Invert the gray channel
8838  *
8839  *  png_set_invert_mono(png_structrp png_ptr)
8840  */
8841 static void
image_transform_png_set_invert_mono_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8842 image_transform_png_set_invert_mono_set(const image_transform *this,
8843     transform_display *that, png_structp pp, png_infop pi)
8844 {
8845    png_set_invert_mono(pp);
8846    this->next->set(this->next, that, pp, pi);
8847 }
8848 
8849 static void
image_transform_png_set_invert_mono_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8850 image_transform_png_set_invert_mono_mod(const image_transform *this,
8851     image_pixel *that, png_const_structp pp,
8852     const transform_display *display)
8853 {
8854    if (that->colour_type & 4)
8855       that->mono_inverted = 1;
8856 
8857    this->next->mod(this->next, that, pp, display);
8858 }
8859 
8860 static int
image_transform_png_set_invert_mono_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8861 image_transform_png_set_invert_mono_add(image_transform *this,
8862     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8863 {
8864    UNUSED(bit_depth)
8865 
8866    this->next = *that;
8867    *that = this;
8868 
8869    /* Only has an effect on pixels with no colour: */
8870    return (colour_type & 2) == 0;
8871 }
8872 
8873 IT(invert_mono);
8874 #undef PT
8875 #define PT ITSTRUCT(invert_mono)
8876 
8877 #endif /* PNG_READ_INVERT_MONO_SUPPORTED */
8878 
8879 #ifdef PNG_READ_SHIFT_SUPPORTED
8880 /* png_set_shift(png_structp, png_const_color_8p true_bits)
8881  *
8882  * The output pixels will be shifted by the given true_bits
8883  * values.
8884  */
8885 #define data ITDATA(shift)
8886 static png_color_8 data;
8887 
8888 static void
image_transform_png_set_shift_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8889 image_transform_png_set_shift_set(const image_transform *this,
8890     transform_display *that, png_structp pp, png_infop pi)
8891 {
8892    /* Get a random set of shifts.  The shifts need to do something
8893     * to test the transform, so they are limited to the bit depth
8894     * of the input image.  Notice that in the following the 'gray'
8895     * field is randomized independently.  This acts as a check that
8896     * libpng does use the correct field.
8897     */
8898    unsigned int depth = that->this.bit_depth;
8899 
8900    data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
8901    data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
8902    data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
8903    data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
8904    data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
8905 
8906    png_set_shift(pp, &data);
8907    this->next->set(this->next, that, pp, pi);
8908 }
8909 
8910 static void
image_transform_png_set_shift_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8911 image_transform_png_set_shift_mod(const image_transform *this,
8912     image_pixel *that, png_const_structp pp,
8913     const transform_display *display)
8914 {
8915    /* Copy the correct values into the sBIT fields, libpng does not do
8916     * anything to palette data:
8917     */
8918    if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
8919    {
8920        that->sig_bits = 1;
8921 
8922        /* The sBIT fields are reset to the values previously sent to
8923         * png_set_shift according to the colour type.
8924         * does.
8925         */
8926        if (that->colour_type & 2) /* RGB channels */
8927        {
8928           that->red_sBIT = data.red;
8929           that->green_sBIT = data.green;
8930           that->blue_sBIT = data.blue;
8931        }
8932 
8933        else /* One grey channel */
8934           that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
8935 
8936        that->alpha_sBIT = data.alpha;
8937    }
8938 
8939    this->next->mod(this->next, that, pp, display);
8940 }
8941 
8942 static int
image_transform_png_set_shift_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8943 image_transform_png_set_shift_add(image_transform *this,
8944     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8945 {
8946    UNUSED(bit_depth)
8947 
8948    this->next = *that;
8949    *that = this;
8950 
8951    return colour_type != PNG_COLOR_TYPE_PALETTE;
8952 }
8953 
8954 IT(shift);
8955 #undef PT
8956 #define PT ITSTRUCT(shift)
8957 
8958 #endif /* PNG_READ_SHIFT_SUPPORTED */
8959 
8960 #ifdef THIS_IS_THE_PROFORMA
8961 static void
_set(const image_transform * this,transform_display * that,png_structp pp,png_infop pi)8962 image_transform_png_set_@_set(const image_transform *this,
8963     transform_display *that, png_structp pp, png_infop pi)
8964 {
8965    png_set_@(pp);
8966    this->next->set(this->next, that, pp, pi);
8967 }
8968 
8969 static void
_mod(const image_transform * this,image_pixel * that,png_const_structp pp,const transform_display * display)8970 image_transform_png_set_@_mod(const image_transform *this,
8971     image_pixel *that, png_const_structp pp,
8972     const transform_display *display)
8973 {
8974    this->next->mod(this->next, that, pp, display);
8975 }
8976 
8977 static int
_add(image_transform * this,const image_transform ** that,png_byte colour_type,png_byte bit_depth)8978 image_transform_png_set_@_add(image_transform *this,
8979     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8980 {
8981    this->next = *that;
8982    *that = this;
8983 
8984    return 1;
8985 }
8986 
8987 IT(@);
8988 #endif
8989 
8990 
8991 /* This may just be 'end' if all the transforms are disabled! */
8992 static image_transform *const image_transform_first = &PT;
8993 
8994 static void
transform_enable(const char * name)8995 transform_enable(const char *name)
8996 {
8997    /* Everything starts out enabled, so if we see an 'enable' disabled
8998     * everything else the first time round.
8999     */
9000    static int all_disabled = 0;
9001    int found_it = 0;
9002    image_transform *list = image_transform_first;
9003 
9004    while (list != &image_transform_end)
9005    {
9006       if (strcmp(list->name, name) == 0)
9007       {
9008          list->enable = 1;
9009          found_it = 1;
9010       }
9011       else if (!all_disabled)
9012          list->enable = 0;
9013 
9014       list = list->list;
9015    }
9016 
9017    all_disabled = 1;
9018 
9019    if (!found_it)
9020    {
9021       fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
9022          name);
9023       exit(99);
9024    }
9025 }
9026 
9027 static void
transform_disable(const char * name)9028 transform_disable(const char *name)
9029 {
9030    image_transform *list = image_transform_first;
9031 
9032    while (list != &image_transform_end)
9033    {
9034       if (strcmp(list->name, name) == 0)
9035       {
9036          list->enable = 0;
9037          return;
9038       }
9039 
9040       list = list->list;
9041    }
9042 
9043    fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
9044       name);
9045    exit(99);
9046 }
9047 
9048 static void
image_transform_reset_count(void)9049 image_transform_reset_count(void)
9050 {
9051    image_transform *next = image_transform_first;
9052    int count = 0;
9053 
9054    while (next != &image_transform_end)
9055    {
9056       next->local_use = 0;
9057       next->next = 0;
9058       next = next->list;
9059       ++count;
9060    }
9061 
9062    /* This can only happen if we every have more than 32 transforms (excluding
9063     * the end) in the list.
9064     */
9065    if (count > 32) abort();
9066 }
9067 
9068 static int
image_transform_test_counter(png_uint_32 counter,unsigned int max)9069 image_transform_test_counter(png_uint_32 counter, unsigned int max)
9070 {
9071    /* Test the list to see if there is any point continuing, given a current
9072     * counter and a 'max' value.
9073     */
9074    image_transform *next = image_transform_first;
9075 
9076    while (next != &image_transform_end)
9077    {
9078       /* For max 0 or 1 continue until the counter overflows: */
9079       counter >>= 1;
9080 
9081       /* Continue if any entry hasn't reacked the max. */
9082       if (max > 1 && next->local_use < max)
9083          return 1;
9084       next = next->list;
9085    }
9086 
9087    return max <= 1 && counter == 0;
9088 }
9089 
9090 static png_uint_32
image_transform_add(const image_transform ** this,unsigned int max,png_uint_32 counter,char * name,size_t sizeof_name,size_t * pos,png_byte colour_type,png_byte bit_depth)9091 image_transform_add(const image_transform **this, unsigned int max,
9092    png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
9093    png_byte colour_type, png_byte bit_depth)
9094 {
9095    for (;;) /* until we manage to add something */
9096    {
9097       png_uint_32 mask;
9098       image_transform *list;
9099 
9100       /* Find the next counter value, if the counter is zero this is the start
9101        * of the list.  This routine always returns the current counter (not the
9102        * next) so it returns 0 at the end and expects 0 at the beginning.
9103        */
9104       if (counter == 0) /* first time */
9105       {
9106          image_transform_reset_count();
9107          if (max <= 1)
9108             counter = 1;
9109          else
9110             counter = random_32();
9111       }
9112       else /* advance the counter */
9113       {
9114          switch (max)
9115          {
9116             case 0:  ++counter; break;
9117             case 1:  counter <<= 1; break;
9118             default: counter = random_32(); break;
9119          }
9120       }
9121 
9122       /* Now add all these items, if possible */
9123       *this = &image_transform_end;
9124       list = image_transform_first;
9125       mask = 1;
9126 
9127       /* Go through the whole list adding anything that the counter selects: */
9128       while (list != &image_transform_end)
9129       {
9130          if ((counter & mask) != 0 && list->enable &&
9131              (max == 0 || list->local_use < max))
9132          {
9133             /* Candidate to add: */
9134             if (list->add(list, this, colour_type, bit_depth) || max == 0)
9135             {
9136                /* Added, so add to the name too. */
9137                *pos = safecat(name, sizeof_name, *pos, " +");
9138                *pos = safecat(name, sizeof_name, *pos, list->name);
9139             }
9140 
9141             else
9142             {
9143                /* Not useful and max>0, so remove it from *this: */
9144                *this = list->next;
9145                list->next = 0;
9146 
9147                /* And, since we know it isn't useful, stop it being added again
9148                 * in this run:
9149                 */
9150                list->local_use = max;
9151             }
9152          }
9153 
9154          mask <<= 1;
9155          list = list->list;
9156       }
9157 
9158       /* Now if anything was added we have something to do. */
9159       if (*this != &image_transform_end)
9160          return counter;
9161 
9162       /* Nothing added, but was there anything in there to add? */
9163       if (!image_transform_test_counter(counter, max))
9164          return 0;
9165    }
9166 }
9167 
9168 static void
perform_transform_test(png_modifier * pm)9169 perform_transform_test(png_modifier *pm)
9170 {
9171    png_byte colour_type = 0;
9172    png_byte bit_depth = 0;
9173    unsigned int palette_number = 0;
9174 
9175    while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
9176             pm->test_tRNS))
9177    {
9178       png_uint_32 counter = 0;
9179       size_t base_pos;
9180       char name[64];
9181 
9182       base_pos = safecat(name, sizeof name, 0, "transform:");
9183 
9184       for (;;)
9185       {
9186          size_t pos = base_pos;
9187          const image_transform *list = 0;
9188 
9189          /* 'max' is currently hardwired to '1'; this should be settable on the
9190           * command line.
9191           */
9192          counter = image_transform_add(&list, 1/*max*/, counter,
9193             name, sizeof name, &pos, colour_type, bit_depth);
9194 
9195          if (counter == 0)
9196             break;
9197 
9198          /* The command line can change this to checking interlaced images. */
9199          do
9200          {
9201             pm->repeat = 0;
9202             transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
9203                pm->interlace_type, 0, 0, 0), list, name);
9204 
9205             if (fail(pm))
9206                return;
9207          }
9208          while (pm->repeat);
9209       }
9210    }
9211 }
9212 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
9213 
9214 /********************************* GAMMA TESTS ********************************/
9215 #ifdef PNG_READ_GAMMA_SUPPORTED
9216 /* Reader callbacks and implementations, where they differ from the standard
9217  * ones.
9218  */
9219 typedef struct gamma_display
9220 {
9221    standard_display this;
9222 
9223    /* Parameters */
9224    png_modifier*    pm;
9225    double           file_gamma;
9226    double           screen_gamma;
9227    double           background_gamma;
9228    png_byte         sbit;
9229    int              threshold_test;
9230    int              use_input_precision;
9231    int              scale16;
9232    int              expand16;
9233    int              do_background;
9234    png_color_16     background_color;
9235 
9236    /* Local variables */
9237    double       maxerrout;
9238    double       maxerrpc;
9239    double       maxerrabs;
9240 } gamma_display;
9241 
9242 #define ALPHA_MODE_OFFSET 4
9243 
9244 static void
gamma_display_init(gamma_display * dp,png_modifier * pm,png_uint_32 id,double file_gamma,double screen_gamma,png_byte sbit,int threshold_test,int use_input_precision,int scale16,int expand16,int do_background,const png_color_16 * pointer_to_the_background_color,double background_gamma)9245 gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
9246     double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
9247     int use_input_precision, int scale16, int expand16,
9248     int do_background, const png_color_16 *pointer_to_the_background_color,
9249     double background_gamma)
9250 {
9251    /* Standard fields */
9252    standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
9253       pm->use_update_info);
9254 
9255    /* Parameter fields */
9256    dp->pm = pm;
9257    dp->file_gamma = file_gamma;
9258    dp->screen_gamma = screen_gamma;
9259    dp->background_gamma = background_gamma;
9260    dp->sbit = sbit;
9261    dp->threshold_test = threshold_test;
9262    dp->use_input_precision = use_input_precision;
9263    dp->scale16 = scale16;
9264    dp->expand16 = expand16;
9265    dp->do_background = do_background;
9266    if (do_background && pointer_to_the_background_color != 0)
9267       dp->background_color = *pointer_to_the_background_color;
9268    else
9269       memset(&dp->background_color, 0, sizeof dp->background_color);
9270 
9271    /* Local variable fields */
9272    dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
9273 }
9274 
9275 static void
gamma_info_imp(gamma_display * dp,png_structp pp,png_infop pi)9276 gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
9277 {
9278    /* Reuse the standard stuff as appropriate. */
9279    standard_info_part1(&dp->this, pp, pi);
9280 
9281    /* If requested strip 16 to 8 bits - this is handled automagically below
9282     * because the output bit depth is read from the library.  Note that there
9283     * are interactions with sBIT but, internally, libpng makes sbit at most
9284     * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
9285     */
9286    if (dp->scale16)
9287 #     ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
9288          png_set_scale_16(pp);
9289 #     else
9290          /* The following works both in 1.5.4 and earlier versions: */
9291 #        ifdef PNG_READ_16_TO_8_SUPPORTED
9292             png_set_strip_16(pp);
9293 #        else
9294             png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
9295 #        endif
9296 #     endif
9297 
9298    if (dp->expand16)
9299 #     ifdef PNG_READ_EXPAND_16_SUPPORTED
9300          png_set_expand_16(pp);
9301 #     else
9302          png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
9303 #     endif
9304 
9305    if (dp->do_background >= ALPHA_MODE_OFFSET)
9306    {
9307 #     ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9308       {
9309          /* This tests the alpha mode handling, if supported. */
9310          int mode = dp->do_background - ALPHA_MODE_OFFSET;
9311 
9312          /* The gamma value is the output gamma, and is in the standard,
9313           * non-inverted, representation.  It provides a default for the PNG file
9314           * gamma, but since the file has a gAMA chunk this does not matter.
9315           */
9316          const double sg = dp->screen_gamma;
9317 #        ifndef PNG_FLOATING_POINT_SUPPORTED
9318             png_fixed_point g = fix(sg);
9319 #        endif
9320 
9321 #        ifdef PNG_FLOATING_POINT_SUPPORTED
9322             png_set_alpha_mode(pp, mode, sg);
9323 #        else
9324             png_set_alpha_mode_fixed(pp, mode, g);
9325 #        endif
9326 
9327          /* However, for the standard Porter-Duff algorithm the output defaults
9328           * to be linear, so if the test requires non-linear output it must be
9329           * corrected here.
9330           */
9331          if (mode == PNG_ALPHA_STANDARD && sg != 1)
9332          {
9333 #           ifdef PNG_FLOATING_POINT_SUPPORTED
9334                png_set_gamma(pp, sg, dp->file_gamma);
9335 #           else
9336                png_fixed_point f = fix(dp->file_gamma);
9337                png_set_gamma_fixed(pp, g, f);
9338 #           endif
9339          }
9340       }
9341 #     else
9342          png_error(pp, "alpha mode handling not supported");
9343 #     endif
9344    }
9345 
9346    else
9347    {
9348       /* Set up gamma processing. */
9349 #     ifdef PNG_FLOATING_POINT_SUPPORTED
9350          png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
9351 #     else
9352       {
9353          png_fixed_point s = fix(dp->screen_gamma);
9354          png_fixed_point f = fix(dp->file_gamma);
9355          png_set_gamma_fixed(pp, s, f);
9356       }
9357 #     endif
9358 
9359       if (dp->do_background)
9360       {
9361 #     ifdef PNG_READ_BACKGROUND_SUPPORTED
9362          /* NOTE: this assumes the caller provided the correct background gamma!
9363           */
9364          const double bg = dp->background_gamma;
9365 #        ifndef PNG_FLOATING_POINT_SUPPORTED
9366             png_fixed_point g = fix(bg);
9367 #        endif
9368 
9369 #        ifdef PNG_FLOATING_POINT_SUPPORTED
9370             png_set_background(pp, &dp->background_color, dp->do_background,
9371                0/*need_expand*/, bg);
9372 #        else
9373             png_set_background_fixed(pp, &dp->background_color,
9374                dp->do_background, 0/*need_expand*/, g);
9375 #        endif
9376 #     else
9377          png_error(pp, "png_set_background not supported");
9378 #     endif
9379       }
9380    }
9381 
9382    {
9383       int i = dp->this.use_update_info;
9384       /* Always do one call, even if use_update_info is 0. */
9385       do
9386          png_read_update_info(pp, pi);
9387       while (--i > 0);
9388    }
9389 
9390    /* Now we may get a different cbRow: */
9391    standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
9392 }
9393 
9394 static void PNGCBAPI
gamma_info(png_structp pp,png_infop pi)9395 gamma_info(png_structp pp, png_infop pi)
9396 {
9397    gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
9398       pi);
9399 }
9400 
9401 /* Validate a single component value - the routine gets the input and output
9402  * sample values as unscaled PNG component values along with a cache of all the
9403  * information required to validate the values.
9404  */
9405 typedef struct validate_info
9406 {
9407    png_const_structp  pp;
9408    gamma_display *dp;
9409    png_byte sbit;
9410    int use_input_precision;
9411    int do_background;
9412    int scale16;
9413    unsigned int sbit_max;
9414    unsigned int isbit_shift;
9415    unsigned int outmax;
9416 
9417    double gamma_correction; /* Overall correction required. */
9418    double file_inverse;     /* Inverse of file gamma. */
9419    double screen_gamma;
9420    double screen_inverse;   /* Inverse of screen gamma. */
9421 
9422    double background_red;   /* Linear background value, red or gray. */
9423    double background_green;
9424    double background_blue;
9425 
9426    double maxabs;
9427    double maxpc;
9428    double maxcalc;
9429    double maxout;
9430    double maxout_total;     /* Total including quantization error */
9431    double outlog;
9432    int    outquant;
9433 }
9434 validate_info;
9435 
9436 static void
init_validate_info(validate_info * vi,gamma_display * dp,png_const_structp pp,int in_depth,int out_depth)9437 init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
9438     int in_depth, int out_depth)
9439 {
9440    unsigned int outmax = (1U<<out_depth)-1;
9441 
9442    vi->pp = pp;
9443    vi->dp = dp;
9444 
9445    if (dp->sbit > 0 && dp->sbit < in_depth)
9446    {
9447       vi->sbit = dp->sbit;
9448       vi->isbit_shift = in_depth - dp->sbit;
9449    }
9450 
9451    else
9452    {
9453       vi->sbit = (png_byte)in_depth;
9454       vi->isbit_shift = 0;
9455    }
9456 
9457    vi->sbit_max = (1U << vi->sbit)-1;
9458 
9459    /* This mimics the libpng threshold test, '0' is used to prevent gamma
9460     * correction in the validation test.
9461     */
9462    vi->screen_gamma = dp->screen_gamma;
9463    if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
9464       vi->screen_gamma = vi->screen_inverse = 0;
9465    else
9466       vi->screen_inverse = 1/vi->screen_gamma;
9467 
9468    vi->use_input_precision = dp->use_input_precision;
9469    vi->outmax = outmax;
9470    vi->maxabs = abserr(dp->pm, in_depth, out_depth);
9471    vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
9472    vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
9473    vi->maxout = outerr(dp->pm, in_depth, out_depth);
9474    vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
9475    vi->maxout_total = vi->maxout + vi->outquant * .5;
9476    vi->outlog = outlog(dp->pm, in_depth, out_depth);
9477 
9478    if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
9479       (dp->this.colour_type == 3 && dp->this.is_transparent) ||
9480       ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
9481        dp->this.has_tRNS))
9482    {
9483       vi->do_background = dp->do_background;
9484 
9485       if (vi->do_background != 0)
9486       {
9487          const double bg_inverse = 1/dp->background_gamma;
9488          double r, g, b;
9489 
9490          /* Caller must at least put the gray value into the red channel */
9491          r = dp->background_color.red; r /= outmax;
9492          g = dp->background_color.green; g /= outmax;
9493          b = dp->background_color.blue; b /= outmax;
9494 
9495 #     if 0
9496          /* libpng doesn't do this optimization, if we do pngvalid will fail.
9497           */
9498          if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
9499 #     endif
9500          {
9501             r = pow(r, bg_inverse);
9502             g = pow(g, bg_inverse);
9503             b = pow(b, bg_inverse);
9504          }
9505 
9506          vi->background_red = r;
9507          vi->background_green = g;
9508          vi->background_blue = b;
9509       }
9510    }
9511    else /* Do not expect any background processing */
9512       vi->do_background = 0;
9513 
9514    if (vi->do_background == 0)
9515       vi->background_red = vi->background_green = vi->background_blue = 0;
9516 
9517    vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
9518    if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
9519       vi->gamma_correction = 0;
9520 
9521    vi->file_inverse = 1/dp->file_gamma;
9522    if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
9523       vi->file_inverse = 0;
9524 
9525    vi->scale16 = dp->scale16;
9526 }
9527 
9528 /* This function handles composition of a single non-alpha component.  The
9529  * argument is the input sample value, in the range 0..1, and the alpha value.
9530  * The result is the composed, linear, input sample.  If alpha is less than zero
9531  * this is the alpha component and the function should not be called!
9532  */
9533 static double
gamma_component_compose(int do_background,double input_sample,double alpha,double background,int * compose)9534 gamma_component_compose(int do_background, double input_sample, double alpha,
9535    double background, int *compose)
9536 {
9537    switch (do_background)
9538    {
9539 #ifdef PNG_READ_BACKGROUND_SUPPORTED
9540       case PNG_BACKGROUND_GAMMA_SCREEN:
9541       case PNG_BACKGROUND_GAMMA_FILE:
9542       case PNG_BACKGROUND_GAMMA_UNIQUE:
9543          /* Standard PNG background processing. */
9544          if (alpha < 1)
9545          {
9546             if (alpha > 0)
9547             {
9548                input_sample = input_sample * alpha + background * (1-alpha);
9549                if (compose != NULL)
9550                   *compose = 1;
9551             }
9552 
9553             else
9554                input_sample = background;
9555          }
9556          break;
9557 #endif
9558 
9559 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9560       case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9561       case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9562          /* The components are premultiplied in either case and the output is
9563           * gamma encoded (to get standard Porter-Duff we expect the output
9564           * gamma to be set to 1.0!)
9565           */
9566       case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9567          /* The optimization is that the partial-alpha entries are linear
9568           * while the opaque pixels are gamma encoded, but this only affects the
9569           * output encoding.
9570           */
9571          if (alpha < 1)
9572          {
9573             if (alpha > 0)
9574             {
9575                input_sample *= alpha;
9576                if (compose != NULL)
9577                   *compose = 1;
9578             }
9579 
9580             else
9581                input_sample = 0;
9582          }
9583          break;
9584 #endif
9585 
9586       default:
9587          /* Standard cases where no compositing is done (so the component
9588           * value is already correct.)
9589           */
9590          UNUSED(alpha)
9591          UNUSED(background)
9592          UNUSED(compose)
9593          break;
9594    }
9595 
9596    return input_sample;
9597 }
9598 
9599 /* This API returns the encoded *input* component, in the range 0..1 */
9600 static double
gamma_component_validate(const char * name,const validate_info * vi,unsigned int id,unsigned int od,const double alpha,const double background)9601 gamma_component_validate(const char *name, const validate_info *vi,
9602     unsigned int id, unsigned int od,
9603     const double alpha /* <0 for the alpha channel itself */,
9604     const double background /* component background value */)
9605 {
9606    unsigned int isbit = id >> vi->isbit_shift;
9607    unsigned int sbit_max = vi->sbit_max;
9608    unsigned int outmax = vi->outmax;
9609    int do_background = vi->do_background;
9610 
9611    double i;
9612 
9613    /* First check on the 'perfect' result obtained from the digitized input
9614     * value, id, and compare this against the actual digitized result, 'od'.
9615     * 'i' is the input result in the range 0..1:
9616     */
9617    i = isbit; i /= sbit_max;
9618 
9619    /* Check for the fast route: if we don't do any background composition or if
9620     * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
9621     * just use the gamma_correction field to correct to the final output gamma.
9622     */
9623    if (alpha == 1 /* opaque pixel component */ || !do_background
9624 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9625       || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
9626 #endif
9627       || (alpha < 0 /* alpha channel */
9628 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9629       && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
9630 #endif
9631       ))
9632    {
9633       /* Then get the gamma corrected version of 'i' and compare to 'od', any
9634        * error less than .5 is insignificant - just quantization of the output
9635        * value to the nearest digital value (nevertheless the error is still
9636        * recorded - it's interesting ;-)
9637        */
9638       double encoded_sample = i;
9639       double encoded_error;
9640 
9641       /* alpha less than 0 indicates the alpha channel, which is always linear
9642        */
9643       if (alpha >= 0 && vi->gamma_correction > 0)
9644          encoded_sample = pow(encoded_sample, vi->gamma_correction);
9645       encoded_sample *= outmax;
9646 
9647       encoded_error = fabs(od-encoded_sample);
9648 
9649       if (encoded_error > vi->dp->maxerrout)
9650          vi->dp->maxerrout = encoded_error;
9651 
9652       if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
9653          return i;
9654    }
9655 
9656    /* The slow route - attempt to do linear calculations. */
9657    /* There may be an error, or background processing is required, so calculate
9658     * the actual sample values - unencoded light intensity values.  Note that in
9659     * practice these are not completely unencoded because they include a
9660     * 'viewing correction' to decrease or (normally) increase the perceptual
9661     * contrast of the image.  There's nothing we can do about this - we don't
9662     * know what it is - so assume the unencoded value is perceptually linear.
9663     */
9664    {
9665       double input_sample = i; /* In range 0..1 */
9666       double output, error, encoded_sample, encoded_error;
9667       double es_lo, es_hi;
9668       int compose = 0;           /* Set to one if composition done */
9669       int output_is_encoded;     /* Set if encoded to screen gamma */
9670       int log_max_error = 1;     /* Check maximum error values */
9671       png_const_charp pass = 0;  /* Reason test passes (or 0 for fail) */
9672 
9673       /* Convert to linear light (with the above caveat.)  The alpha channel is
9674        * already linear.
9675        */
9676       if (alpha >= 0)
9677       {
9678          int tcompose;
9679 
9680          if (vi->file_inverse > 0)
9681             input_sample = pow(input_sample, vi->file_inverse);
9682 
9683          /* Handle the compose processing: */
9684          tcompose = 0;
9685          input_sample = gamma_component_compose(do_background, input_sample,
9686             alpha, background, &tcompose);
9687 
9688          if (tcompose)
9689             compose = 1;
9690       }
9691 
9692       /* And similarly for the output value, but we need to check the background
9693        * handling to linearize it correctly.
9694        */
9695       output = od;
9696       output /= outmax;
9697 
9698       output_is_encoded = vi->screen_gamma > 0;
9699 
9700       if (alpha < 0) /* The alpha channel */
9701       {
9702 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9703          if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
9704 #endif
9705          {
9706             /* In all other cases the output alpha channel is linear already,
9707              * don't log errors here, they are much larger in linear data.
9708              */
9709             output_is_encoded = 0;
9710             log_max_error = 0;
9711          }
9712       }
9713 
9714 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9715       else /* A component */
9716       {
9717          if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
9718             alpha < 1) /* the optimized case - linear output */
9719          {
9720             if (alpha > 0) log_max_error = 0;
9721             output_is_encoded = 0;
9722          }
9723       }
9724 #endif
9725 
9726       if (output_is_encoded)
9727          output = pow(output, vi->screen_gamma);
9728 
9729       /* Calculate (or recalculate) the encoded_sample value and repeat the
9730        * check above (unnecessary if we took the fast route, but harmless.)
9731        */
9732       encoded_sample = input_sample;
9733       if (output_is_encoded)
9734          encoded_sample = pow(encoded_sample, vi->screen_inverse);
9735       encoded_sample *= outmax;
9736 
9737       encoded_error = fabs(od-encoded_sample);
9738 
9739       /* Don't log errors in the alpha channel, or the 'optimized' case,
9740        * neither are significant to the overall perception.
9741        */
9742       if (log_max_error && encoded_error > vi->dp->maxerrout)
9743          vi->dp->maxerrout = encoded_error;
9744 
9745       if (encoded_error < vi->maxout_total)
9746       {
9747          if (encoded_error < vi->outlog)
9748             return i;
9749 
9750          /* Test passed but error is bigger than the log limit, record why the
9751           * test passed:
9752           */
9753          pass = "less than maxout:\n";
9754       }
9755 
9756       /* i: the original input value in the range 0..1
9757        *
9758        * pngvalid calculations:
9759        *  input_sample: linear result; i linearized and composed, range 0..1
9760        *  encoded_sample: encoded result; input_sample scaled to output bit depth
9761        *
9762        * libpng calculations:
9763        *  output: linear result; od scaled to 0..1 and linearized
9764        *  od: encoded result from libpng
9765        */
9766 
9767       /* Now we have the numbers for real errors, both absolute values as as a
9768        * percentage of the correct value (output):
9769        */
9770       error = fabs(input_sample-output);
9771 
9772       if (log_max_error && error > vi->dp->maxerrabs)
9773          vi->dp->maxerrabs = error;
9774 
9775       /* The following is an attempt to ignore the tendency of quantization to
9776        * dominate the percentage errors for lower result values:
9777        */
9778       if (log_max_error && input_sample > .5)
9779       {
9780          double percentage_error = error/input_sample;
9781          if (percentage_error > vi->dp->maxerrpc)
9782             vi->dp->maxerrpc = percentage_error;
9783       }
9784 
9785       /* Now calculate the digitization limits for 'encoded_sample' using the
9786        * 'max' values.  Note that maxout is in the encoded space but maxpc and
9787        * maxabs are in linear light space.
9788        *
9789        * First find the maximum error in linear light space, range 0..1:
9790        */
9791       {
9792          double tmp = input_sample * vi->maxpc;
9793          if (tmp < vi->maxabs) tmp = vi->maxabs;
9794          /* If 'compose' is true the composition was done in linear space using
9795           * integer arithmetic.  This introduces an extra error of +/- 0.5 (at
9796           * least) in the integer space used.  'maxcalc' records this, taking
9797           * into account the possibility that even for 16 bit output 8 bit space
9798           * may have been used.
9799           */
9800          if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
9801 
9802          /* The 'maxout' value refers to the encoded result, to compare with
9803           * this encode input_sample adjusted by the maximum error (tmp) above.
9804           */
9805          es_lo = encoded_sample - vi->maxout;
9806 
9807          if (es_lo > 0 && input_sample-tmp > 0)
9808          {
9809             double low_value = input_sample-tmp;
9810             if (output_is_encoded)
9811                low_value = pow(low_value, vi->screen_inverse);
9812             low_value *= outmax;
9813             if (low_value < es_lo) es_lo = low_value;
9814 
9815             /* Quantize this appropriately: */
9816             es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
9817          }
9818 
9819          else
9820             es_lo = 0;
9821 
9822          es_hi = encoded_sample + vi->maxout;
9823 
9824          if (es_hi < outmax && input_sample+tmp < 1)
9825          {
9826             double high_value = input_sample+tmp;
9827             if (output_is_encoded)
9828                high_value = pow(high_value, vi->screen_inverse);
9829             high_value *= outmax;
9830             if (high_value > es_hi) es_hi = high_value;
9831 
9832             es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
9833          }
9834 
9835          else
9836             es_hi = outmax;
9837       }
9838 
9839       /* The primary test is that the final encoded value returned by the
9840        * library should be between the two limits (inclusive) that were
9841        * calculated above.
9842        */
9843       if (od >= es_lo && od <= es_hi)
9844       {
9845          /* The value passes, but we may need to log the information anyway. */
9846          if (encoded_error < vi->outlog)
9847             return i;
9848 
9849          if (pass == 0)
9850             pass = "within digitization limits:\n";
9851       }
9852 
9853       {
9854          /* There has been an error in processing, or we need to log this
9855           * value.
9856           */
9857          double is_lo, is_hi;
9858 
9859          /* pass is set at this point if either of the tests above would have
9860           * passed.  Don't do these additional tests here - just log the
9861           * original [es_lo..es_hi] values.
9862           */
9863          if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
9864          {
9865             /* Ok, something is wrong - this actually happens in current libpng
9866              * 16-to-8 processing.  Assume that the input value (id, adjusted
9867              * for sbit) can be anywhere between value-.5 and value+.5 - quite a
9868              * large range if sbit is low.
9869              *
9870              * NOTE: at present because the libpng gamma table stuff has been
9871              * changed to use a rounding algorithm to correct errors in 8-bit
9872              * calculations the precise sbit calculation (a shift) has been
9873              * lost.  This can result in up to a +/-1 error in the presence of
9874              * an sbit less than the bit depth.
9875              */
9876 #           if PNG_LIBPNG_VER < 10700
9877 #              define SBIT_ERROR .5
9878 #           else
9879 #              define SBIT_ERROR 1.
9880 #           endif
9881             double tmp = (isbit - SBIT_ERROR)/sbit_max;
9882 
9883             if (tmp <= 0)
9884                tmp = 0;
9885 
9886             else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9887                tmp = pow(tmp, vi->file_inverse);
9888 
9889             tmp = gamma_component_compose(do_background, tmp, alpha, background,
9890                NULL);
9891 
9892             if (output_is_encoded && tmp > 0 && tmp < 1)
9893                tmp = pow(tmp, vi->screen_inverse);
9894 
9895             is_lo = ceil(outmax * tmp - vi->maxout_total);
9896 
9897             if (is_lo < 0)
9898                is_lo = 0;
9899 
9900             tmp = (isbit + SBIT_ERROR)/sbit_max;
9901 
9902             if (tmp >= 1)
9903                tmp = 1;
9904 
9905             else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9906                tmp = pow(tmp, vi->file_inverse);
9907 
9908             tmp = gamma_component_compose(do_background, tmp, alpha, background,
9909                NULL);
9910 
9911             if (output_is_encoded && tmp > 0 && tmp < 1)
9912                tmp = pow(tmp, vi->screen_inverse);
9913 
9914             is_hi = floor(outmax * tmp + vi->maxout_total);
9915 
9916             if (is_hi > outmax)
9917                is_hi = outmax;
9918 
9919             if (!(od < is_lo || od > is_hi))
9920             {
9921                if (encoded_error < vi->outlog)
9922                   return i;
9923 
9924                pass = "within input precision limits:\n";
9925             }
9926 
9927             /* One last chance.  If this is an alpha channel and the 16to8
9928              * option has been used and 'inaccurate' scaling is used then the
9929              * bit reduction is obtained by simply using the top 8 bits of the
9930              * value.
9931              *
9932              * This is only done for older libpng versions when the 'inaccurate'
9933              * (chop) method of scaling was used.
9934              */
9935 #           ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
9936 #              if PNG_LIBPNG_VER < 10504
9937                   /* This may be required for other components in the future,
9938                    * but at present the presence of gamma correction effectively
9939                    * prevents the errors in the component scaling (I don't quite
9940                    * understand why, but since it's better this way I care not
9941                    * to ask, JB 20110419.)
9942                    */
9943                   if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
9944                      vi->sbit + vi->isbit_shift == 16)
9945                   {
9946                      tmp = ((id >> 8) - .5)/255;
9947 
9948                      if (tmp > 0)
9949                      {
9950                         is_lo = ceil(outmax * tmp - vi->maxout_total);
9951                         if (is_lo < 0) is_lo = 0;
9952                      }
9953 
9954                      else
9955                         is_lo = 0;
9956 
9957                      tmp = ((id >> 8) + .5)/255;
9958 
9959                      if (tmp < 1)
9960                      {
9961                         is_hi = floor(outmax * tmp + vi->maxout_total);
9962                         if (is_hi > outmax) is_hi = outmax;
9963                      }
9964 
9965                      else
9966                         is_hi = outmax;
9967 
9968                      if (!(od < is_lo || od > is_hi))
9969                      {
9970                         if (encoded_error < vi->outlog)
9971                            return i;
9972 
9973                         pass = "within 8 bit limits:\n";
9974                      }
9975                   }
9976 #              endif
9977 #           endif
9978          }
9979          else /* !use_input_precision */
9980             is_lo = es_lo, is_hi = es_hi;
9981 
9982          /* Attempt to output a meaningful error/warning message: the message
9983           * output depends on the background/composite operation being performed
9984           * because this changes what parameters were actually used above.
9985           */
9986          {
9987             size_t pos = 0;
9988             /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
9989              * places.  Just use outmax to work out which.
9990              */
9991             int precision = (outmax >= 1000 ? 6 : 3);
9992             int use_input=1, use_background=0, do_compose=0;
9993             char msg[256];
9994 
9995             if (pass != 0)
9996                pos = safecat(msg, sizeof msg, pos, "\n\t");
9997 
9998             /* Set up the various flags, the output_is_encoded flag above
9999              * is also used below.  do_compose is just a double check.
10000              */
10001             switch (do_background)
10002             {
10003 #           ifdef PNG_READ_BACKGROUND_SUPPORTED
10004                case PNG_BACKGROUND_GAMMA_SCREEN:
10005                case PNG_BACKGROUND_GAMMA_FILE:
10006                case PNG_BACKGROUND_GAMMA_UNIQUE:
10007                   use_background = (alpha >= 0 && alpha < 1);
10008 #           endif
10009 #           ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10010                /* FALLTHROUGH */
10011                case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10012                case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10013                case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10014 #           endif /* ALPHA_MODE_SUPPORTED */
10015 #           if (defined PNG_READ_BACKGROUND_SUPPORTED) ||\
10016                (defined PNG_READ_ALPHA_MODE_SUPPORTED)
10017                do_compose = (alpha > 0 && alpha < 1);
10018                use_input = (alpha != 0);
10019                break;
10020 #           endif
10021 
10022             default:
10023                break;
10024             }
10025 
10026             /* Check the 'compose' flag */
10027             if (compose != do_compose)
10028                png_error(vi->pp, "internal error (compose)");
10029 
10030             /* 'name' is the component name */
10031             pos = safecat(msg, sizeof msg, pos, name);
10032             pos = safecat(msg, sizeof msg, pos, "(");
10033             pos = safecatn(msg, sizeof msg, pos, id);
10034             if (use_input || pass != 0/*logging*/)
10035             {
10036                if (isbit != id)
10037                {
10038                   /* sBIT has reduced the precision of the input: */
10039                   pos = safecat(msg, sizeof msg, pos, ", sbit(");
10040                   pos = safecatn(msg, sizeof msg, pos, vi->sbit);
10041                   pos = safecat(msg, sizeof msg, pos, "): ");
10042                   pos = safecatn(msg, sizeof msg, pos, isbit);
10043                }
10044                pos = safecat(msg, sizeof msg, pos, "/");
10045                /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
10046                pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
10047             }
10048             pos = safecat(msg, sizeof msg, pos, ")");
10049 
10050             /* A component may have been multiplied (in linear space) by the
10051              * alpha value, 'compose' says whether this is relevant.
10052              */
10053             if (compose || pass != 0)
10054             {
10055                /* If any form of composition is being done report our
10056                 * calculated linear value here (the code above doesn't record
10057                 * the input value before composition is performed, so what
10058                 * gets reported is the value after composition.)
10059                 */
10060                if (use_input || pass != 0)
10061                {
10062                   if (vi->file_inverse > 0)
10063                   {
10064                      pos = safecat(msg, sizeof msg, pos, "^");
10065                      pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
10066                   }
10067 
10068                   else
10069                      pos = safecat(msg, sizeof msg, pos, "[linear]");
10070 
10071                   pos = safecat(msg, sizeof msg, pos, "*(alpha)");
10072                   pos = safecatd(msg, sizeof msg, pos, alpha, precision);
10073                }
10074 
10075                /* Now record the *linear* background value if it was used
10076                 * (this function is not passed the original, non-linear,
10077                 * value but it is contained in the test name.)
10078                 */
10079                if (use_background)
10080                {
10081                   pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
10082                   pos = safecat(msg, sizeof msg, pos, "(background)");
10083                   pos = safecatd(msg, sizeof msg, pos, background, precision);
10084                   pos = safecat(msg, sizeof msg, pos, "*");
10085                   pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
10086                }
10087             }
10088 
10089             /* Report the calculated value (input_sample) and the linearized
10090              * libpng value (output) unless this is just a component gamma
10091              * correction.
10092              */
10093             if (compose || alpha < 0 || pass != 0)
10094             {
10095                pos = safecat(msg, sizeof msg, pos,
10096                   pass != 0 ? " =\n\t" : " = ");
10097                pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
10098                pos = safecat(msg, sizeof msg, pos, " (libpng: ");
10099                pos = safecatd(msg, sizeof msg, pos, output, precision);
10100                pos = safecat(msg, sizeof msg, pos, ")");
10101 
10102                /* Finally report the output gamma encoding, if any. */
10103                if (output_is_encoded)
10104                {
10105                   pos = safecat(msg, sizeof msg, pos, " ^");
10106                   pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
10107                   pos = safecat(msg, sizeof msg, pos, "(to screen) =");
10108                }
10109 
10110                else
10111                   pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
10112             }
10113 
10114             if ((!compose && alpha >= 0) || pass != 0)
10115             {
10116                if (pass != 0) /* logging */
10117                   pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
10118 
10119                /* This is the non-composition case, the internal linear
10120                 * values are irrelevant (though the log below will reveal
10121                 * them.)  Output a much shorter warning/error message and report
10122                 * the overall gamma correction.
10123                 */
10124                if (vi->gamma_correction > 0)
10125                {
10126                   pos = safecat(msg, sizeof msg, pos, " ^");
10127                   pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
10128                   pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
10129                }
10130 
10131                else
10132                   pos = safecat(msg, sizeof msg, pos,
10133                      " [no gamma correction] =");
10134 
10135                if (pass != 0)
10136                   pos = safecat(msg, sizeof msg, pos, "]");
10137             }
10138 
10139             /* This is our calculated encoded_sample which should (but does
10140              * not) match od:
10141              */
10142             pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
10143             pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
10144             pos = safecat(msg, sizeof msg, pos, " < ");
10145             pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
10146             pos = safecat(msg, sizeof msg, pos, " (libpng: ");
10147             pos = safecatn(msg, sizeof msg, pos, od);
10148             pos = safecat(msg, sizeof msg, pos, ")");
10149             pos = safecat(msg, sizeof msg, pos, "/");
10150             pos = safecatn(msg, sizeof msg, pos, outmax);
10151             pos = safecat(msg, sizeof msg, pos, " < ");
10152             pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
10153 
10154             if (pass == 0) /* The error condition */
10155             {
10156 #              ifdef PNG_WARNINGS_SUPPORTED
10157                   png_warning(vi->pp, msg);
10158 #              else
10159                   store_warning(vi->pp, msg);
10160 #              endif
10161             }
10162 
10163             else /* logging this value */
10164                store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
10165          }
10166       }
10167    }
10168 
10169    return i;
10170 }
10171 
10172 static void
gamma_image_validate(gamma_display * dp,png_const_structp pp,png_infop pi)10173 gamma_image_validate(gamma_display *dp, png_const_structp pp,
10174    png_infop pi)
10175 {
10176    /* Get some constants derived from the input and output file formats: */
10177    const png_store* const ps = dp->this.ps;
10178    png_byte in_ct = dp->this.colour_type;
10179    png_byte in_bd = dp->this.bit_depth;
10180    png_uint_32 w = dp->this.w;
10181    png_uint_32 h = dp->this.h;
10182    const size_t cbRow = dp->this.cbRow;
10183    png_byte out_ct = png_get_color_type(pp, pi);
10184    png_byte out_bd = png_get_bit_depth(pp, pi);
10185 
10186    /* There are three sources of error, firstly the quantization in the
10187     * file encoding, determined by sbit and/or the file depth, secondly
10188     * the output (screen) gamma and thirdly the output file encoding.
10189     *
10190     * Since this API receives the screen and file gamma in double
10191     * precision it is possible to calculate an exact answer given an input
10192     * pixel value.  Therefore we assume that the *input* value is exact -
10193     * sample/maxsample - calculate the corresponding gamma corrected
10194     * output to the limits of double precision arithmetic and compare with
10195     * what libpng returns.
10196     *
10197     * Since the library must quantize the output to 8 or 16 bits there is
10198     * a fundamental limit on the accuracy of the output of +/-.5 - this
10199     * quantization limit is included in addition to the other limits
10200     * specified by the parameters to the API.  (Effectively, add .5
10201     * everywhere.)
10202     *
10203     * The behavior of the 'sbit' parameter is defined by section 12.5
10204     * (sample depth scaling) of the PNG spec.  That section forces the
10205     * decoder to assume that the PNG values have been scaled if sBIT is
10206     * present:
10207     *
10208     *     png-sample = floor( input-sample * (max-out/max-in) + .5);
10209     *
10210     * This means that only a subset of the possible PNG values should
10211     * appear in the input. However, the spec allows the encoder to use a
10212     * variety of approximations to the above and doesn't require any
10213     * restriction of the values produced.
10214     *
10215     * Nevertheless the spec requires that the upper 'sBIT' bits of the
10216     * value stored in a PNG file be the original sample bits.
10217     * Consequently the code below simply scales the top sbit bits by
10218     * (1<<sbit)-1 to obtain an original sample value.
10219     *
10220     * Because there is limited precision in the input it is arguable that
10221     * an acceptable result is any valid result from input-.5 to input+.5.
10222     * The basic tests below do not do this, however if 'use_input_precision'
10223     * is set a subsequent test is performed above.
10224     */
10225    unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
10226    int processing;
10227    png_uint_32 y;
10228    const store_palette_entry *in_palette = dp->this.palette;
10229    int in_is_transparent = dp->this.is_transparent;
10230    int process_tRNS;
10231    int out_npalette = -1;
10232    int out_is_transparent = 0; /* Just refers to the palette case */
10233    store_palette out_palette;
10234    validate_info vi;
10235 
10236    /* Check for row overwrite errors */
10237    store_image_check(dp->this.ps, pp, 0);
10238 
10239    /* Supply the input and output sample depths here - 8 for an indexed image,
10240     * otherwise the bit depth.
10241     */
10242    init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
10243 
10244    processing = (vi.gamma_correction > 0 && !dp->threshold_test)
10245       || in_bd != out_bd || in_ct != out_ct || vi.do_background;
10246    process_tRNS = dp->this.has_tRNS && vi.do_background;
10247 
10248    /* TODO: FIX THIS: MAJOR BUG!  If the transformations all happen inside
10249     * the palette there is no way of finding out, because libpng fails to
10250     * update the palette on png_read_update_info.  Indeed, libpng doesn't
10251     * even do the required work until much later, when it doesn't have any
10252     * info pointer.  Oops.  For the moment 'processing' is turned off if
10253     * out_ct is palette.
10254     */
10255    if (in_ct == 3 && out_ct == 3)
10256       processing = 0;
10257 
10258    if (processing && out_ct == 3)
10259       out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
10260 
10261    for (y=0; y<h; ++y)
10262    {
10263       png_const_bytep pRow = store_image_row(ps, pp, 0, y);
10264       png_byte std[STANDARD_ROWMAX];
10265 
10266       transform_row(pp, std, in_ct, in_bd, y);
10267 
10268       if (processing)
10269       {
10270          unsigned int x;
10271 
10272          for (x=0; x<w; ++x)
10273          {
10274             double alpha = 1; /* serves as a flag value */
10275 
10276             /* Record the palette index for index images. */
10277             unsigned int in_index =
10278                in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
10279             unsigned int out_index =
10280                out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
10281 
10282             /* Handle input alpha - png_set_background will cause the output
10283              * alpha to disappear so there is nothing to check.
10284              */
10285             if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
10286                 (in_ct == 3 && in_is_transparent))
10287             {
10288                unsigned int input_alpha = in_ct == 3 ?
10289                   dp->this.palette[in_index].alpha :
10290                   sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
10291 
10292                unsigned int output_alpha = 65536 /* as a flag value */;
10293 
10294                if (out_ct == 3)
10295                {
10296                   if (out_is_transparent)
10297                      output_alpha = out_palette[out_index].alpha;
10298                }
10299 
10300                else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
10301                   output_alpha = sample(pRow, out_ct, out_bd, x,
10302                      samples_per_pixel, 0, 0);
10303 
10304                if (output_alpha != 65536)
10305                   alpha = gamma_component_validate("alpha", &vi, input_alpha,
10306                      output_alpha, -1/*alpha*/, 0/*background*/);
10307 
10308                else /* no alpha in output */
10309                {
10310                   /* This is a copy of the calculation of 'i' above in order to
10311                    * have the alpha value to use in the background calculation.
10312                    */
10313                   alpha = input_alpha >> vi.isbit_shift;
10314                   alpha /= vi.sbit_max;
10315                }
10316             }
10317 
10318             else if (process_tRNS)
10319             {
10320                /* alpha needs to be set appropriately for this pixel, it is
10321                 * currently 1 and needs to be 0 for an input pixel which matches
10322                 * the values in tRNS.
10323                 */
10324                switch (in_ct)
10325                {
10326                   case 0: /* gray */
10327                      if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
10328                            dp->this.transparent.red)
10329                         alpha = 0;
10330                      break;
10331 
10332                   case 2: /* RGB */
10333                      if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
10334                            dp->this.transparent.red &&
10335                          sample(std, in_ct, in_bd, x, 1, 0, 0) ==
10336                            dp->this.transparent.green &&
10337                          sample(std, in_ct, in_bd, x, 2, 0, 0) ==
10338                            dp->this.transparent.blue)
10339                         alpha = 0;
10340                      break;
10341 
10342                   default:
10343                      break;
10344                }
10345             }
10346 
10347             /* Handle grayscale or RGB components. */
10348             if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
10349                (void)gamma_component_validate("gray", &vi,
10350                   sample(std, in_ct, in_bd, x, 0, 0, 0),
10351                   sample(pRow, out_ct, out_bd, x, 0, 0, 0),
10352                   alpha/*component*/, vi.background_red);
10353             else /* RGB or palette */
10354             {
10355                (void)gamma_component_validate("red", &vi,
10356                   in_ct == 3 ? in_palette[in_index].red :
10357                      sample(std, in_ct, in_bd, x, 0, 0, 0),
10358                   out_ct == 3 ? out_palette[out_index].red :
10359                      sample(pRow, out_ct, out_bd, x, 0, 0, 0),
10360                   alpha/*component*/, vi.background_red);
10361 
10362                (void)gamma_component_validate("green", &vi,
10363                   in_ct == 3 ? in_palette[in_index].green :
10364                      sample(std, in_ct, in_bd, x, 1, 0, 0),
10365                   out_ct == 3 ? out_palette[out_index].green :
10366                      sample(pRow, out_ct, out_bd, x, 1, 0, 0),
10367                   alpha/*component*/, vi.background_green);
10368 
10369                (void)gamma_component_validate("blue", &vi,
10370                   in_ct == 3 ? in_palette[in_index].blue :
10371                      sample(std, in_ct, in_bd, x, 2, 0, 0),
10372                   out_ct == 3 ? out_palette[out_index].blue :
10373                      sample(pRow, out_ct, out_bd, x, 2, 0, 0),
10374                   alpha/*component*/, vi.background_blue);
10375             }
10376          }
10377       }
10378 
10379       else if (memcmp(std, pRow, cbRow) != 0)
10380       {
10381          char msg[64];
10382 
10383          /* No transform is expected on the threshold tests. */
10384          sprintf(msg, "gamma: below threshold row %lu changed",
10385             (unsigned long)y);
10386 
10387          png_error(pp, msg);
10388       }
10389    } /* row (y) loop */
10390 
10391    dp->this.ps->validated = 1;
10392 }
10393 
10394 static void PNGCBAPI
gamma_end(png_structp ppIn,png_infop pi)10395 gamma_end(png_structp ppIn, png_infop pi)
10396 {
10397    png_const_structp pp = ppIn;
10398    gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
10399 
10400    if (!dp->this.speed)
10401       gamma_image_validate(dp, pp, pi);
10402    else
10403       dp->this.ps->validated = 1;
10404 }
10405 
10406 /* A single test run checking a gamma transformation.
10407  *
10408  * maxabs: maximum absolute error as a fraction
10409  * maxout: maximum output error in the output units
10410  * maxpc:  maximum percentage error (as a percentage)
10411  */
10412 static void
gamma_test(png_modifier * pmIn,png_byte colour_typeIn,png_byte bit_depthIn,int palette_numberIn,int interlace_typeIn,const double file_gammaIn,const double screen_gammaIn,png_byte sbitIn,int threshold_testIn,const char * name,int use_input_precisionIn,int scale16In,int expand16In,int do_backgroundIn,const png_color_16 * bkgd_colorIn,double bkgd_gammaIn)10413 gamma_test(png_modifier *pmIn, png_byte colour_typeIn,
10414     png_byte bit_depthIn, int palette_numberIn,
10415     int interlace_typeIn,
10416     const double file_gammaIn, const double screen_gammaIn,
10417     png_byte sbitIn, int threshold_testIn,
10418     const char *name,
10419     int use_input_precisionIn, int scale16In,
10420     int expand16In, int do_backgroundIn,
10421     const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
10422 {
10423    gamma_display d;
10424    context(&pmIn->this, fault);
10425 
10426    gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
10427       palette_numberIn, interlace_typeIn, 0, 0, 0),
10428       file_gammaIn, screen_gammaIn, sbitIn,
10429       threshold_testIn, use_input_precisionIn, scale16In,
10430       expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
10431 
10432    Try
10433    {
10434       png_structp pp;
10435       png_infop pi;
10436       gama_modification gama_mod;
10437       srgb_modification srgb_mod;
10438       sbit_modification sbit_mod;
10439 
10440       /* For the moment don't use the png_modifier support here. */
10441       d.pm->encoding_counter = 0;
10442       modifier_set_encoding(d.pm); /* Just resets everything */
10443       d.pm->current_gamma = d.file_gamma;
10444 
10445       /* Make an appropriate modifier to set the PNG file gamma to the
10446        * given gamma value and the sBIT chunk to the given precision.
10447        */
10448       d.pm->modifications = NULL;
10449       gama_modification_init(&gama_mod, d.pm, d.file_gamma);
10450       srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
10451       if (d.sbit > 0)
10452          sbit_modification_init(&sbit_mod, d.pm, d.sbit);
10453 
10454       modification_reset(d.pm->modifications);
10455 
10456       /* Get a png_struct for reading the image. */
10457       pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
10458       standard_palette_init(&d.this);
10459 
10460       /* Introduce the correct read function. */
10461       if (d.pm->this.progressive)
10462       {
10463          /* Share the row function with the standard implementation. */
10464          png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
10465             gamma_end);
10466 
10467          /* Now feed data into the reader until we reach the end: */
10468          modifier_progressive_read(d.pm, pp, pi);
10469       }
10470       else
10471       {
10472          /* modifier_read expects a png_modifier* */
10473          png_set_read_fn(pp, d.pm, modifier_read);
10474 
10475          /* Check the header values: */
10476          png_read_info(pp, pi);
10477 
10478          /* Process the 'info' requirements. Only one image is generated */
10479          gamma_info_imp(&d, pp, pi);
10480 
10481          sequential_row(&d.this, pp, pi, -1, 0);
10482 
10483          if (!d.this.speed)
10484             gamma_image_validate(&d, pp, pi);
10485          else
10486             d.this.ps->validated = 1;
10487       }
10488 
10489       modifier_reset(d.pm);
10490 
10491       if (d.pm->log && !d.threshold_test && !d.this.speed)
10492          fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
10493             d.this.bit_depth, colour_types[d.this.colour_type], name,
10494             d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
10495 
10496       /* Log the summary values too. */
10497       if (d.this.colour_type == 0 || d.this.colour_type == 4)
10498       {
10499          switch (d.this.bit_depth)
10500          {
10501          case 1:
10502             break;
10503 
10504          case 2:
10505             if (d.maxerrout > d.pm->error_gray_2)
10506                d.pm->error_gray_2 = d.maxerrout;
10507 
10508             break;
10509 
10510          case 4:
10511             if (d.maxerrout > d.pm->error_gray_4)
10512                d.pm->error_gray_4 = d.maxerrout;
10513 
10514             break;
10515 
10516          case 8:
10517             if (d.maxerrout > d.pm->error_gray_8)
10518                d.pm->error_gray_8 = d.maxerrout;
10519 
10520             break;
10521 
10522          case 16:
10523             if (d.maxerrout > d.pm->error_gray_16)
10524                d.pm->error_gray_16 = d.maxerrout;
10525 
10526             break;
10527 
10528          default:
10529             png_error(pp, "bad bit depth (internal: 1)");
10530          }
10531       }
10532 
10533       else if (d.this.colour_type == 2 || d.this.colour_type == 6)
10534       {
10535          switch (d.this.bit_depth)
10536          {
10537          case 8:
10538 
10539             if (d.maxerrout > d.pm->error_color_8)
10540                d.pm->error_color_8 = d.maxerrout;
10541 
10542             break;
10543 
10544          case 16:
10545 
10546             if (d.maxerrout > d.pm->error_color_16)
10547                d.pm->error_color_16 = d.maxerrout;
10548 
10549             break;
10550 
10551          default:
10552             png_error(pp, "bad bit depth (internal: 2)");
10553          }
10554       }
10555 
10556       else if (d.this.colour_type == 3)
10557       {
10558          if (d.maxerrout > d.pm->error_indexed)
10559             d.pm->error_indexed = d.maxerrout;
10560       }
10561    }
10562 
10563    Catch(fault)
10564       modifier_reset(voidcast(png_modifier*,(void*)fault));
10565 }
10566 
gamma_threshold_test(png_modifier * pm,png_byte colour_type,png_byte bit_depth,int interlace_type,double file_gamma,double screen_gamma)10567 static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
10568     png_byte bit_depth, int interlace_type, double file_gamma,
10569     double screen_gamma)
10570 {
10571    size_t pos = 0;
10572    char name[64];
10573    pos = safecat(name, sizeof name, pos, "threshold ");
10574    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10575    pos = safecat(name, sizeof name, pos, "/");
10576    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10577 
10578    (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
10579       file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
10580       0 /*no input precision*/,
10581       0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
10582       0 /*no background gamma*/);
10583 }
10584 
10585 static void
perform_gamma_threshold_tests(png_modifier * pm)10586 perform_gamma_threshold_tests(png_modifier *pm)
10587 {
10588    png_byte colour_type = 0;
10589    png_byte bit_depth = 0;
10590    unsigned int palette_number = 0;
10591 
10592    /* Don't test more than one instance of each palette - it's pointless, in
10593     * fact this test is somewhat excessive since libpng doesn't make this
10594     * decision based on colour type or bit depth!
10595     *
10596     * CHANGED: now test two palettes and, as a side effect, images with and
10597     * without tRNS.
10598     */
10599    while (next_format(&colour_type, &bit_depth, &palette_number,
10600                       pm->test_lbg_gamma_threshold, pm->test_tRNS))
10601       if (palette_number < 2)
10602    {
10603       double test_gamma = 1.0;
10604       while (test_gamma >= .4)
10605       {
10606          /* There's little point testing the interlacing vs non-interlacing,
10607           * but this can be set from the command line.
10608           */
10609          gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10610             test_gamma, 1/test_gamma);
10611          test_gamma *= .95;
10612       }
10613 
10614       /* And a special test for sRGB */
10615       gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10616           .45455, 2.2);
10617 
10618       if (fail(pm))
10619          return;
10620    }
10621 }
10622 
gamma_transform_test(png_modifier * pm,png_byte colour_type,png_byte bit_depth,int palette_number,int interlace_type,const double file_gamma,const double screen_gamma,png_byte sbit,int use_input_precision,int scale16)10623 static void gamma_transform_test(png_modifier *pm,
10624    png_byte colour_type, png_byte bit_depth,
10625    int palette_number,
10626    int interlace_type, const double file_gamma,
10627    const double screen_gamma, png_byte sbit,
10628    int use_input_precision, int scale16)
10629 {
10630    size_t pos = 0;
10631    char name[64];
10632 
10633    if (sbit != bit_depth && sbit != 0)
10634    {
10635       pos = safecat(name, sizeof name, pos, "sbit(");
10636       pos = safecatn(name, sizeof name, pos, sbit);
10637       pos = safecat(name, sizeof name, pos, ") ");
10638    }
10639 
10640    else
10641       pos = safecat(name, sizeof name, pos, "gamma ");
10642 
10643    if (scale16)
10644       pos = safecat(name, sizeof name, pos, "16to8 ");
10645 
10646    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10647    pos = safecat(name, sizeof name, pos, "->");
10648    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10649 
10650    gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10651       file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
10652       scale16, pm->test_gamma_expand16, 0 , 0, 0);
10653 }
10654 
perform_gamma_transform_tests(png_modifier * pm)10655 static void perform_gamma_transform_tests(png_modifier *pm)
10656 {
10657    png_byte colour_type = 0;
10658    png_byte bit_depth = 0;
10659    unsigned int palette_number = 0;
10660 
10661    while (next_format(&colour_type, &bit_depth, &palette_number,
10662                       pm->test_lbg_gamma_transform, pm->test_tRNS))
10663    {
10664       unsigned int i, j;
10665 
10666       for (i=0; i<pm->ngamma_tests; ++i)
10667       {
10668          for (j=0; j<pm->ngamma_tests; ++j)
10669          {
10670             if (i != j)
10671             {
10672                gamma_transform_test(pm, colour_type, bit_depth, palette_number,
10673                   pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10674                   0/*sBIT*/, pm->use_input_precision, 0/*do not scale16*/);
10675 
10676                if (fail(pm))
10677                   return;
10678             }
10679          }
10680       }
10681    }
10682 }
10683 
perform_gamma_sbit_tests(png_modifier * pm)10684 static void perform_gamma_sbit_tests(png_modifier *pm)
10685 {
10686    png_byte sbit;
10687 
10688    /* The only interesting cases are colour and grayscale, alpha is ignored here
10689     * for overall speed.  Only bit depths where sbit is less than the bit depth
10690     * are tested.
10691     */
10692    for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
10693    {
10694       png_byte colour_type = 0, bit_depth = 0;
10695       unsigned int npalette = 0;
10696 
10697       while (next_format(&colour_type, &bit_depth, &npalette,
10698                          pm->test_lbg_gamma_sbit, pm->test_tRNS))
10699          if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
10700             ((colour_type == 3 && sbit < 8) ||
10701             (colour_type != 3 && sbit < bit_depth)))
10702       {
10703          unsigned int i;
10704 
10705          for (i=0; i<pm->ngamma_tests; ++i)
10706          {
10707             unsigned int j;
10708 
10709             for (j=0; j<pm->ngamma_tests; ++j)
10710             {
10711                if (i != j)
10712                {
10713                   gamma_transform_test(pm, colour_type, bit_depth, npalette,
10714                      pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10715                      sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
10716 
10717                   if (fail(pm))
10718                      return;
10719                }
10720             }
10721          }
10722       }
10723    }
10724 }
10725 
10726 /* Note that this requires a 16 bit source image but produces 8 bit output, so
10727  * we only need the 16bit write support, but the 16 bit images are only
10728  * generated if DO_16BIT is defined.
10729  */
10730 #ifdef DO_16BIT
perform_gamma_scale16_tests(png_modifier * pm)10731 static void perform_gamma_scale16_tests(png_modifier *pm)
10732 {
10733 #  ifndef PNG_MAX_GAMMA_8
10734 #     define PNG_MAX_GAMMA_8 11
10735 #  endif
10736 #  if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
10737 #     define SBIT_16_TO_8 PNG_MAX_GAMMA_8
10738 #  else
10739 #     define SBIT_16_TO_8 16
10740 #  endif
10741    /* Include the alpha cases here. Note that sbit matches the internal value
10742     * used by the library - otherwise we will get spurious errors from the
10743     * internal sbit style approximation.
10744     *
10745     * The threshold test is here because otherwise the 16 to 8 conversion will
10746     * proceed *without* gamma correction, and the tests above will fail (but not
10747     * by much) - this could be fixed, it only appears with the -g option.
10748     */
10749    unsigned int i, j;
10750    for (i=0; i<pm->ngamma_tests; ++i)
10751    {
10752       for (j=0; j<pm->ngamma_tests; ++j)
10753       {
10754          if (i != j &&
10755              fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
10756          {
10757             gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
10758                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10759                pm->use_input_precision_16to8, 1 /*scale16*/);
10760 
10761             if (fail(pm))
10762                return;
10763 
10764             gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
10765                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10766                pm->use_input_precision_16to8, 1 /*scale16*/);
10767 
10768             if (fail(pm))
10769                return;
10770 
10771             gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
10772                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10773                pm->use_input_precision_16to8, 1 /*scale16*/);
10774 
10775             if (fail(pm))
10776                return;
10777 
10778             gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
10779                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10780                pm->use_input_precision_16to8, 1 /*scale16*/);
10781 
10782             if (fail(pm))
10783                return;
10784          }
10785       }
10786    }
10787 }
10788 #endif /* 16 to 8 bit conversion */
10789 
10790 #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
10791    defined(PNG_READ_ALPHA_MODE_SUPPORTED)
gamma_composition_test(png_modifier * pm,png_byte colour_type,png_byte bit_depth,int palette_number,int interlace_type,const double file_gamma,const double screen_gamma,int use_input_precision,int do_background,int expand_16)10792 static void gamma_composition_test(png_modifier *pm,
10793    png_byte colour_type, png_byte bit_depth,
10794    int palette_number,
10795    int interlace_type, const double file_gamma,
10796    const double screen_gamma,
10797    int use_input_precision, int do_background,
10798    int expand_16)
10799 {
10800    size_t pos = 0;
10801    png_const_charp base;
10802    double bg;
10803    char name[128];
10804    png_color_16 background;
10805 
10806    /* Make up a name and get an appropriate background gamma value. */
10807    switch (do_background)
10808    {
10809       default:
10810          base = "";
10811          bg = 4; /* should not be used */
10812          break;
10813       case PNG_BACKGROUND_GAMMA_SCREEN:
10814          base = " bckg(Screen):";
10815          bg = 1/screen_gamma;
10816          break;
10817       case PNG_BACKGROUND_GAMMA_FILE:
10818          base = " bckg(File):";
10819          bg = file_gamma;
10820          break;
10821       case PNG_BACKGROUND_GAMMA_UNIQUE:
10822          base = " bckg(Unique):";
10823          /* This tests the handling of a unique value, the math is such that the
10824           * value tends to be <1, but is neither screen nor file (even if they
10825           * match!)
10826           */
10827          bg = (file_gamma + screen_gamma) / 3;
10828          break;
10829 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10830       case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
10831          base = " alpha(PNG)";
10832          bg = 4; /* should not be used */
10833          break;
10834       case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10835          base = " alpha(Porter-Duff)";
10836          bg = 4; /* should not be used */
10837          break;
10838       case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10839          base = " alpha(Optimized)";
10840          bg = 4; /* should not be used */
10841          break;
10842       case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10843          base = " alpha(Broken)";
10844          bg = 4; /* should not be used */
10845          break;
10846 #endif
10847    }
10848 
10849    /* Use random background values - the background is always presented in the
10850     * output space (8 or 16 bit components).
10851     */
10852    if (expand_16 || bit_depth == 16)
10853    {
10854       png_uint_32 r = random_32();
10855 
10856       background.red = (png_uint_16)r;
10857       background.green = (png_uint_16)(r >> 16);
10858       r = random_32();
10859       background.blue = (png_uint_16)r;
10860       background.gray = (png_uint_16)(r >> 16);
10861 
10862       /* In earlier libpng versions, those where DIGITIZE is set, any background
10863        * gamma correction in the expand16 case was done using 8-bit gamma
10864        * correction tables, resulting in larger errors.  To cope with those
10865        * cases use a 16-bit background value which will handle this gamma
10866        * correction.
10867        */
10868 #     if DIGITIZE
10869          if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
10870                            do_background == PNG_BACKGROUND_GAMMA_FILE) &&
10871             fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
10872          {
10873             /* The background values will be looked up in an 8-bit table to do
10874              * the gamma correction, so only select values which are an exact
10875              * match for the 8-bit table entries:
10876              */
10877             background.red = (png_uint_16)((background.red >> 8) * 257);
10878             background.green = (png_uint_16)((background.green >> 8) * 257);
10879             background.blue = (png_uint_16)((background.blue >> 8) * 257);
10880             background.gray = (png_uint_16)((background.gray >> 8) * 257);
10881          }
10882 #     endif
10883    }
10884 
10885    else /* 8 bit colors */
10886    {
10887       png_uint_32 r = random_32();
10888 
10889       background.red = (png_byte)r;
10890       background.green = (png_byte)(r >> 8);
10891       background.blue = (png_byte)(r >> 16);
10892       background.gray = (png_byte)(r >> 24);
10893    }
10894 
10895    background.index = 193; /* rgb(193,193,193) to detect errors */
10896 
10897    if (!(colour_type & PNG_COLOR_MASK_COLOR))
10898    {
10899       /* Because, currently, png_set_background is always called with
10900        * 'need_expand' false in this case and because the gamma test itself
10901        * doesn't cause an expand to 8-bit for lower bit depths the colour must
10902        * be reduced to the correct range.
10903        */
10904       if (bit_depth < 8)
10905          background.gray &= (png_uint_16)((1U << bit_depth)-1);
10906 
10907       /* Grayscale input, we do not convert to RGB (TBD), so we must set the
10908        * background to gray - else libpng seems to fail.
10909        */
10910       background.red = background.green = background.blue = background.gray;
10911    }
10912 
10913    pos = safecat(name, sizeof name, pos, "gamma ");
10914    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10915    pos = safecat(name, sizeof name, pos, "->");
10916    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10917 
10918    pos = safecat(name, sizeof name, pos, base);
10919    if (do_background < ALPHA_MODE_OFFSET)
10920    {
10921       /* Include the background color and gamma in the name: */
10922       pos = safecat(name, sizeof name, pos, "(");
10923       /* This assumes no expand gray->rgb - the current code won't handle that!
10924        */
10925       if (colour_type & PNG_COLOR_MASK_COLOR)
10926       {
10927          pos = safecatn(name, sizeof name, pos, background.red);
10928          pos = safecat(name, sizeof name, pos, ",");
10929          pos = safecatn(name, sizeof name, pos, background.green);
10930          pos = safecat(name, sizeof name, pos, ",");
10931          pos = safecatn(name, sizeof name, pos, background.blue);
10932       }
10933       else
10934          pos = safecatn(name, sizeof name, pos, background.gray);
10935       pos = safecat(name, sizeof name, pos, ")^");
10936       pos = safecatd(name, sizeof name, pos, bg, 3);
10937    }
10938 
10939    gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10940       file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
10941       0/*strip 16*/, expand_16, do_background, &background, bg);
10942 }
10943 
10944 
10945 static void
perform_gamma_composition_tests(png_modifier * pm,int do_background,int expand_16)10946 perform_gamma_composition_tests(png_modifier *pm, int do_background,
10947    int expand_16)
10948 {
10949    png_byte colour_type = 0;
10950    png_byte bit_depth = 0;
10951    unsigned int palette_number = 0;
10952 
10953    /* Skip the non-alpha cases - there is no setting of a transparency colour at
10954     * present.
10955     *
10956     * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
10957     * however the palette case fails miserably so is commented out below.
10958     */
10959    while (next_format(&colour_type, &bit_depth, &palette_number,
10960                       pm->test_lbg_gamma_composition, pm->test_tRNS))
10961       if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
10962 #if 0 /* TODO: FIXME */
10963           /*TODO: FIXME: this should work */
10964           || colour_type == 3
10965 #endif
10966           || (colour_type != 3 && palette_number != 0))
10967    {
10968       unsigned int i, j;
10969 
10970       /* Don't skip the i==j case here - it's relevant. */
10971       for (i=0; i<pm->ngamma_tests; ++i)
10972       {
10973          for (j=0; j<pm->ngamma_tests; ++j)
10974          {
10975             gamma_composition_test(pm, colour_type, bit_depth, palette_number,
10976                pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10977                pm->use_input_precision, do_background, expand_16);
10978 
10979             if (fail(pm))
10980                return;
10981          }
10982       }
10983    }
10984 }
10985 #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
10986 
10987 static void
init_gamma_errors(png_modifier * pm)10988 init_gamma_errors(png_modifier *pm)
10989 {
10990    /* Use -1 to catch tests that were not actually run */
10991    pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
10992    pm->error_color_8 = -1.;
10993    pm->error_indexed = -1.;
10994    pm->error_gray_16 = pm->error_color_16 = -1.;
10995 }
10996 
10997 static void
print_one(const char * leader,double err)10998 print_one(const char *leader, double err)
10999 {
11000    if (err != -1.)
11001       printf(" %s %.5f\n", leader, err);
11002 }
11003 
11004 static void
summarize_gamma_errors(png_modifier * pm,png_const_charp who,int low_bit_depth,int indexed)11005 summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
11006    int indexed)
11007 {
11008    fflush(stderr);
11009 
11010    if (who)
11011       printf("\nGamma correction with %s:\n", who);
11012 
11013    else
11014       printf("\nBasic gamma correction:\n");
11015 
11016    if (low_bit_depth)
11017    {
11018       print_one(" 2 bit gray: ", pm->error_gray_2);
11019       print_one(" 4 bit gray: ", pm->error_gray_4);
11020       print_one(" 8 bit gray: ", pm->error_gray_8);
11021       print_one(" 8 bit color:", pm->error_color_8);
11022       if (indexed)
11023          print_one(" indexed:    ", pm->error_indexed);
11024    }
11025 
11026    print_one("16 bit gray: ", pm->error_gray_16);
11027    print_one("16 bit color:", pm->error_color_16);
11028 
11029    fflush(stdout);
11030 }
11031 
11032 static void
perform_gamma_test(png_modifier * pm,int summary)11033 perform_gamma_test(png_modifier *pm, int summary)
11034 {
11035    /*TODO: remove this*/
11036    /* Save certain values for the temporary overrides below. */
11037    unsigned int calculations_use_input_precision =
11038       pm->calculations_use_input_precision;
11039 #  ifdef PNG_READ_BACKGROUND_SUPPORTED
11040       double maxout8 = pm->maxout8;
11041 #  endif
11042 
11043    /* First some arbitrary no-transform tests: */
11044    if (!pm->this.speed && pm->test_gamma_threshold)
11045    {
11046       perform_gamma_threshold_tests(pm);
11047 
11048       if (fail(pm))
11049          return;
11050    }
11051 
11052    /* Now some real transforms. */
11053    if (pm->test_gamma_transform)
11054    {
11055       if (summary)
11056       {
11057          fflush(stderr);
11058          printf("Gamma correction error summary\n\n");
11059          printf("The printed value is the maximum error in the pixel values\n");
11060          printf("calculated by the libpng gamma correction code.  The error\n");
11061          printf("is calculated as the difference between the output pixel\n");
11062          printf("value (always an integer) and the ideal value from the\n");
11063          printf("libpng specification (typically not an integer).\n\n");
11064 
11065          printf("Expect this value to be less than .5 for 8 bit formats,\n");
11066          printf("less than 1 for formats with fewer than 8 bits and a small\n");
11067          printf("number (typically less than 5) for the 16 bit formats.\n");
11068          printf("For performance reasons the value for 16 bit formats\n");
11069          printf("increases when the image file includes an sBIT chunk.\n");
11070          fflush(stdout);
11071       }
11072 
11073       init_gamma_errors(pm);
11074       /*TODO: remove this.  Necessary because the current libpng
11075        * implementation works in 8 bits:
11076        */
11077       if (pm->test_gamma_expand16)
11078          pm->calculations_use_input_precision = 1;
11079       perform_gamma_transform_tests(pm);
11080       if (!calculations_use_input_precision)
11081          pm->calculations_use_input_precision = 0;
11082 
11083       if (summary)
11084          summarize_gamma_errors(pm, NULL/*who*/, 1/*low bit depth*/, 1/*indexed*/);
11085 
11086       if (fail(pm))
11087          return;
11088    }
11089 
11090    /* The sbit tests produce much larger errors: */
11091    if (pm->test_gamma_sbit)
11092    {
11093       init_gamma_errors(pm);
11094       perform_gamma_sbit_tests(pm);
11095 
11096       if (summary)
11097          summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
11098 
11099       if (fail(pm))
11100          return;
11101    }
11102 
11103 #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
11104    if (pm->test_gamma_scale16)
11105    {
11106       /* The 16 to 8 bit strip operations: */
11107       init_gamma_errors(pm);
11108       perform_gamma_scale16_tests(pm);
11109 
11110       if (summary)
11111       {
11112          fflush(stderr);
11113          printf("\nGamma correction with 16 to 8 bit reduction:\n");
11114          printf(" 16 bit gray:  %.5f\n", pm->error_gray_16);
11115          printf(" 16 bit color: %.5f\n", pm->error_color_16);
11116          fflush(stdout);
11117       }
11118 
11119       if (fail(pm))
11120          return;
11121    }
11122 #endif
11123 
11124 #ifdef PNG_READ_BACKGROUND_SUPPORTED
11125    if (pm->test_gamma_background)
11126    {
11127       init_gamma_errors(pm);
11128 
11129       /*TODO: remove this.  Necessary because the current libpng
11130        * implementation works in 8 bits:
11131        */
11132       if (pm->test_gamma_expand16)
11133       {
11134          pm->calculations_use_input_precision = 1;
11135          pm->maxout8 = .499; /* because the 16 bit background is smashed */
11136       }
11137       perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
11138          pm->test_gamma_expand16);
11139       if (!calculations_use_input_precision)
11140          pm->calculations_use_input_precision = 0;
11141       pm->maxout8 = maxout8;
11142 
11143       if (summary)
11144          summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
11145 
11146       if (fail(pm))
11147          return;
11148    }
11149 #endif
11150 
11151 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
11152    if (pm->test_gamma_alpha_mode)
11153    {
11154       int do_background;
11155 
11156       init_gamma_errors(pm);
11157 
11158       /*TODO: remove this.  Necessary because the current libpng
11159        * implementation works in 8 bits:
11160        */
11161       if (pm->test_gamma_expand16)
11162          pm->calculations_use_input_precision = 1;
11163       for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
11164          do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
11165          ++do_background)
11166          perform_gamma_composition_tests(pm, do_background,
11167             pm->test_gamma_expand16);
11168       if (!calculations_use_input_precision)
11169          pm->calculations_use_input_precision = 0;
11170 
11171       if (summary)
11172          summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
11173 
11174       if (fail(pm))
11175          return;
11176    }
11177 #endif
11178 }
11179 #endif /* PNG_READ_GAMMA_SUPPORTED */
11180 #endif /* PNG_READ_SUPPORTED */
11181 
11182 /* INTERLACE MACRO VALIDATION */
11183 /* This is copied verbatim from the specification, it is simply the pass
11184  * number in which each pixel in each 8x8 tile appears.  The array must
11185  * be indexed adam7[y][x] and notice that the pass numbers are based at
11186  * 1, not 0 - the base libpng uses.
11187  */
11188 static const
11189 png_byte adam7[8][8] =
11190 {
11191    { 1,6,4,6,2,6,4,6 },
11192    { 7,7,7,7,7,7,7,7 },
11193    { 5,6,5,6,5,6,5,6 },
11194    { 7,7,7,7,7,7,7,7 },
11195    { 3,6,4,6,3,6,4,6 },
11196    { 7,7,7,7,7,7,7,7 },
11197    { 5,6,5,6,5,6,5,6 },
11198    { 7,7,7,7,7,7,7,7 }
11199 };
11200 
11201 /* This routine validates all the interlace support macros in png.h for
11202  * a variety of valid PNG widths and heights.  It uses a number of similarly
11203  * named internal routines that feed off the above array.
11204  */
11205 static png_uint_32
png_pass_start_row(int pass)11206 png_pass_start_row(int pass)
11207 {
11208    int x, y;
11209    ++pass;
11210    for (y=0; y<8; ++y)
11211       for (x=0; x<8; ++x)
11212          if (adam7[y][x] == pass)
11213             return y;
11214    return 0xf;
11215 }
11216 
11217 static png_uint_32
png_pass_start_col(int pass)11218 png_pass_start_col(int pass)
11219 {
11220    int x, y;
11221    ++pass;
11222    for (x=0; x<8; ++x)
11223       for (y=0; y<8; ++y)
11224          if (adam7[y][x] == pass)
11225             return x;
11226    return 0xf;
11227 }
11228 
11229 static int
png_pass_row_shift(int pass)11230 png_pass_row_shift(int pass)
11231 {
11232    int x, y, base=(-1), inc=8;
11233    ++pass;
11234    for (y=0; y<8; ++y)
11235    {
11236       for (x=0; x<8; ++x)
11237       {
11238          if (adam7[y][x] == pass)
11239          {
11240             if (base == (-1))
11241                base = y;
11242             else if (base == y)
11243                {}
11244             else if (inc == y-base)
11245                base=y;
11246             else if (inc == 8)
11247                inc = y-base, base=y;
11248             else if (inc != y-base)
11249                return 0xff; /* error - more than one 'inc' value! */
11250          }
11251       }
11252    }
11253 
11254    if (base == (-1)) return 0xfe; /* error - no row in pass! */
11255 
11256    /* The shift is always 1, 2 or 3 - no pass has all the rows! */
11257    switch (inc)
11258    {
11259 case 2: return 1;
11260 case 4: return 2;
11261 case 8: return 3;
11262 default: break;
11263    }
11264 
11265    /* error - unrecognized 'inc' */
11266    return (inc << 8) + 0xfd;
11267 }
11268 
11269 static int
png_pass_col_shift(int pass)11270 png_pass_col_shift(int pass)
11271 {
11272    int x, y, base=(-1), inc=8;
11273    ++pass;
11274    for (x=0; x<8; ++x)
11275    {
11276       for (y=0; y<8; ++y)
11277       {
11278          if (adam7[y][x] == pass)
11279          {
11280             if (base == (-1))
11281                base = x;
11282             else if (base == x)
11283                {}
11284             else if (inc == x-base)
11285                base=x;
11286             else if (inc == 8)
11287                inc = x-base, base=x;
11288             else if (inc != x-base)
11289                return 0xff; /* error - more than one 'inc' value! */
11290          }
11291       }
11292    }
11293 
11294    if (base == (-1)) return 0xfe; /* error - no row in pass! */
11295 
11296    /* The shift is always 1, 2 or 3 - no pass has all the rows! */
11297    switch (inc)
11298    {
11299 case 1: return 0; /* pass 7 has all the columns */
11300 case 2: return 1;
11301 case 4: return 2;
11302 case 8: return 3;
11303 default: break;
11304    }
11305 
11306    /* error - unrecognized 'inc' */
11307    return (inc << 8) + 0xfd;
11308 }
11309 
11310 static png_uint_32
png_row_from_pass_row(png_uint_32 yIn,int pass)11311 png_row_from_pass_row(png_uint_32 yIn, int pass)
11312 {
11313    /* By examination of the array: */
11314    switch (pass)
11315    {
11316 case 0: return yIn * 8;
11317 case 1: return yIn * 8;
11318 case 2: return yIn * 8 + 4;
11319 case 3: return yIn * 4;
11320 case 4: return yIn * 4 + 2;
11321 case 5: return yIn * 2;
11322 case 6: return yIn * 2 + 1;
11323 default: break;
11324    }
11325 
11326    return 0xff; /* bad pass number */
11327 }
11328 
11329 static png_uint_32
png_col_from_pass_col(png_uint_32 xIn,int pass)11330 png_col_from_pass_col(png_uint_32 xIn, int pass)
11331 {
11332    /* By examination of the array: */
11333    switch (pass)
11334    {
11335 case 0: return xIn * 8;
11336 case 1: return xIn * 8 + 4;
11337 case 2: return xIn * 4;
11338 case 3: return xIn * 4 + 2;
11339 case 4: return xIn * 2;
11340 case 5: return xIn * 2 + 1;
11341 case 6: return xIn;
11342 default: break;
11343    }
11344 
11345    return 0xff; /* bad pass number */
11346 }
11347 
11348 static int
png_row_in_interlace_pass(png_uint_32 y,int pass)11349 png_row_in_interlace_pass(png_uint_32 y, int pass)
11350 {
11351    /* Is row 'y' in pass 'pass'? */
11352    int x;
11353    y &= 7;
11354    ++pass;
11355    for (x=0; x<8; ++x)
11356       if (adam7[y][x] == pass)
11357          return 1;
11358 
11359    return 0;
11360 }
11361 
11362 static int
png_col_in_interlace_pass(png_uint_32 x,int pass)11363 png_col_in_interlace_pass(png_uint_32 x, int pass)
11364 {
11365    /* Is column 'x' in pass 'pass'? */
11366    int y;
11367    x &= 7;
11368    ++pass;
11369    for (y=0; y<8; ++y)
11370       if (adam7[y][x] == pass)
11371          return 1;
11372 
11373    return 0;
11374 }
11375 
11376 static png_uint_32
png_pass_rows(png_uint_32 height,int pass)11377 png_pass_rows(png_uint_32 height, int pass)
11378 {
11379    png_uint_32 tiles = height>>3;
11380    png_uint_32 rows = 0;
11381    unsigned int x, y;
11382 
11383    height &= 7;
11384    ++pass;
11385    for (y=0; y<8; ++y)
11386    {
11387       for (x=0; x<8; ++x)
11388       {
11389          if (adam7[y][x] == pass)
11390          {
11391             rows += tiles;
11392             if (y < height) ++rows;
11393             break; /* i.e. break the 'x', column, loop. */
11394          }
11395       }
11396    }
11397 
11398    return rows;
11399 }
11400 
11401 static png_uint_32
png_pass_cols(png_uint_32 width,int pass)11402 png_pass_cols(png_uint_32 width, int pass)
11403 {
11404    png_uint_32 tiles = width>>3;
11405    png_uint_32 cols = 0;
11406    unsigned int x, y;
11407 
11408    width &= 7;
11409    ++pass;
11410    for (x=0; x<8; ++x)
11411    {
11412       for (y=0; y<8; ++y)
11413       {
11414          if (adam7[y][x] == pass)
11415          {
11416             cols += tiles;
11417             if (x < width) ++cols;
11418             break; /* i.e. break the 'y', row, loop. */
11419          }
11420       }
11421    }
11422 
11423    return cols;
11424 }
11425 
11426 static void
perform_interlace_macro_validation(void)11427 perform_interlace_macro_validation(void)
11428 {
11429    /* The macros to validate, first those that depend only on pass:
11430     *
11431     * PNG_PASS_START_ROW(pass)
11432     * PNG_PASS_START_COL(pass)
11433     * PNG_PASS_ROW_SHIFT(pass)
11434     * PNG_PASS_COL_SHIFT(pass)
11435     */
11436    int pass;
11437 
11438    for (pass=0; pass<7; ++pass)
11439    {
11440       png_uint_32 m, f, v;
11441 
11442       m = PNG_PASS_START_ROW(pass);
11443       f = png_pass_start_row(pass);
11444       if (m != f)
11445       {
11446          fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
11447          exit(99);
11448       }
11449 
11450       m = PNG_PASS_START_COL(pass);
11451       f = png_pass_start_col(pass);
11452       if (m != f)
11453       {
11454          fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
11455          exit(99);
11456       }
11457 
11458       m = PNG_PASS_ROW_SHIFT(pass);
11459       f = png_pass_row_shift(pass);
11460       if (m != f)
11461       {
11462          fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
11463          exit(99);
11464       }
11465 
11466       m = PNG_PASS_COL_SHIFT(pass);
11467       f = png_pass_col_shift(pass);
11468       if (m != f)
11469       {
11470          fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
11471          exit(99);
11472       }
11473 
11474       /* Macros that depend on the image or sub-image height too:
11475        *
11476        * PNG_PASS_ROWS(height, pass)
11477        * PNG_PASS_COLS(width, pass)
11478        * PNG_ROW_FROM_PASS_ROW(yIn, pass)
11479        * PNG_COL_FROM_PASS_COL(xIn, pass)
11480        * PNG_ROW_IN_INTERLACE_PASS(y, pass)
11481        * PNG_COL_IN_INTERLACE_PASS(x, pass)
11482        */
11483       for (v=0;;)
11484       {
11485          /* The first two tests overflow if the pass row or column is outside
11486           * the possible range for a 32-bit result.  In fact the values should
11487           * never be outside the range for a 31-bit result, but checking for 32
11488           * bits here ensures that if an app uses a bogus pass row or column
11489           * (just so long as it fits in a 32 bit integer) it won't get a
11490           * possibly dangerous overflow.
11491           */
11492          /* First the base 0 stuff: */
11493          if (v < png_pass_rows(0xFFFFFFFFU, pass))
11494          {
11495             m = PNG_ROW_FROM_PASS_ROW(v, pass);
11496             f = png_row_from_pass_row(v, pass);
11497             if (m != f)
11498             {
11499                fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
11500                   v, pass, m, f);
11501                exit(99);
11502             }
11503          }
11504 
11505          if (v < png_pass_cols(0xFFFFFFFFU, pass))
11506          {
11507             m = PNG_COL_FROM_PASS_COL(v, pass);
11508             f = png_col_from_pass_col(v, pass);
11509             if (m != f)
11510             {
11511                fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
11512                   v, pass, m, f);
11513                exit(99);
11514             }
11515          }
11516 
11517          m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
11518          f = png_row_in_interlace_pass(v, pass);
11519          if (m != f)
11520          {
11521             fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11522                v, pass, m, f);
11523             exit(99);
11524          }
11525 
11526          m = PNG_COL_IN_INTERLACE_PASS(v, pass);
11527          f = png_col_in_interlace_pass(v, pass);
11528          if (m != f)
11529          {
11530             fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11531                v, pass, m, f);
11532             exit(99);
11533          }
11534 
11535          /* Then the base 1 stuff: */
11536          ++v;
11537          m = PNG_PASS_ROWS(v, pass);
11538          f = png_pass_rows(v, pass);
11539          if (m != f)
11540          {
11541             fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
11542                v, pass, m, f);
11543             exit(99);
11544          }
11545 
11546          m = PNG_PASS_COLS(v, pass);
11547          f = png_pass_cols(v, pass);
11548          if (m != f)
11549          {
11550             fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
11551                v, pass, m, f);
11552             exit(99);
11553          }
11554 
11555          /* Move to the next v - the stepping algorithm starts skipping
11556           * values above 1024.
11557           */
11558          if (v > 1024)
11559          {
11560             if (v == PNG_UINT_31_MAX)
11561                break;
11562 
11563             v = (v << 1) ^ v;
11564             if (v >= PNG_UINT_31_MAX)
11565                v = PNG_UINT_31_MAX-1;
11566          }
11567       }
11568    }
11569 }
11570 
11571 /* Test color encodings. These values are back-calculated from the published
11572  * chromaticities.  The values are accurate to about 14 decimal places; 15 are
11573  * given.  These values are much more accurate than the ones given in the spec,
11574  * which typically don't exceed 4 decimal places.  This allows testing of the
11575  * libpng code to its theoretical accuracy of 4 decimal places.  (If pngvalid
11576  * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
11577  * more.)
11578  *
11579  * The png_modifier code assumes that encodings[0] is sRGB and treats it
11580  * specially: do not change the first entry in this list!
11581  */
11582 static const color_encoding test_encodings[] =
11583 {
11584 /* sRGB: must be first in this list! */
11585 /*gamma:*/ { 1/2.2,
11586 /*red:  */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
11587 /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
11588 /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
11589 /* Kodak ProPhoto (wide gamut) */
11590 /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
11591 /*red:  */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
11592 /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
11593 /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
11594 /* Adobe RGB (1998) */
11595 /*gamma:*/ { 1/(2+51./256),
11596 /*red:  */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
11597 /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
11598 /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
11599 /* Adobe Wide Gamut RGB */
11600 /*gamma:*/ { 1/(2+51./256),
11601 /*red:  */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
11602 /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
11603 /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
11604 /* Fake encoding which selects just the green channel */
11605 /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
11606 /*red:  */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
11607 /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
11608 /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
11609 };
11610 
11611 /* signal handler
11612  *
11613  * This attempts to trap signals and escape without crashing.  It needs a
11614  * context pointer so that it can throw an exception (call longjmp) to recover
11615  * from the condition; this is handled by making the png_modifier used by 'main'
11616  * into a global variable.
11617  */
11618 static png_modifier pm;
11619 
signal_handler(int signum)11620 static void signal_handler(int signum)
11621 {
11622 
11623    size_t pos = 0;
11624    char msg[64];
11625 
11626    pos = safecat(msg, sizeof msg, pos, "caught signal: ");
11627 
11628    switch (signum)
11629    {
11630       case SIGABRT:
11631          pos = safecat(msg, sizeof msg, pos, "abort");
11632          break;
11633 
11634       case SIGFPE:
11635          pos = safecat(msg, sizeof msg, pos, "floating point exception");
11636          break;
11637 
11638       case SIGILL:
11639          pos = safecat(msg, sizeof msg, pos, "illegal instruction");
11640          break;
11641 
11642       case SIGINT:
11643          pos = safecat(msg, sizeof msg, pos, "interrupt");
11644          break;
11645 
11646       case SIGSEGV:
11647          pos = safecat(msg, sizeof msg, pos, "invalid memory access");
11648          break;
11649 
11650       case SIGTERM:
11651          pos = safecat(msg, sizeof msg, pos, "termination request");
11652          break;
11653 
11654       default:
11655          pos = safecat(msg, sizeof msg, pos, "unknown ");
11656          pos = safecatn(msg, sizeof msg, pos, signum);
11657          break;
11658    }
11659 
11660    store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
11661 
11662    /* And finally throw an exception so we can keep going, unless this is
11663     * SIGTERM in which case stop now.
11664     */
11665    if (signum != SIGTERM)
11666    {
11667       struct exception_context *the_exception_context =
11668          &pm.this.exception_context;
11669 
11670       Throw &pm.this;
11671    }
11672 
11673    else
11674       exit(1);
11675 }
11676 
11677 /* main program */
main(int argc,char ** argv)11678 int main(int argc, char **argv)
11679 {
11680    int summary = 1;  /* Print the error summary at the end */
11681    int memstats = 0; /* Print memory statistics at the end */
11682 
11683    /* Create the given output file on success: */
11684    const char *touch = NULL;
11685 
11686    /* This is an array of standard gamma values (believe it or not I've seen
11687     * every one of these mentioned somewhere.)
11688     *
11689     * In the following list the most useful values are first!
11690     */
11691    static double
11692       gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
11693 
11694    /* This records the command and arguments: */
11695    size_t cp = 0;
11696    char command[1024];
11697 
11698    anon_context(&pm.this);
11699 
11700    gnu_volatile(summary)
11701    gnu_volatile(memstats)
11702    gnu_volatile(touch)
11703 
11704    /* Add appropriate signal handlers, just the ANSI specified ones: */
11705    signal(SIGABRT, signal_handler);
11706    signal(SIGFPE, signal_handler);
11707    signal(SIGILL, signal_handler);
11708    signal(SIGINT, signal_handler);
11709    signal(SIGSEGV, signal_handler);
11710    signal(SIGTERM, signal_handler);
11711 
11712 #ifdef HAVE_FEENABLEEXCEPT
11713    /* Only required to enable FP exceptions on platforms where they start off
11714     * disabled; this is not necessary but if it is not done pngvalid will likely
11715     * end up ignoring FP conditions that other platforms fault.
11716     */
11717    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
11718 #endif
11719 
11720    modifier_init(&pm);
11721 
11722    /* Preallocate the image buffer, because we know how big it needs to be,
11723     * note that, for testing purposes, it is deliberately mis-aligned by tag
11724     * bytes either side.  All rows have an additional five bytes of padding for
11725     * overwrite checking.
11726     */
11727    store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
11728 
11729    /* Don't give argv[0], it's normally some horrible libtool string: */
11730    cp = safecat(command, sizeof command, cp, "pngvalid");
11731 
11732    /* Default to error on warning: */
11733    pm.this.treat_warnings_as_errors = 1;
11734 
11735    /* Default assume_16_bit_calculations appropriately; this tells the checking
11736     * code that 16-bit arithmetic is used for 8-bit samples when it would make a
11737     * difference.
11738     */
11739    pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
11740 
11741    /* Currently 16 bit expansion happens at the end of the pipeline, so the
11742     * calculations are done in the input bit depth not the output.
11743     *
11744     * TODO: fix this
11745     */
11746    pm.calculations_use_input_precision = 1U;
11747 
11748    /* Store the test gammas */
11749    pm.gammas = gammas;
11750    pm.ngammas = ARRAY_SIZE(gammas);
11751    pm.ngamma_tests = 0; /* default to off */
11752 
11753    /* Low bit depth gray images don't do well in the gamma tests, until
11754     * this is fixed turn them off for some gamma cases:
11755     */
11756 #  ifdef PNG_WRITE_tRNS_SUPPORTED
11757       pm.test_tRNS = 1;
11758 #  endif
11759    pm.test_lbg = PNG_LIBPNG_VER >= 10600;
11760    pm.test_lbg_gamma_threshold = 1;
11761    pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
11762    pm.test_lbg_gamma_sbit = 1;
11763    pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
11764 
11765    /* And the test encodings */
11766    pm.encodings = test_encodings;
11767    pm.nencodings = ARRAY_SIZE(test_encodings);
11768 
11769 #  if PNG_LIBPNG_VER < 10700
11770       pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
11771 #  else
11772       pm.sbitlow = 1U;
11773 #  endif
11774 
11775    /* The following allows results to pass if they correspond to anything in the
11776     * transformed range [input-.5,input+.5]; this is is required because of the
11777     * way libpng treats the 16_TO_8 flag when building the gamma tables in
11778     * releases up to 1.6.0.
11779     *
11780     * TODO: review this
11781     */
11782    pm.use_input_precision_16to8 = 1U;
11783    pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
11784 
11785    /* Some default values (set the behavior for 'make check' here).
11786     * These values simply control the maximum error permitted in the gamma
11787     * transformations.  The practical limits for human perception are described
11788     * below (the setting for maxpc16), however for 8 bit encodings it isn't
11789     * possible to meet the accepted capabilities of human vision - i.e. 8 bit
11790     * images can never be good enough, regardless of encoding.
11791     */
11792    pm.maxout8 = .1;     /* Arithmetic error in *encoded* value */
11793    pm.maxabs8 = .00005; /* 1/20000 */
11794    pm.maxcalc8 = 1./255;  /* +/-1 in 8 bits for compose errors */
11795    pm.maxpc8 = .499;    /* I.e., .499% fractional error */
11796    pm.maxout16 = .499;  /* Error in *encoded* value */
11797    pm.maxabs16 = .00005;/* 1/20000 */
11798    pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
11799 #  if PNG_LIBPNG_VER < 10700
11800       pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
11801 #  else
11802       pm.maxcalcG = 1./((1<<16)-1);
11803 #  endif
11804 
11805    /* NOTE: this is a reasonable perceptual limit. We assume that humans can
11806     * perceive light level differences of 1% over a 100:1 range, so we need to
11807     * maintain 1 in 10000 accuracy (in linear light space), which is what the
11808     * following guarantees.  It also allows significantly higher errors at
11809     * higher 16 bit values, which is important for performance.  The actual
11810     * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
11811     * this is only allowed for values >38149 by the following:
11812     */
11813    pm.maxpc16 = .005;   /* I.e., 1/200% - 1/20000 */
11814 
11815    /* Now parse the command line options. */
11816    while (--argc >= 1)
11817    {
11818       int catmore = 0; /* Set if the argument has an argument. */
11819 
11820       /* Record each argument for posterity: */
11821       cp = safecat(command, sizeof command, cp, " ");
11822       cp = safecat(command, sizeof command, cp, *++argv);
11823 
11824       if (strcmp(*argv, "-v") == 0)
11825          pm.this.verbose = 1;
11826 
11827       else if (strcmp(*argv, "-l") == 0)
11828          pm.log = 1;
11829 
11830       else if (strcmp(*argv, "-q") == 0)
11831          summary = pm.this.verbose = pm.log = 0;
11832 
11833       else if (strcmp(*argv, "-w") == 0 ||
11834                strcmp(*argv, "--strict") == 0)
11835          pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */
11836 
11837       else if (strcmp(*argv, "--nostrict") == 0)
11838          pm.this.treat_warnings_as_errors = 0;
11839 
11840       else if (strcmp(*argv, "--speed") == 0)
11841          pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
11842             summary = 0;
11843 
11844       else if (strcmp(*argv, "--memory") == 0)
11845          memstats = 1;
11846 
11847       else if (strcmp(*argv, "--size") == 0)
11848          pm.test_size = 1;
11849 
11850       else if (strcmp(*argv, "--nosize") == 0)
11851          pm.test_size = 0;
11852 
11853       else if (strcmp(*argv, "--standard") == 0)
11854          pm.test_standard = 1;
11855 
11856       else if (strcmp(*argv, "--nostandard") == 0)
11857          pm.test_standard = 0;
11858 
11859       else if (strcmp(*argv, "--transform") == 0)
11860          pm.test_transform = 1;
11861 
11862       else if (strcmp(*argv, "--notransform") == 0)
11863          pm.test_transform = 0;
11864 
11865 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
11866       else if (strncmp(*argv, "--transform-disable=",
11867          sizeof "--transform-disable") == 0)
11868       {
11869          pm.test_transform = 1;
11870          transform_disable(*argv + sizeof "--transform-disable");
11871       }
11872 
11873       else if (strncmp(*argv, "--transform-enable=",
11874          sizeof "--transform-enable") == 0)
11875       {
11876          pm.test_transform = 1;
11877          transform_enable(*argv + sizeof "--transform-enable");
11878       }
11879 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11880 
11881       else if (strcmp(*argv, "--gamma") == 0)
11882       {
11883          /* Just do two gamma tests here (2.2 and linear) for speed: */
11884          pm.ngamma_tests = 2U;
11885          pm.test_gamma_threshold = 1;
11886          pm.test_gamma_transform = 1;
11887          pm.test_gamma_sbit = 1;
11888          pm.test_gamma_scale16 = 1;
11889          pm.test_gamma_background = 1; /* composition */
11890          pm.test_gamma_alpha_mode = 1;
11891       }
11892 
11893       else if (strcmp(*argv, "--nogamma") == 0)
11894          pm.ngamma_tests = 0;
11895 
11896       else if (strcmp(*argv, "--gamma-threshold") == 0)
11897          pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
11898 
11899       else if (strcmp(*argv, "--nogamma-threshold") == 0)
11900          pm.test_gamma_threshold = 0;
11901 
11902       else if (strcmp(*argv, "--gamma-transform") == 0)
11903          pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
11904 
11905       else if (strcmp(*argv, "--nogamma-transform") == 0)
11906          pm.test_gamma_transform = 0;
11907 
11908       else if (strcmp(*argv, "--gamma-sbit") == 0)
11909          pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
11910 
11911       else if (strcmp(*argv, "--nogamma-sbit") == 0)
11912          pm.test_gamma_sbit = 0;
11913 
11914       else if (strcmp(*argv, "--gamma-16-to-8") == 0)
11915          pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
11916 
11917       else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
11918          pm.test_gamma_scale16 = 0;
11919 
11920       else if (strcmp(*argv, "--gamma-background") == 0)
11921          pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
11922 
11923       else if (strcmp(*argv, "--nogamma-background") == 0)
11924          pm.test_gamma_background = 0;
11925 
11926       else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
11927          pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
11928 
11929       else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
11930          pm.test_gamma_alpha_mode = 0;
11931 
11932       else if (strcmp(*argv, "--expand16") == 0)
11933       {
11934 #        ifdef PNG_READ_EXPAND_16_SUPPORTED
11935             pm.test_gamma_expand16 = 1;
11936 #        else
11937             fprintf(stderr, "pngvalid: --expand16: no read support\n");
11938             return SKIP;
11939 #        endif
11940       }
11941 
11942       else if (strcmp(*argv, "--noexpand16") == 0)
11943          pm.test_gamma_expand16 = 0;
11944 
11945       else if (strcmp(*argv, "--low-depth-gray") == 0)
11946          pm.test_lbg = pm.test_lbg_gamma_threshold =
11947             pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11948             pm.test_lbg_gamma_composition = 1;
11949 
11950       else if (strcmp(*argv, "--nolow-depth-gray") == 0)
11951          pm.test_lbg = pm.test_lbg_gamma_threshold =
11952             pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11953             pm.test_lbg_gamma_composition = 0;
11954 
11955       else if (strcmp(*argv, "--tRNS") == 0)
11956       {
11957 #        ifdef PNG_WRITE_tRNS_SUPPORTED
11958             pm.test_tRNS = 1;
11959 #        else
11960             fprintf(stderr, "pngvalid: --tRNS: no write support\n");
11961             return SKIP;
11962 #        endif
11963       }
11964 
11965       else if (strcmp(*argv, "--notRNS") == 0)
11966          pm.test_tRNS = 0;
11967 
11968       else if (strcmp(*argv, "--more-gammas") == 0)
11969          pm.ngamma_tests = 3U;
11970 
11971       else if (strcmp(*argv, "--all-gammas") == 0)
11972          pm.ngamma_tests = pm.ngammas;
11973 
11974       else if (strcmp(*argv, "--progressive-read") == 0)
11975          pm.this.progressive = 1;
11976 
11977       else if (strcmp(*argv, "--use-update-info") == 0)
11978          ++pm.use_update_info; /* Can call multiple times */
11979 
11980       else if (strcmp(*argv, "--interlace") == 0)
11981       {
11982 #        if CAN_WRITE_INTERLACE
11983             pm.interlace_type = PNG_INTERLACE_ADAM7;
11984 #        else /* !CAN_WRITE_INTERLACE */
11985             fprintf(stderr, "pngvalid: no write interlace support\n");
11986             return SKIP;
11987 #        endif /* !CAN_WRITE_INTERLACE */
11988       }
11989 
11990       else if (strcmp(*argv, "--use-input-precision") == 0)
11991          pm.use_input_precision = 1U;
11992 
11993       else if (strcmp(*argv, "--use-calculation-precision") == 0)
11994          pm.use_input_precision = 0;
11995 
11996       else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
11997          pm.calculations_use_input_precision = 1U;
11998 
11999       else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
12000          pm.assume_16_bit_calculations = 1U;
12001 
12002       else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
12003          pm.calculations_use_input_precision =
12004             pm.assume_16_bit_calculations = 0;
12005 
12006       else if (strcmp(*argv, "--exhaustive") == 0)
12007          pm.test_exhaustive = 1;
12008 
12009       else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
12010          --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
12011 
12012       else if (argc > 1 && strcmp(*argv, "--touch") == 0)
12013          --argc, touch = *++argv, catmore = 1;
12014 
12015       else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
12016       {
12017          --argc;
12018 
12019          if (strcmp(5+*argv, "abs8") == 0)
12020             pm.maxabs8 = atof(*++argv);
12021 
12022          else if (strcmp(5+*argv, "abs16") == 0)
12023             pm.maxabs16 = atof(*++argv);
12024 
12025          else if (strcmp(5+*argv, "calc8") == 0)
12026             pm.maxcalc8 = atof(*++argv);
12027 
12028          else if (strcmp(5+*argv, "calc16") == 0)
12029             pm.maxcalc16 = atof(*++argv);
12030 
12031          else if (strcmp(5+*argv, "out8") == 0)
12032             pm.maxout8 = atof(*++argv);
12033 
12034          else if (strcmp(5+*argv, "out16") == 0)
12035             pm.maxout16 = atof(*++argv);
12036 
12037          else if (strcmp(5+*argv, "pc8") == 0)
12038             pm.maxpc8 = atof(*++argv);
12039 
12040          else if (strcmp(5+*argv, "pc16") == 0)
12041             pm.maxpc16 = atof(*++argv);
12042 
12043          else
12044          {
12045             fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
12046             exit(99);
12047          }
12048 
12049          catmore = 1;
12050       }
12051 
12052       else if (strcmp(*argv, "--log8") == 0)
12053          --argc, pm.log8 = atof(*++argv), catmore = 1;
12054 
12055       else if (strcmp(*argv, "--log16") == 0)
12056          --argc, pm.log16 = atof(*++argv), catmore = 1;
12057 
12058 #ifdef PNG_SET_OPTION_SUPPORTED
12059       else if (strncmp(*argv, "--option=", 9) == 0)
12060       {
12061          /* Syntax of the argument is <option>:{on|off} */
12062          const char *arg = 9+*argv;
12063          unsigned char option=0, setting=0;
12064 
12065 #ifdef PNG_ARM_NEON
12066          if (strncmp(arg, "arm-neon:", 9) == 0)
12067             option = PNG_ARM_NEON, arg += 9;
12068 
12069          else
12070 #endif
12071 #ifdef PNG_EXTENSIONS
12072          if (strncmp(arg, "extensions:", 11) == 0)
12073             option = PNG_EXTENSIONS, arg += 11;
12074 
12075          else
12076 #endif
12077 #ifdef PNG_MAXIMUM_INFLATE_WINDOW
12078          if (strncmp(arg, "max-inflate-window:", 19) == 0)
12079             option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
12080 
12081          else
12082 #endif
12083          {
12084             fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
12085             exit(99);
12086          }
12087 
12088          if (strcmp(arg, "off") == 0)
12089             setting = PNG_OPTION_OFF;
12090 
12091          else if (strcmp(arg, "on") == 0)
12092             setting = PNG_OPTION_ON;
12093 
12094          else
12095          {
12096             fprintf(stderr,
12097                "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
12098                *argv, arg);
12099             exit(99);
12100          }
12101 
12102          pm.this.options[pm.this.noptions].option = option;
12103          pm.this.options[pm.this.noptions++].setting = setting;
12104       }
12105 #endif /* PNG_SET_OPTION_SUPPORTED */
12106 
12107       else
12108       {
12109          fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
12110          exit(99);
12111       }
12112 
12113       if (catmore) /* consumed an extra *argv */
12114       {
12115          cp = safecat(command, sizeof command, cp, " ");
12116          cp = safecat(command, sizeof command, cp, *argv);
12117       }
12118    }
12119 
12120    /* If pngvalid is run with no arguments default to a reasonable set of the
12121     * tests.
12122     */
12123    if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
12124       pm.ngamma_tests == 0)
12125    {
12126       /* Make this do all the tests done in the test shell scripts with the same
12127        * parameters, where possible.  The limitation is that all the progressive
12128        * read and interlace stuff has to be done in separate runs, so only the
12129        * basic 'standard' and 'size' tests are done.
12130        */
12131       pm.test_standard = 1;
12132       pm.test_size = 1;
12133       pm.test_transform = 1;
12134       pm.ngamma_tests = 2U;
12135    }
12136 
12137    if (pm.ngamma_tests > 0 &&
12138       pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
12139       pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
12140       pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
12141    {
12142       pm.test_gamma_threshold = 1;
12143       pm.test_gamma_transform = 1;
12144       pm.test_gamma_sbit = 1;
12145       pm.test_gamma_scale16 = 1;
12146       pm.test_gamma_background = 1;
12147       pm.test_gamma_alpha_mode = 1;
12148    }
12149 
12150    else if (pm.ngamma_tests == 0)
12151    {
12152       /* Nothing to test so turn everything off: */
12153       pm.test_gamma_threshold = 0;
12154       pm.test_gamma_transform = 0;
12155       pm.test_gamma_sbit = 0;
12156       pm.test_gamma_scale16 = 0;
12157       pm.test_gamma_background = 0;
12158       pm.test_gamma_alpha_mode = 0;
12159    }
12160 
12161    Try
12162    {
12163       /* Make useful base images */
12164       make_transform_images(&pm);
12165 
12166       /* Perform the standard and gamma tests. */
12167       if (pm.test_standard)
12168       {
12169          perform_interlace_macro_validation();
12170          perform_formatting_test(&pm.this);
12171 #        ifdef PNG_READ_SUPPORTED
12172             perform_standard_test(&pm);
12173 #        endif
12174          perform_error_test(&pm);
12175       }
12176 
12177       /* Various oddly sized images: */
12178       if (pm.test_size)
12179       {
12180          make_size_images(&pm.this);
12181 #        ifdef PNG_READ_SUPPORTED
12182             perform_size_test(&pm);
12183 #        endif
12184       }
12185 
12186 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
12187       /* Combinatorial transforms: */
12188       if (pm.test_transform)
12189          perform_transform_test(&pm);
12190 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
12191 
12192 #ifdef PNG_READ_GAMMA_SUPPORTED
12193       if (pm.ngamma_tests > 0)
12194          perform_gamma_test(&pm, summary);
12195 #endif
12196    }
12197 
12198    Catch_anonymous
12199    {
12200       fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
12201       if (!pm.this.verbose)
12202       {
12203          if (pm.this.error[0] != 0)
12204             fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
12205 
12206          fprintf(stderr, "pngvalid: run with -v to see what happened\n");
12207       }
12208       exit(1);
12209    }
12210 
12211    if (summary)
12212    {
12213       printf("%s: %s (%s point arithmetic)\n",
12214          (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
12215             pm.this.nwarnings)) ? "FAIL" : "PASS",
12216          command,
12217 #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
12218          "floating"
12219 #else
12220          "fixed"
12221 #endif
12222          );
12223    }
12224 
12225    if (memstats)
12226    {
12227       printf("Allocated memory statistics (in bytes):\n"
12228          "\tread  %lu maximum single, %lu peak, %lu total\n"
12229          "\twrite %lu maximum single, %lu peak, %lu total\n",
12230          (unsigned long)pm.this.read_memory_pool.max_max,
12231          (unsigned long)pm.this.read_memory_pool.max_limit,
12232          (unsigned long)pm.this.read_memory_pool.max_total,
12233          (unsigned long)pm.this.write_memory_pool.max_max,
12234          (unsigned long)pm.this.write_memory_pool.max_limit,
12235          (unsigned long)pm.this.write_memory_pool.max_total);
12236    }
12237 
12238    /* Do this here to provoke memory corruption errors in memory not directly
12239     * allocated by libpng - not a complete test, but better than nothing.
12240     */
12241    store_delete(&pm.this);
12242 
12243    /* Error exit if there are any errors, and maybe if there are any
12244     * warnings.
12245     */
12246    if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
12247        pm.this.nwarnings))
12248    {
12249       if (!pm.this.verbose)
12250          fprintf(stderr, "pngvalid: %s\n", pm.this.error);
12251 
12252       fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
12253           pm.this.nwarnings);
12254 
12255       exit(1);
12256    }
12257 
12258    /* Success case. */
12259    if (touch != NULL)
12260    {
12261       FILE *fsuccess = fopen(touch, "wt");
12262 
12263       if (fsuccess != NULL)
12264       {
12265          int error = 0;
12266          fprintf(fsuccess, "PNG validation succeeded\n");
12267          fflush(fsuccess);
12268          error = ferror(fsuccess);
12269 
12270          if (fclose(fsuccess) || error)
12271          {
12272             fprintf(stderr, "%s: write failed\n", touch);
12273             exit(1);
12274          }
12275       }
12276 
12277       else
12278       {
12279          fprintf(stderr, "%s: open failed\n", touch);
12280          exit(1);
12281       }
12282    }
12283 
12284    /* This is required because some very minimal configurations do not use it:
12285     */
12286    UNUSED(fail)
12287    return 0;
12288 }
12289 #else /* write or low level APIs not supported */
main(void)12290 int main(void)
12291 {
12292    fprintf(stderr,
12293       "pngvalid: no low level write support in libpng, all tests skipped\n");
12294    /* So the test is skipped: */
12295    return SKIP;
12296 }
12297 #endif
12298