Imported Upstream version 1.6.13
[platform/upstream/libpng.git] / contrib / libtests / pngimage.c
1 /* pngimage.c
2  *
3  * Copyright (c) 2014 John Cunningham Bowler
4  *
5  * Last changed in libpng 1.6.10 [March 6, 2014]
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  * Test the png_read_png and png_write_png interfaces.  Given a PNG file load it
12  * using png_read_png and then write with png_write_png.  Test all possible
13  * transforms.
14  */
15 #include <stdarg.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <stdio.h>
20 #include <assert.h>
21
22 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
23 #  include <config.h>
24 #endif
25
26 /* Define the following to use this test against your installed libpng, rather
27  * than the one being built here:
28  */
29 #ifdef PNG_FREESTANDING_TESTS
30 #  include <png.h>
31 #else
32 #  include "../../png.h"
33 #endif
34
35 #ifndef PNG_SETJMP_SUPPORTED
36 #  include <setjmp.h> /* because png.h did *not* include this */
37 #endif
38
39 #if defined(PNG_INFO_IMAGE_SUPPORTED) && defined(PNG_SEQUENTIAL_READ_SUPPORTED)
40 /* If a transform is valid on both read and write this implies that if the
41  * transform is applied to read it must also be applied on write to produce
42  * meaningful data.  This is because these transforms when performed on read
43  * produce data with a memory format that does not correspond to a PNG format.
44  *
45  * Most of these transforms are invertible; after applying the transform on
46  * write the result is the original PNG data that would have would have been
47  * read if no transform were applied.
48  *
49  * The exception is _SHIFT, which destroys the low order bits marked as not
50  * significant in a PNG with the sBIT chunk.
51  *
52  * The following table lists, for each transform, the conditions under which it
53  * is expected to do anything.  Conditions are defined as follows:
54  *
55  * 1) Color mask bits required - simply a mask to AND with color_type; one of
56  *    these must be present for the transform to fire, except that 0 means
57  *    'always'.
58  * 2) Color mask bits which must be absent - another mask - none of these must
59  *    be present.
60  * 3) Bit depths - a mask of component bit depths for the transform to fire.
61  * 4) 'read' - the transform works in png_read_png.
62  * 5) 'write' - the transform works in png_write_png.
63  * 6) PNG_INFO_chunk; a mask of the chunks that must be present for the
64  *    transform to fire.  All must be present - the requirement is that
65  *    png_get_valid() & mask == mask, so if mask is 0 there is no requirement.
66  *
67  * The condition refers to the original image state - if multiple transforms are
68  * used together it is possible to cause a transform that wouldn't fire on the
69  * original image to fire.
70  */
71 static struct transform_info
72 {
73    const char *name;
74    int         transform;
75    png_uint_32 valid_chunks;
76 #     define CHUNK_NONE 0
77 #     define CHUNK_sBIT PNG_INFO_sBIT
78 #     define CHUNK_tRNS PNG_INFO_tRNS
79    png_byte    color_mask_required;
80    png_byte    color_mask_absent;
81 #     define COLOR_MASK_X   0
82 #     define COLOR_MASK_P   PNG_COLOR_MASK_PALETTE
83 #     define COLOR_MASK_C   PNG_COLOR_MASK_COLOR
84 #     define COLOR_MASK_A   PNG_COLOR_MASK_ALPHA
85 #     define COLOR_MASK_ALL (PALETTE+COLOR+ALPHA)  /* absent = gray, no alpha */
86    png_byte    bit_depths;
87 #     define BD_ALL  (1 + 2 + 4 + 8 + 16)
88 #     define BD_PAL  (1 + 2 + 4 + 8)
89 #     define BD_LOW  (1 + 2 + 4)
90 #     define BD_16   16
91 #     define BD_TRUE (8+16) /* i.e. true-color depths */
92    png_byte    when;
93 #     define TRANSFORM_R  1
94 #     define TRANSFORM_W  2
95 #     define TRANSFORM_RW 3
96    png_byte    tested; /* the transform was tested somewhere */
97 } transform_info[] =
98 {
99    /* List ALL the PNG_TRANSFORM_ macros here.  Check for support using the READ
100     * macros; even if the transform is supported on write it cannot be tested
101     * without the read support.
102     */
103 #  define T(name,chunk,cm_required,cm_absent,bd,when)\
104    {  #name, PNG_TRANSFORM_ ## name, CHUNK_ ## chunk,\
105       COLOR_MASK_ ## cm_required, COLOR_MASK_ ## cm_absent, BD_ ## bd,\
106       TRANSFORM_ ## when, 0/*!tested*/ }
107
108 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
109    T(STRIP_16,            NONE, X,   X,   16,  R),
110       /* drops the bottom 8 bits when bit depth is 16 */
111 #endif
112 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
113    T(STRIP_ALPHA,         NONE, A,   X,  ALL,  R),
114       /* removes the alpha channel if present */
115 #endif
116 #ifdef PNG_WRITE_PACK_SUPPORTED
117 #  define TRANSFORM_RW_PACK TRANSFORM_RW
118 #else
119 #  define TRANSFORM_RW_PACK TRANSFORM_R
120 #endif
121 #ifdef PNG_READ_PACK_SUPPORTED
122    T(PACKING,             NONE, X,   X,  LOW, RW_PACK),
123       /* unpacks low-bit-depth components into 1 byte per component on read,
124        * reverses this on write.
125        */
126 #endif
127 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
128 #  define TRANSFORM_RW_PACKSWAP TRANSFORM_RW
129 #else
130 #  define TRANSFORM_RW_PACKSWAP TRANSFORM_R
131 #endif
132 #ifdef PNG_READ_PACKSWAP_SUPPORTED
133    T(PACKSWAP,            NONE, X,   X,  LOW, RW_PACKSWAP),
134       /* reverses the order of low-bit-depth components packed into a byte */
135 #endif
136 #ifdef PNG_READ_EXPAND_SUPPORTED
137    T(EXPAND,              NONE, P,   X,  ALL,  R),
138       /* expands PLTE PNG files to RGB (no tRNS) or RGBA (tRNS) *
139        * Note that the 'EXPAND' transform does lots of different things: */
140    T(EXPAND,              NONE, X,   C,  ALL,  R),
141       /* expands grayscale PNG files to RGB, or RGBA */
142    T(EXPAND,              tRNS, X,   A,  ALL,  R),
143       /* expands the tRNS chunk in files without alpha */
144 #endif
145 #ifdef PNG_WRITE_INVERT_SUPPORTED
146 #  define TRANSFORM_RW_INVERT TRANSFORM_RW
147 #else
148 #  define TRANSFORM_RW_INVERT TRANSFORM_R
149 #endif
150 #ifdef PNG_READ_INVERT_SUPPORTED
151    T(INVERT_MONO,         NONE, X,   C,  ALL, RW_INVERT),
152       /* converts gray-scale components to 1..0 from 0..1 */
153 #endif
154 #ifdef PNG_WRITE_SHIFT_SUPPORTED
155 #  define TRANSFORM_RW_SHIFT TRANSFORM_RW
156 #else
157 #  define TRANSFORM_RW_SHIFT TRANSFORM_R
158 #endif
159 #ifdef PNG_READ_SHIFT_SUPPORTED
160    T(SHIFT,               sBIT, X,   X,  ALL, RW_SHIFT),
161       /* reduces component values to the original range based on the sBIT chunk,
162        * this is only partially reversible - the low bits are lost and cannot be
163        * recovered on write.  In fact write code replicates the bits to generate
164        * new low-order bits.
165        */
166 #endif
167 #ifdef PNG_WRITE_BGR_SUPPORTED
168 #  define TRANSFORM_RW_BGR TRANSFORM_RW
169 #else
170 #  define TRANSFORM_RW_BGR TRANSFORM_R
171 #endif
172 #ifdef PNG_READ_BGR_SUPPORTED
173    T(BGR,                 NONE, C,   P, TRUE, RW_BGR),
174       /* reverses the rgb component values of true-color pixels */
175 #endif
176 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
177 #  define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_RW
178 #else
179 #  define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_R
180 #endif
181 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
182    T(SWAP_ALPHA,          NONE, A,   X, TRUE, RW_SWAP_ALPHA),
183       /* swaps the alpha channel of RGBA or GA pixels to the front - ARGB or
184        * AG, on write reverses the process.
185        */
186 #endif
187 #ifdef PNG_WRITE_SWAP_SUPPORTED
188 #  define TRANSFORM_RW_SWAP TRANSFORM_RW
189 #else
190 #  define TRANSFORM_RW_SWAP TRANSFORM_R
191 #endif
192 #ifdef PNG_READ_SWAP_SUPPORTED
193    T(SWAP_ENDIAN,         NONE, X,   P,   16, RW_SWAP),
194       /* byte-swaps 16-bit component values */
195 #endif
196 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
197 #  define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_RW
198 #else
199 #  define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_R
200 #endif
201 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
202    T(INVERT_ALPHA,        NONE, A,   X, TRUE, RW_INVERT_ALPHA),
203       /* converts an alpha channel from 0..1 to 1..0 */
204 #endif
205 #ifdef PNG_WRITE_FILLER_SUPPORTED
206    T(STRIP_FILLER_BEFORE, NONE, A,   P, TRUE,  W), /* 'A' for a filler! */
207       /* on write skips a leading filler channel; testing requires data with a
208        * filler channel so this is produced from RGBA or GA images by removing
209        * the 'alpha' flag from the color type in place.
210        */
211    T(STRIP_FILLER_AFTER,  NONE, A,   P, TRUE,  W),
212       /* on write strips a trailing filler channel */
213 #endif
214 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
215    T(GRAY_TO_RGB,         NONE, X,   C,  ALL,  R),
216       /* expands grayscale images to RGB, also causes the palette part of
217        * 'EXPAND' to happen.  Low bit depth grayscale images are expanded to
218        * 8-bits per component and no attempt is made to convert the image to a
219        * palette image.  While this transform is partially reversible
220        * png_write_png does not currently support this.
221        */
222    T(GRAY_TO_RGB,         NONE, P,   X,  ALL,  R),
223       /* The 'palette' side effect mentioned above; a bit bogus but this is the
224        * way the libpng code works.
225        */
226 #endif
227 #ifdef PNG_READ_EXPAND_16_SUPPORTED
228    T(EXPAND_16,           NONE, X,   X,  PAL,  R),
229       /* expands images to 16-bits per component, as a side effect expands
230        * palette images to RGB and expands the tRNS chunk if present, so it can
231        * modify 16-bit per component images as well:
232        */
233    T(EXPAND_16,           tRNS, X,   A,   16,  R),
234       /* side effect of EXPAND_16 - expands the tRNS chunk in an RGB or G 16-bit
235        * image.
236        */
237 #endif
238 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
239    T(SCALE_16,            NONE, X,   X,   16,  R)
240       /* scales 16-bit components to 8-bits. */
241 #endif
242
243 #undef T
244 };
245
246 #define ARRAY_SIZE(a) ((sizeof a)/(sizeof a[0]))
247 #define TTABLE_SIZE ARRAY_SIZE(transform_info)
248
249 /* Some combinations of options that should be reversible are not; these cases
250  * are bugs.
251  */
252 static int known_bad_combos[][2] =
253 {
254    /* problem, antidote */
255    { PNG_TRANSFORM_SHIFT | PNG_TRANSFORM_INVERT_ALPHA, 0/*antidote*/ }
256 };
257
258 static int
259 is_combo(int transforms)
260 {
261    return transforms & (transforms-1); /* non-zero if more than one set bit */
262 }
263
264 static int
265 first_transform(int transforms)
266 {
267    return transforms & -transforms; /* lowest set bit */
268 }
269
270 static int
271 is_bad_combo(int transforms)
272 {
273    unsigned int i;
274
275    for (i=0; i<ARRAY_SIZE(known_bad_combos); ++i)
276    {
277       int combo = known_bad_combos[i][0];
278
279       if ((combo & transforms) == combo &&
280          (transforms & known_bad_combos[i][1]) == 0)
281          return 1;
282    }
283
284    return 0; /* combo is ok */
285 }
286
287 static const char *
288 transform_name(int t)
289    /* The name, if 't' has multiple bits set the name of the lowest set bit is
290     * returned.
291     */
292 {
293    unsigned int i;
294
295    t &= -t; /* first set bit */
296
297    for (i=0; i<TTABLE_SIZE; ++i)
298    {
299       if ((transform_info[i].transform & t) != 0)
300          return transform_info[i].name;
301    }
302
303    return "invalid transform";
304 }
305
306 /* Variables calculated by validate_T below and used to record all the supported
307  * transforms.  Need (unsigned int) here because of the places where these
308  * values are used (unsigned compares in the 'exhaustive' iterator.)
309  */
310 static unsigned int read_transforms, write_transforms, rw_transforms;
311
312 static void
313 validate_T(void)
314    /* Validate the above table - this just builds the above values */
315 {
316    unsigned int i;
317
318    for (i=0; i<TTABLE_SIZE; ++i)
319    {
320       if (transform_info[i].when & TRANSFORM_R)
321          read_transforms |= transform_info[i].transform;
322
323       if (transform_info[i].when & TRANSFORM_W)
324          write_transforms |= transform_info[i].transform;
325    }
326
327    /* Reversible transforms are those which are supported on both read and
328     * write.
329     */
330    rw_transforms = read_transforms & write_transforms;
331 }
332
333 /* FILE DATA HANDLING
334  *    The original file is cached in memory.  During write the output file is
335  *    written to memory.
336  *
337  *    In both cases the file data is held in a linked list of buffers - not all
338  *    of these are in use at any time.
339  */
340 struct buffer_list
341 {
342    struct buffer_list *next;         /* next buffer in list */
343    png_byte            buffer[1024]; /* the actual buffer */
344 };
345
346 struct buffer
347 {
348    struct buffer_list  *last;       /* last buffer in use */
349    size_t               end_count;  /* bytes in the last buffer */
350    struct buffer_list  *current;    /* current buffer being read */
351    size_t               read_count; /* count of bytes read from current */
352    struct buffer_list   first;      /* the very first buffer */
353 };
354
355 static void
356 buffer_init(struct buffer *buffer)
357    /* Call this only once for a given buffer */
358 {
359    buffer->first.next = NULL;
360    buffer->last = NULL;
361    buffer->current = NULL;
362 }
363
364 #ifdef PNG_WRITE_SUPPORTED
365 static void
366 buffer_start_write(struct buffer *buffer)
367 {
368    buffer->last = &buffer->first;
369    buffer->end_count = 0;
370    buffer->current = NULL;
371 }
372 #endif
373
374 static void
375 buffer_start_read(struct buffer *buffer)
376 {
377    buffer->current = &buffer->first;
378    buffer->read_count = 0;
379 }
380
381 #ifdef ENOMEM /* required by POSIX 1003.1 */
382 #  define MEMORY ENOMEM
383 #else
384 #  define MEMORY ERANGE /* required by ANSI-C */
385 #endif
386 static struct buffer *
387 get_buffer(png_structp pp)
388    /* Used from libpng callbacks to get the current buffer */
389 {
390    return (struct buffer*)png_get_io_ptr(pp);
391 }
392
393 #define NEW(type) ((type *)malloc(sizeof (type)))
394
395 static struct buffer_list *
396 buffer_extend(struct buffer_list *current)
397 {
398    struct buffer_list *add;
399
400    assert(current->next == NULL);
401
402    add = NEW(struct buffer_list);
403    if (add == NULL)
404       return NULL;
405
406    add->next = NULL;
407    current->next = add;
408
409    return add;
410 }
411
412 /* Load a buffer from a file; does the equivalent of buffer_start_write.  On a
413  * read error returns an errno value, else returns 0.
414  */
415 static int
416 buffer_from_file(struct buffer *buffer, FILE *fp)
417 {
418    struct buffer_list *last = &buffer->first;
419    size_t count = 0;
420
421    for (;;)
422    {
423       size_t r = fread(last->buffer+count, 1/*size*/,
424          (sizeof last->buffer)-count, fp);
425
426       if (r > 0)
427       {
428          count += r;
429
430          if (count >= sizeof last->buffer)
431          {
432             assert(count == sizeof last->buffer);
433             count = 0;
434
435             if (last->next == NULL)
436             {
437                last = buffer_extend(last);
438                if (last == NULL)
439                   return MEMORY;
440             }
441
442             else
443                last = last->next;
444          }
445       }
446
447       else /* fread failed - probably end of file */
448       {
449          if (feof(fp))
450          {
451             buffer->last = last;
452             buffer->end_count = count;
453             return 0; /* no error */
454          }
455
456          /* Some kind of funky error; errno should be non-zero */
457          return errno == 0 ? ERANGE : errno;
458       }
459    }
460 }
461
462 /* This structure is used to control the test of a single file. */
463 typedef enum
464 {
465    VERBOSE,        /* switches on all messages */
466    INFORMATION,
467    WARNINGS,       /* switches on warnings */
468    LIBPNG_WARNING,
469    APP_WARNING,
470    ERRORS,         /* just errors */
471    APP_FAIL,       /* continuable error - no need to longjmp */
472    LIBPNG_ERROR,   /* this and higher cause a longjmp */
473    LIBPNG_BUG,     /* erroneous behavior in libpng */
474    APP_ERROR,      /* such as out-of-memory in a callback */
475    QUIET,          /* no normal messages */
476    USER_ERROR,     /* such as file-not-found */
477    INTERNAL_ERROR
478 } error_level;
479 #define LEVEL_MASK      0xf   /* where the level is in 'options' */
480
481 #define EXHAUSTIVE      0x010 /* Test all combinations of active options */
482 #define STRICT          0x020 /* Fail on warnings as well as errors */
483 #define LOG             0x040 /* Log pass/fail to stdout */
484 #define CONTINUE        0x080 /* Continue on APP_FAIL errors */
485 #define SKIP_BUGS       0x100 /* Skip over known bugs */
486 #define LOG_SKIPPED     0x200 /* Log skipped bugs */
487 #define FIND_BAD_COMBOS 0x400 /* Attempt to deduce bad combos */
488
489 /* Result masks apply to the result bits in the 'results' field below; these
490  * bits are simple 1U<<error_level.  A pass requires either nothing worse than
491  * warnings (--relaxes) or nothing worse than information (--strict)
492  */
493 #define RESULT_STRICT(r)   (((r) & ~((1U<<WARNINGS)-1)) == 0)
494 #define RESULT_RELAXED(r)  (((r) & ~((1U<<ERRORS)-1)) == 0)
495
496 struct display
497 {
498    jmp_buf        error_return;      /* Where to go to on error */
499
500    const char    *filename;          /* The name of the original file */
501    const char    *operation;         /* Operation being performed */
502    int            transforms;        /* Transform used in operation */
503    png_uint_32    options;           /* See display_log below */
504    png_uint_32    results;           /* A mask of errors seen */
505
506
507    png_structp    original_pp;       /* used on the original read */
508    png_infop      original_ip;       /* set by the original read */
509
510    png_size_t     original_rowbytes; /* of the original rows: */
511    png_bytepp     original_rows;     /* from the original read */
512
513    /* Original chunks valid */
514    png_uint_32    chunks;
515
516    /* Original IHDR information */
517    png_uint_32    width;
518    png_uint_32    height;
519    int            bit_depth;
520    int            color_type;
521    int            interlace_method;
522    int            compression_method;
523    int            filter_method;
524
525    /* Derived information for the original image. */
526    int            active_transforms;  /* transforms that do something on read */
527    int            ignored_transforms; /* transforms that should do nothing */
528
529    /* Used on a read, both the original read and when validating a written
530     * image.
531     */
532    png_structp    read_pp;
533    png_infop      read_ip;
534
535 #  ifdef PNG_WRITE_SUPPORTED
536       /* Used to write a new image (the original info_ptr is used) */
537       png_structp   write_pp;
538       struct buffer written_file;   /* where the file gets written */
539 #  endif
540
541    struct buffer  original_file;     /* Data read from the original file */
542 };
543
544 static void
545 display_init(struct display *dp)
546    /* Call this only once right at the start to initialize the control
547     * structure, the (struct buffer) lists are maintained across calls - the
548     * memory is not freed.
549     */
550 {
551    memset(dp, 0, sizeof *dp);
552    dp->options = WARNINGS; /* default to !verbose, !quiet */
553    dp->filename = NULL;
554    dp->operation = NULL;
555    dp->original_pp = NULL;
556    dp->original_ip = NULL;
557    dp->original_rows = NULL;
558    dp->read_pp = NULL;
559    dp->read_ip = NULL;
560    buffer_init(&dp->original_file);
561
562 #  ifdef PNG_WRITE_SUPPORTED
563       dp->write_pp = NULL;
564       buffer_init(&dp->written_file);
565 #  endif
566 }
567
568 static void
569 display_clean_read(struct display *dp)
570 {
571    if (dp->read_pp != NULL)
572       png_destroy_read_struct(&dp->read_pp, &dp->read_ip, NULL);
573 }
574
575 #ifdef PNG_WRITE_SUPPORTED
576 static void
577 display_clean_write(struct display *dp)
578 {
579       if (dp->write_pp != NULL)
580          png_destroy_write_struct(&dp->write_pp, NULL);
581 }
582 #endif
583
584 static void
585 display_clean(struct display *dp)
586 {
587 #  ifdef PNG_WRITE_SUPPORTED
588       display_clean_write(dp);
589 #  endif
590    display_clean_read(dp);
591
592    dp->original_rowbytes = 0;
593    dp->original_rows = NULL;
594    dp->chunks = 0;
595
596    png_destroy_read_struct(&dp->original_pp, &dp->original_ip, NULL);
597    /* leave the filename for error detection */
598    dp->results = 0; /* reset for next time */
599 }
600
601 static struct display *
602 get_dp(png_structp pp)
603    /* The display pointer is always stored in the png_struct error pointer */
604 {
605    struct display *dp = (struct display*)png_get_error_ptr(pp);
606
607    if (dp == NULL)
608    {
609       fprintf(stderr, "pngimage: internal error (no display)\n");
610       exit(99); /* prevents a crash */
611    }
612
613    return dp;
614 }
615
616 /* error handling */
617 #ifdef __GNUC__
618 #  define VGATTR __attribute__((__format__ (__printf__,3,4)))
619    /* Required to quiet GNUC warnings when the compiler sees a stdarg function
620     * that calls one of the stdio v APIs.
621     */
622 #else
623 #  define VGATTR
624 #endif
625 static void VGATTR
626 display_log(struct display *dp, error_level level, const char *fmt, ...)
627    /* 'level' is as above, fmt is a stdio style format string.  This routine
628     * does not return if level is above LIBPNG_WARNING
629     */
630 {
631    dp->results |= 1U << level;
632
633    if (level > (error_level)(dp->options & LEVEL_MASK))
634    {
635       const char *lp;
636       va_list ap;
637
638       switch (level)
639       {
640          case INFORMATION:    lp = "information"; break;
641          case LIBPNG_WARNING: lp = "warning(libpng)"; break;
642          case APP_WARNING:    lp = "warning(pngimage)"; break;
643          case APP_FAIL:       lp = "error(continuable)"; break;
644          case LIBPNG_ERROR:   lp = "error(libpng)"; break;
645          case LIBPNG_BUG:     lp = "bug(libpng)"; break;
646          case APP_ERROR:      lp = "error(pngimage)"; break;
647          case USER_ERROR:     lp = "error(user)"; break;
648
649          case INTERNAL_ERROR: /* anything unexpected is an internal error: */
650          case VERBOSE: case WARNINGS: case ERRORS: case QUIET:
651          default:             lp = "bug(pngimage)"; break;
652       }
653
654       fprintf(stderr, "%s: %s: %s",
655          dp->filename != NULL ? dp->filename : "<stdin>", lp, dp->operation);
656
657       if (dp->transforms != 0)
658       {
659          int tr = dp->transforms;
660
661          if (is_combo(tr))
662             fprintf(stderr, "(0x%x)", tr);
663
664          else
665             fprintf(stderr, "(%s)", transform_name(tr));
666       }
667
668       fprintf(stderr, ": ");
669
670       va_start(ap, fmt);
671       vfprintf(stderr, fmt, ap);
672       va_end(ap);
673
674       fputc('\n', stderr);
675    }
676    /* else do not output any message */
677
678    /* Errors cause this routine to exit to the fail code */
679    if (level > APP_FAIL || (level > ERRORS && !(dp->options & CONTINUE)))
680       longjmp(dp->error_return, level);
681 }
682
683 /* error handler callbacks for libpng */
684 static void PNGCBAPI
685 display_warning(png_structp pp, png_const_charp warning)
686 {
687    display_log(get_dp(pp), LIBPNG_WARNING, "%s", warning);
688 }
689
690 static void PNGCBAPI
691 display_error(png_structp pp, png_const_charp error)
692 {
693    struct display *dp = get_dp(pp);
694
695    display_log(dp, LIBPNG_ERROR, "%s", error);
696 }
697
698 static void
699 display_cache_file(struct display *dp, const char *filename)
700    /* Does the initial cache of the file. */
701 {
702    FILE *fp;
703    int ret;
704
705    dp->filename = filename;
706
707    if (filename != NULL)
708    {
709       fp = fopen(filename, "rb");
710       if (fp == NULL)
711          display_log(dp, USER_ERROR, "open failed: %s", strerror(errno));
712    }
713
714    else
715       fp = stdin;
716
717    ret = buffer_from_file(&dp->original_file, fp);
718
719    fclose(fp);
720
721    if (ret != 0)
722       display_log(dp, APP_ERROR, "read failed: %s", strerror(ret));
723 }
724
725 static void
726 buffer_read(struct display *dp, struct buffer *bp, png_bytep data,
727    png_size_t size)
728 {
729    struct buffer_list *last = bp->current;
730    size_t read_count = bp->read_count;
731
732    while (size > 0)
733    {
734       size_t avail;
735
736       if (last == NULL ||
737          (last == bp->last && read_count >= bp->end_count))
738       {
739          display_log(dp, USER_ERROR, "file truncated (%lu bytes)",
740             (unsigned long)size);
741          /*NOTREACHED*/
742          break;
743       }
744
745       else if (read_count >= sizeof last->buffer)
746       {
747          /* Move to the next buffer: */
748          last = last->next;
749          read_count = 0;
750          bp->current = last; /* Avoid update outside the loop */
751
752          /* And do a sanity check (the EOF case is caught above) */
753          if (last == NULL)
754          {
755             display_log(dp, INTERNAL_ERROR, "damaged buffer list");
756             /*NOTREACHED*/
757             break;
758          }
759       }
760
761       avail = (sizeof last->buffer) - read_count;
762       if (avail > size)
763          avail = size;
764
765       memcpy(data, last->buffer + read_count, avail);
766       read_count += avail;
767       size -= avail;
768       data += avail;
769    }
770
771    bp->read_count = read_count;
772 }
773
774 static void PNGCBAPI
775 read_function(png_structp pp, png_bytep data, png_size_t size)
776 {
777    buffer_read(get_dp(pp), get_buffer(pp), data, size);
778 }
779
780 static void
781 read_png(struct display *dp, struct buffer *bp, const char *operation,
782    int transforms)
783 {
784    png_structp pp;
785    png_infop   ip;
786
787    /* This cleans out any previous read and sets operation and transforms to
788     * empty.
789     */
790    display_clean_read(dp);
791
792    if (operation != NULL) /* else this is a verify and do not overwrite info */
793    {
794       dp->operation = operation;
795       dp->transforms = transforms;
796    }
797
798    dp->read_pp = pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, dp,
799       display_error, display_warning);
800    if (pp == NULL)
801       display_log(dp, LIBPNG_ERROR, "failed to create read struct");
802
803    /* The png_read_png API requires us to make the info struct, but it does the
804     * call to png_read_info.
805     */
806    dp->read_ip = ip = png_create_info_struct(pp);
807    if (ip == NULL)
808       display_log(dp, LIBPNG_ERROR, "failed to create info struct");
809
810 #  ifdef PNG_SET_USER_LIMITS_SUPPORTED
811       /* Remove the user limits, if any */
812       png_set_user_limits(pp, 0x7fffffff, 0x7fffffff);
813 #  endif
814
815    /* Set the IO handling */
816    buffer_start_read(bp);
817    png_set_read_fn(pp, bp, read_function);
818
819    png_read_png(pp, ip, transforms, NULL/*params*/);
820
821 #if 0 /* crazy debugging */
822    {
823       png_bytep pr = png_get_rows(pp, ip)[0];
824       size_t rb = png_get_rowbytes(pp, ip);
825       size_t cb;
826       char c = ' ';
827
828       fprintf(stderr, "%.4x %2d (%3lu bytes):", transforms, png_get_bit_depth(pp,ip), (unsigned long)rb);
829
830       for (cb=0; cb<rb; ++cb)
831          fputc(c, stderr), fprintf(stderr, "%.2x", pr[cb]), c='.';
832
833       fputc('\n', stderr);
834    }
835 #endif
836 }
837
838 static void
839 update_display(struct display *dp)
840    /* called once after the first read to update all the info, original_pp and
841     * original_ip must have been filled in.
842     */
843 {
844    png_structp pp;
845    png_infop   ip;
846
847    /* Now perform the initial read with a 0 tranform. */
848    read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
849
850    /* Move the result to the 'original' fields */
851    dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
852    dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
853
854    dp->original_rowbytes = png_get_rowbytes(pp, ip);
855    if (dp->original_rowbytes == 0)
856       display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
857
858    dp->chunks = png_get_valid(pp, ip, 0xffffffff);
859    if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
860       display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
861
862    dp->original_rows = png_get_rows(pp, ip);
863    if (dp->original_rows == NULL)
864       display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
865
866    if (!png_get_IHDR(pp, ip,
867       &dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
868       &dp->interlace_method, &dp->compression_method, &dp->filter_method))
869       display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
870
871    /* 'active' transforms are discovered based on the original image format;
872     * running one active transform can activate others.  At present the code
873     * does not attempt to determine the closure.
874     */
875    {
876       png_uint_32 chunks = dp->chunks;
877       int active = 0, inactive = 0;
878       int ct = dp->color_type;
879       int bd = dp->bit_depth;
880       unsigned int i;
881
882       for (i=0; i<TTABLE_SIZE; ++i)
883       {
884          int transform = transform_info[i].transform;
885
886          if ((transform_info[i].valid_chunks == 0 ||
887                (transform_info[i].valid_chunks & chunks) != 0) &&
888             (transform_info[i].color_mask_required & ct) == 
889                transform_info[i].color_mask_required &&
890             (transform_info[i].color_mask_absent & ct) == 0 &&
891             (transform_info[i].bit_depths & bd) != 0 &&
892             (transform_info[i].when & TRANSFORM_R) != 0)
893             active |= transform;
894
895          else if ((transform_info[i].when & TRANSFORM_R) != 0)
896             inactive |= transform;
897       }
898
899       /* Some transforms appear multiple times in the table; the 'active' status
900        * is the logical OR of these and the inactive status must be adjusted to
901        * take this into account.
902        */
903       inactive &= ~active;
904
905       dp->active_transforms = active;
906       dp->ignored_transforms = inactive; /* excluding write-only transforms */
907
908       if (active == 0)
909          display_log(dp, INTERNAL_ERROR, "bad transform table");
910    }
911 }
912
913 static int
914 compare_read(struct display *dp, int applied_transforms)
915 {
916    /* Compare the png_info from read_ip with original_info */
917    size_t rowbytes;
918    png_uint_32 width, height;
919    int bit_depth, color_type;
920    int interlace_method, compression_method, filter_method;
921    const char *e = NULL;
922
923    png_get_IHDR(dp->read_pp, dp->read_ip, &width, &height, &bit_depth,
924       &color_type, &interlace_method, &compression_method, &filter_method);
925
926 #  define C(item) if (item != dp->item) \
927       display_log(dp, APP_WARNING, "IHDR " #item "(%lu) changed to %lu",\
928          (unsigned long)dp->item, (unsigned long)item), e = #item
929
930    /* The IHDR should be identical: */
931    C(width);
932    C(height);
933    C(bit_depth);
934    C(color_type);
935    C(interlace_method);
936    C(compression_method);
937    C(filter_method);
938
939    /* 'e' remains set to the name of the last thing changed: */
940    if (e)
941       display_log(dp, APP_ERROR, "IHDR changed (%s)", e);
942
943    /* All the chunks from the original PNG should be preserved in the output PNG
944     * because the PNG format has not been changed.
945     */
946    {
947       unsigned long chunks =
948          png_get_valid(dp->read_pp, dp->read_ip, 0xffffffff);
949       
950       if (chunks != dp->chunks)
951          display_log(dp, APP_FAIL, "PNG chunks changed from 0x%lx to 0x%lx",
952             (unsigned long)dp->chunks, chunks);
953    }
954
955    /* rowbytes should be the same */
956    rowbytes = png_get_rowbytes(dp->read_pp, dp->read_ip);
957
958    /* NOTE: on 64-bit systems this may trash the top bits of rowbytes,
959     * which could lead to weird error messages.
960     */
961    if (rowbytes != dp->original_rowbytes)
962       display_log(dp, APP_ERROR, "PNG rowbytes changed from %lu to %lu",
963          (unsigned long)dp->original_rowbytes, (unsigned long)rowbytes);
964
965    /* The rows should be the same too, unless the applied transforms includes
966     * the shift transform, in which case low bits may have been lost.
967     */
968    {
969       png_bytepp rows = png_get_rows(dp->read_pp, dp->read_ip);
970       unsigned int mask;  /* mask (if not zero) for the final byte */
971
972       if (bit_depth < 8)
973       {
974          /* Need the stray bits at the end, this depends only on the low bits
975           * of the image width; overflow does not matter.  If the width is an
976           * exact multiple of 8 bits this gives a mask of 0, not 0xff.
977           */
978          mask = 0xff & (0xff00 >> ((bit_depth * width) & 7));
979       }
980
981       else
982          mask = 0;
983
984       if (rows == NULL)
985          display_log(dp, LIBPNG_BUG, "png_get_rows returned NULL");
986
987       if ((applied_transforms & PNG_TRANSFORM_SHIFT) == 0 ||
988          (dp->active_transforms & PNG_TRANSFORM_SHIFT) == 0 ||
989          color_type == PNG_COLOR_TYPE_PALETTE)
990       {
991          unsigned long y;
992
993          for (y=0; y<height; ++y)
994          {
995             png_bytep row = rows[y];
996             png_bytep orig = dp->original_rows[y];
997
998             if (memcmp(row, orig, rowbytes-(mask != 0)) != 0 || (mask != 0 &&
999                ((row[rowbytes-1] & mask) != (orig[rowbytes-1] & mask))))
1000             {
1001                size_t x;
1002
1003                /* Find the first error */
1004                for (x=0; x<rowbytes-1; ++x) if (row[x] != orig[x])
1005                   break;
1006
1007                display_log(dp, APP_FAIL,
1008                   "byte(%lu,%lu) changed 0x%.2x -> 0x%.2x",
1009                   (unsigned long)x, (unsigned long)y, orig[x], row[x]);
1010                return 0; /* don't keep reporting failed rows on 'continue' */
1011             }
1012          }
1013       }
1014
1015       else
1016       {
1017          unsigned long y;
1018          int bpp;   /* bits-per-pixel then bytes-per-pixel */
1019          /* components are up to 8 bytes in size */
1020          png_byte sig_bits[8];
1021          png_color_8p sBIT;
1022
1023          if (png_get_sBIT(dp->read_pp, dp->read_ip, &sBIT) != PNG_INFO_sBIT)
1024             display_log(dp, INTERNAL_ERROR,
1025                "active shift transform but no sBIT in file");
1026
1027          switch (color_type)
1028          {
1029             case PNG_COLOR_TYPE_GRAY:
1030                sig_bits[0] = sBIT->gray;
1031                bpp = bit_depth;
1032                break;
1033
1034             case PNG_COLOR_TYPE_GA:
1035                sig_bits[0] = sBIT->gray;
1036                sig_bits[1] = sBIT->alpha;
1037                bpp = 2 * bit_depth;
1038                break;
1039
1040             case PNG_COLOR_TYPE_RGB:
1041                sig_bits[0] = sBIT->red;
1042                sig_bits[1] = sBIT->green;
1043                sig_bits[2] = sBIT->blue;
1044                bpp = 3 * bit_depth;
1045                break;
1046
1047             case PNG_COLOR_TYPE_RGBA:
1048                sig_bits[0] = sBIT->red;
1049                sig_bits[1] = sBIT->green;
1050                sig_bits[2] = sBIT->blue;
1051                sig_bits[3] = sBIT->alpha;
1052                bpp = 4 * bit_depth;
1053                break;
1054
1055             default:
1056                display_log(dp, LIBPNG_ERROR, "invalid colour type %d",
1057                   color_type);
1058                /*NOTREACHED*/
1059                bpp = 0;
1060                break;
1061          }
1062
1063          {
1064             int b;
1065
1066             for (b=0; 8*b<bpp; ++b)
1067             {
1068                /* libpng should catch this; if not there is a security issue
1069                 * because an app (like this one) may overflow an array. In fact
1070                 * libpng doesn't catch this at present.
1071                 */
1072                if (sig_bits[b] == 0 || sig_bits[b] > bit_depth/*!palette*/)
1073                   display_log(dp, LIBPNG_BUG,
1074                      "invalid sBIT[%u]  value %d returned for PNG bit depth %d",
1075                      b, sig_bits[b], bit_depth);
1076             }
1077          }
1078
1079          if (bpp < 8 && bpp != bit_depth)
1080          {
1081             /* sanity check; this is a grayscale PNG; something is wrong in the
1082              * code above.
1083              */
1084             display_log(dp, INTERNAL_ERROR, "invalid bpp %u for bit_depth %u",
1085                bpp, bit_depth);
1086          }
1087
1088          switch (bit_depth)
1089          {
1090             int b;
1091
1092             case 16: /* Two bytes per component, bit-endian */
1093                for (b = (bpp >> 4); b > 0; )
1094                {
1095                   unsigned int sig = (unsigned int)(0xffff0000 >> sig_bits[b]);
1096
1097                   sig_bits[2*b+1] = (png_byte)sig;
1098                   sig_bits[2*b+0] = (png_byte)(sig >> 8); /* big-endian */
1099                }
1100                break;
1101
1102             case 8: /* One byte per component */
1103                for (b=0; b*8 < bpp; ++b)
1104                   sig_bits[b] = (png_byte)(0xff00 >> sig_bits[b]);
1105                break;
1106
1107             case 1: /* allowed, but dumb */
1108                /* Value is 1 */
1109                sig_bits[0] = 0xff;
1110                break;
1111
1112             case 2: /* Replicate 4 times */
1113                /* Value is 1 or 2 */
1114                b = 0x3 & ((0x3<<2) >> sig_bits[0]);
1115                b |= b << 2;
1116                b |= b << 4;
1117                sig_bits[0] = (png_byte)b;
1118                break;
1119
1120             case 4: /* Relicate twice */
1121                /* Value is 1, 2, 3 or 4 */
1122                b = 0xf & ((0xf << 4) >> sig_bits[0]);
1123                b |= b << 4;
1124                sig_bits[0] = (png_byte)b;
1125                break;
1126
1127             default:
1128                display_log(dp, LIBPNG_BUG, "invalid bit depth %d", bit_depth);
1129                break;
1130          }
1131
1132          /* Convert bpp to bytes; this gives '1' for low-bit depth grayscale,
1133           * where there are multiple pixels per byte.
1134           */
1135          bpp = (bpp+7) >> 3;
1136
1137          /* The mask can be combined with sig_bits[0] */
1138          if (mask != 0)
1139          {
1140             mask &= sig_bits[0];
1141
1142             if (bpp != 1 || mask == 0)
1143                display_log(dp, INTERNAL_ERROR, "mask calculation error %u, %u",
1144                   bpp, mask);
1145          }
1146
1147          for (y=0; y<height; ++y)
1148          {
1149             png_bytep row = rows[y];
1150             png_bytep orig = dp->original_rows[y];
1151             unsigned long x;
1152
1153             for (x=0; x<(width-(mask!=0)); ++x)
1154             {
1155                int b;
1156
1157                for (b=0; b<bpp; ++b)
1158                {
1159                   if ((*row++ & sig_bits[b]) != (*orig++ & sig_bits[b]))
1160                   {
1161                      display_log(dp, APP_FAIL,
1162                         "significant bits at (%lu[%u],%lu) changed %.2x->%.2x",
1163                         x, b, y, orig[-1], row[-1]);
1164                      return 0;
1165                   }
1166                }
1167             }
1168
1169             if (mask != 0 && (*row & mask) != (*orig & mask))
1170             {
1171                display_log(dp, APP_FAIL,
1172                   "significant bits at (%lu[end],%lu) changed", x, y);
1173                return 0;
1174             }
1175          } /* for y */
1176       }
1177    }
1178
1179    return 1; /* compare succeeded */
1180 }
1181
1182 #ifdef PNG_WRITE_SUPPORTED
1183 static void
1184 buffer_write(struct display *dp, struct buffer *buffer, png_bytep data,
1185    png_size_t size)
1186    /* Generic write function used both from the write callback provided to
1187     * libpng and from the generic read code.
1188     */
1189 {
1190    /* Write the data into the buffer, adding buffers as required */
1191    struct buffer_list *last = buffer->last;
1192    size_t end_count = buffer->end_count;
1193
1194    while (size > 0)
1195    {
1196       size_t avail;
1197
1198       if (end_count >= sizeof last->buffer)
1199       {
1200          if (last->next == NULL)
1201          {
1202             last = buffer_extend(last);
1203
1204             if (last == NULL)
1205                display_log(dp, APP_ERROR, "out of memory saving file");
1206          }
1207
1208          else
1209             last = last->next;
1210
1211          buffer->last = last; /* avoid the need to rewrite every time */
1212          end_count = 0;
1213       }
1214
1215       avail = (sizeof last->buffer) - end_count;
1216       if (avail > size)
1217          avail = size;
1218
1219       memcpy(last->buffer + end_count, data, avail);
1220       end_count += avail;
1221       size -= avail;
1222       data += avail;
1223    }
1224
1225    buffer->end_count = end_count;
1226 }
1227
1228 static void PNGCBAPI
1229 write_function(png_structp pp, png_bytep data, png_size_t size)
1230 {
1231    buffer_write(get_dp(pp), get_buffer(pp), data, size);
1232 }
1233
1234 static void
1235 write_png(struct display *dp, png_infop ip, int transforms)
1236 {
1237    display_clean_write(dp); /* safety */
1238
1239    buffer_start_write(&dp->written_file);
1240    dp->operation = "write";
1241    dp->transforms = transforms;
1242
1243    dp->write_pp = png_create_write_struct(PNG_LIBPNG_VER_STRING, dp,
1244       display_error, display_warning);
1245
1246    if (dp->write_pp == NULL)
1247       display_log(dp, APP_ERROR, "failed to create write png_struct");
1248
1249    png_set_write_fn(dp->write_pp, &dp->written_file, write_function,
1250       NULL/*flush*/);
1251
1252 #  ifdef PNG_SET_USER_LIMITS_SUPPORTED
1253       /* Remove the user limits, if any */
1254       png_set_user_limits(dp->write_pp, 0x7fffffff, 0x7fffffff);
1255 #  endif
1256
1257    /* Certain transforms require the png_info to be zapped to allow the
1258     * transform to work correctly.
1259     */
1260    if (transforms & (PNG_TRANSFORM_PACKING|
1261                      PNG_TRANSFORM_STRIP_FILLER|
1262                      PNG_TRANSFORM_STRIP_FILLER_BEFORE))
1263    {
1264       int ct = dp->color_type;
1265
1266       if (transforms & (PNG_TRANSFORM_STRIP_FILLER|
1267                         PNG_TRANSFORM_STRIP_FILLER_BEFORE))
1268          ct &= ~PNG_COLOR_MASK_ALPHA;
1269
1270       png_set_IHDR(dp->write_pp, ip, dp->width, dp->height, dp->bit_depth, ct,
1271          dp->interlace_method, dp->compression_method, dp->filter_method);
1272    }
1273
1274    png_write_png(dp->write_pp, ip, transforms, NULL/*params*/);
1275
1276    /* Clean it on the way out - if control returns to the caller then the
1277     * written_file contains the required data.
1278     */
1279    display_clean_write(dp);
1280 }
1281 #endif /* WRITE_SUPPORTED */
1282
1283 static int
1284 skip_transform(struct display *dp, int tr)
1285    /* Helper to test for a bad combo and log it if it is skipped */
1286 {
1287    if ((dp->options & SKIP_BUGS) != 0 && is_bad_combo(tr))
1288    {
1289       /* Log this to stdout if logging is on, otherwise just do an information
1290        * display_log.
1291        */
1292       if ((dp->options & LOG_SKIPPED) != 0)
1293       {
1294          printf("SKIP: %s transforms ", dp->filename);
1295
1296          while (tr != 0)
1297          {
1298             int next = first_transform(tr);
1299             tr &= ~next;
1300
1301             printf("%s", transform_name(next));
1302             if (tr != 0)
1303                putchar('+');
1304          }
1305
1306          putchar('\n');
1307       }
1308
1309       else
1310          display_log(dp, INFORMATION, "%s: skipped known bad combo 0x%x",
1311             dp->filename, tr);
1312
1313       return 1; /* skip */
1314    }
1315
1316    return 0; /* don't skip */
1317 }
1318
1319 static void
1320 test_one_file(struct display *dp, const char *filename)
1321 {
1322    /* First cache the file and update the display original file
1323     * information for the new file.
1324     */
1325    dp->operation = "cache file";
1326    dp->transforms = 0;
1327    display_cache_file(dp, filename);
1328    update_display(dp);
1329
1330    /* First test: if there are options that should be ignored for this file
1331     * verify that they really are ignored.
1332     */
1333    if (dp->ignored_transforms != 0)
1334    {
1335       read_png(dp, &dp->original_file, "ignored transforms",
1336          dp->ignored_transforms);
1337
1338       /* The result should be identical to the original_rows */
1339       if (!compare_read(dp, 0/*transforms applied*/))
1340          return; /* no point testing more */
1341    }
1342
1343 #ifdef PNG_WRITE_SUPPORTED
1344    /* Second test: write the original PNG data out to a new file (to test the
1345     * write side) then read the result back in and make sure that it hasn't
1346     * changed.
1347     */
1348    dp->operation = "write";
1349    write_png(dp, dp->original_ip, 0/*transforms*/);
1350    read_png(dp, &dp->written_file, NULL, 0/*transforms*/);
1351    if (!compare_read(dp, 0/*transforms applied*/))
1352       return;
1353 #endif
1354
1355    /* Third test: the active options.  Test each in turn, or, with the
1356     * EXHAUSTIVE option, test all possible combinations.
1357     */
1358    {
1359       /* Use unsigned int here because the code below to increment through all
1360        * the possibilities exhaustively has to use a compare and that must be
1361        * unsigned, because some transforms are negative on a 16-bit system.
1362        */
1363       unsigned int active = dp->active_transforms;
1364       const int exhaustive = (dp->options & EXHAUSTIVE) != 0;
1365       unsigned int current = first_transform(active);
1366       unsigned int bad_transforms = 0;
1367       unsigned int bad_combo = ~0U;    /* bitwise AND of failing transforms */
1368       unsigned int bad_combo_list = 0; /* bitwise OR of failures */
1369
1370       for (;;)
1371       {
1372          read_png(dp, &dp->original_file, "active transforms", current);
1373
1374          /* If this involved any irreversible transformations then if we write
1375           * it out with just the reversible transformations and read it in again
1376           * with the same transforms we should get the same thing.  At present
1377           * this isn't done - it just seems like a waste of time and it would
1378           * require two sets of read png_struct/png_info.
1379           *
1380           * If there were no irreversible transformations then if we write it
1381           * out and read it back in again (without the reversible transforms)
1382           * we should get back to the place where we started.
1383           */
1384 #ifdef PNG_WRITE_SUPPORTED
1385          if ((current & write_transforms) == current)
1386          {
1387             /* All transforms reversible: write the PNG with the transformations
1388              * reversed, then read it back in with no transformations.  The
1389              * result should be the same as the original apart from the loss of
1390              * low order bits because of the SHIFT/sBIT transform.
1391              */
1392             dp->operation = "reversible transforms";
1393             write_png(dp, dp->read_ip, current);
1394
1395             /* And if this is read back in, because all the transformations were
1396              * reversible, the result should be the same.
1397              */
1398             read_png(dp, &dp->written_file, NULL, 0);
1399             if (!compare_read(dp, current/*for the SHIFT/sBIT transform*/))
1400             {
1401                /* This set of transforms failed.  If a single bit is set - if
1402                 * there is just one transform - don't include this in further
1403                 * 'exhaustive' tests.  Notice that each transform is tested on
1404                 * its own before testing combos in the exhaustive case.
1405                 */
1406                if (is_combo(current))
1407                {
1408                   bad_combo &= current;
1409                   bad_combo_list |= current;
1410                }
1411
1412                else
1413                   bad_transforms |= current;
1414             }
1415          }
1416 #endif
1417
1418          /* Now move to the next transform */
1419          if (exhaustive) /* all combinations */
1420          {
1421             unsigned int next = current;
1422
1423             do
1424             {
1425                if (next == read_transforms) /* Everything tested */
1426                   goto combo;
1427
1428                ++next;
1429             }  /* skip known bad combos if the relevant option is set; skip
1430                 * combos involving known bad single transforms in all cases.
1431                 */
1432             while (  (next & read_transforms) <= current
1433                   || (next & active) == 0 /* skip cases that do nothing */
1434                   || (next & bad_transforms) != 0
1435                   || skip_transform(dp, next));
1436
1437             assert((next & read_transforms) == next);
1438             current = next;
1439          }
1440
1441          else /* one at a time */
1442          {
1443             active &= ~current;
1444
1445             if (active == 0)
1446                goto combo;
1447
1448             current = first_transform(active);
1449          }
1450       }
1451
1452 combo:
1453       if (dp->options & FIND_BAD_COMBOS)
1454       {
1455          /* bad_combos identifies the combos that occur in all failing cases;
1456           * bad_combo_list identifies transforms that do not prevent the
1457           * failure.
1458           */
1459          if (bad_combo != ~0U)
1460             printf("%s[0x%x]: PROBLEM: 0x%x[0x%x] ANTIDOTE: 0x%x\n",
1461                dp->filename, active, bad_combo, bad_combo_list,
1462                rw_transforms & ~bad_combo_list);
1463
1464          else
1465             printf("%s: no %sbad combos found\n", dp->filename,
1466                (dp->options & SKIP_BUGS) ? "additional " : "");
1467       }
1468    }
1469 }
1470
1471 static int
1472 do_test(struct display *dp, const char *file)
1473    /* Exists solely to isolate the setjmp clobbers */
1474 {
1475    int ret = setjmp(dp->error_return);
1476
1477    if (ret == 0)
1478    {
1479       test_one_file(dp, file);
1480       return 0;
1481    }
1482
1483    else if (ret < ERRORS) /* shouldn't longjmp on warnings */
1484       display_log(dp, INTERNAL_ERROR, "unexpected return code %d", ret);
1485
1486    return ret;
1487 }
1488
1489 int
1490 main(const int argc, const char * const * const argv)
1491 {
1492    /* For each file on the command line test it with a range of transforms */
1493    int option_end, ilog = 0;
1494    struct display d;
1495
1496    validate_T();
1497    display_init(&d);
1498
1499    for (option_end=1; option_end<argc; ++option_end)
1500    {
1501       const char *name = argv[option_end];
1502
1503       if (strcmp(name, "--verbose") == 0)
1504          d.options = (d.options & ~LEVEL_MASK) | VERBOSE;
1505
1506       else if (strcmp(name, "--warnings") == 0)
1507          d.options = (d.options & ~LEVEL_MASK) | WARNINGS;
1508
1509       else if (strcmp(name, "--errors") == 0)
1510          d.options = (d.options & ~LEVEL_MASK) | ERRORS;
1511
1512       else if (strcmp(name, "--quiet") == 0)
1513          d.options = (d.options & ~LEVEL_MASK) | QUIET;
1514
1515       else if (strcmp(name, "--exhaustive") == 0)
1516          d.options |= EXHAUSTIVE;
1517
1518       else if (strcmp(name, "--fast") == 0)
1519          d.options &= ~EXHAUSTIVE;
1520
1521       else if (strcmp(name, "--strict") == 0)
1522          d.options |= STRICT;
1523
1524       else if (strcmp(name, "--relaxed") == 0)
1525          d.options &= ~STRICT;
1526
1527       else if (strcmp(name, "--log") == 0)
1528       {
1529          ilog = option_end; /* prevent display */
1530          d.options |= LOG;
1531       }
1532
1533       else if (strcmp(name, "--nolog") == 0)
1534          d.options &= ~LOG;
1535
1536       else if (strcmp(name, "--continue") == 0)
1537          d.options |= CONTINUE;
1538
1539       else if (strcmp(name, "--stop") == 0)
1540          d.options &= ~CONTINUE;
1541
1542       else if (strcmp(name, "--skip-bugs") == 0)
1543          d.options |= SKIP_BUGS;
1544
1545       else if (strcmp(name, "--test-all") == 0)
1546          d.options &= ~SKIP_BUGS;
1547
1548       else if (strcmp(name, "--log-skipped") == 0)
1549          d.options |= LOG_SKIPPED;
1550
1551       else if (strcmp(name, "--nolog-skipped") == 0)
1552          d.options &= ~LOG_SKIPPED;
1553
1554       else if (strcmp(name, "--find-bad-combos") == 0)
1555          d.options |= FIND_BAD_COMBOS;
1556
1557       else if (strcmp(name, "--nofind-bad-combos") == 0)
1558          d.options &= ~FIND_BAD_COMBOS;
1559
1560       else if (name[0] == '-' && name[1] == '-')
1561       {
1562          fprintf(stderr, "pngimage: %s: unknown option\n", name);
1563          return 99;
1564       }
1565
1566       else
1567          break; /* Not an option */
1568    }
1569
1570    {
1571       int i;
1572       int errors = 0;
1573
1574       for (i=option_end; i<argc; ++i)
1575       {
1576          {
1577             int ret = do_test(&d, argv[i]);
1578
1579             if (ret > QUIET) /* abort on user or internal error */
1580                return 99;
1581          }
1582
1583          /* Here on any return, including failures, except user/internal issues
1584           */
1585          {
1586             const int pass = (d.options & STRICT) ?
1587                RESULT_STRICT(d.results) : RESULT_RELAXED(d.results);
1588
1589             if (!pass)
1590                ++errors;
1591
1592             if (d.options & LOG)
1593             {
1594                int j;
1595
1596                printf("%s: pngimage ", pass ? "PASS" : "FAIL");
1597
1598                for (j=1; j<option_end; ++j) if (j != ilog)
1599                   printf("%s ", argv[j]);
1600
1601                printf("%s\n", d.filename);
1602             }
1603          }
1604
1605          display_clean(&d);
1606       }
1607
1608       return errors != 0;
1609    }
1610 }
1611 #else /* !PNG_INFO_IMAGE_SUPPORTED || !PNG_READ_SUPPORTED */
1612 int
1613 main(void)
1614 {
1615    fprintf(stderr, "pngimage: no support for png_read/write_image\n");
1616    return 77;
1617 }
1618 #endif