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