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