4 * Copyright (c) 2021 Cosmin Truta
5 * Copyright (c) 2015,2016 John Cunningham Bowler
7 * This code is released under the libpng license.
8 * For conditions of distribution and use, see the disclaimer
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
23 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
27 /* Define the following to use this test against your installed libpng, rather
28 * than the one being built here:
30 #ifdef PNG_FREESTANDING_TESTS
33 # include "../../png.h"
36 #ifndef PNG_SETJMP_SUPPORTED
37 # include <setjmp.h> /* because png.h did *not* include this */
40 /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
41 * a skipped test, in earlier versions we need to succeed on a skipped test, so:
43 #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
49 #if PNG_LIBPNG_VER < 10700
50 /* READ_PNG and WRITE_PNG were not defined, so: */
51 # ifdef PNG_INFO_IMAGE_SUPPORTED
52 # ifdef PNG_SEQUENTIAL_READ_SUPPORTED
53 # define PNG_READ_PNG_SUPPORTED
54 # endif /* SEQUENTIAL_READ */
55 # ifdef PNG_WRITE_SUPPORTED
56 # define PNG_WRITE_PNG_SUPPORTED
58 # endif /* INFO_IMAGE */
59 #endif /* pre 1.7.0 */
61 #ifdef PNG_READ_PNG_SUPPORTED
62 /* If a transform is valid on both read and write this implies that if the
63 * transform is applied to read it must also be applied on write to produce
64 * meaningful data. This is because these transforms when performed on read
65 * produce data with a memory format that does not correspond to a PNG format.
67 * Most of these transforms are invertible; after applying the transform on
68 * write the result is the original PNG data that would have would have been
69 * read if no transform were applied.
71 * The exception is _SHIFT, which destroys the low order bits marked as not
72 * significant in a PNG with the sBIT chunk.
74 * The following table lists, for each transform, the conditions under which it
75 * is expected to do anything. Conditions are defined as follows:
77 * 1) Color mask bits required - simply a mask to AND with color_type; one of
78 * these must be present for the transform to fire, except that 0 means
80 * 2) Color mask bits which must be absent - another mask - none of these must
82 * 3) Bit depths - a mask of component bit depths for the transform to fire.
83 * 4) 'read' - the transform works in png_read_png.
84 * 5) 'write' - the transform works in png_write_png.
85 * 6) PNG_INFO_chunk; a mask of the chunks that must be present for the
86 * transform to fire. All must be present - the requirement is that
87 * png_get_valid() & mask == mask, so if mask is 0 there is no requirement.
89 * The condition refers to the original image state - if multiple transforms are
90 * used together it is possible to cause a transform that wouldn't fire on the
91 * original image to fire.
93 static struct transform_info
97 png_uint_32 valid_chunks;
99 # define CHUNK_sBIT PNG_INFO_sBIT
100 # define CHUNK_tRNS PNG_INFO_tRNS
101 png_byte color_mask_required;
102 png_byte color_mask_absent;
103 # define COLOR_MASK_X 0
104 # define COLOR_MASK_P PNG_COLOR_MASK_PALETTE
105 # define COLOR_MASK_C PNG_COLOR_MASK_COLOR
106 # define COLOR_MASK_A PNG_COLOR_MASK_ALPHA
107 # define COLOR_MASK_ALL (PALETTE+COLOR+ALPHA) /* absent = gray, no alpha */
109 # define BD_ALL (1 + 2 + 4 + 8 + 16)
110 # define BD_PAL (1 + 2 + 4 + 8)
111 # define BD_LOW (1 + 2 + 4)
113 # define BD_TRUE (8+16) /* i.e. true-color depths */
115 # define TRANSFORM_R 1
116 # define TRANSFORM_W 2
117 # define TRANSFORM_RW 3
118 png_byte tested; /* the transform was tested somewhere */
121 /* List ALL the PNG_TRANSFORM_ macros here. Check for support using the READ
122 * macros; even if the transform is supported on write it cannot be tested
123 * without the read support.
125 # define T(name,chunk,cm_required,cm_absent,bd,when)\
126 { #name, PNG_TRANSFORM_ ## name, CHUNK_ ## chunk,\
127 COLOR_MASK_ ## cm_required, COLOR_MASK_ ## cm_absent, BD_ ## bd,\
128 TRANSFORM_ ## when, 0/*!tested*/ }
130 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
131 T(STRIP_16, NONE, X, X, 16, R),
132 /* drops the bottom 8 bits when bit depth is 16 */
134 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
135 T(STRIP_ALPHA, NONE, A, X, ALL, R),
136 /* removes the alpha channel if present */
138 #ifdef PNG_WRITE_PACK_SUPPORTED
139 # define TRANSFORM_RW_PACK TRANSFORM_RW
141 # define TRANSFORM_RW_PACK TRANSFORM_R
143 #ifdef PNG_READ_PACK_SUPPORTED
144 T(PACKING, NONE, X, X, LOW, RW_PACK),
145 /* unpacks low-bit-depth components into 1 byte per component on read,
146 * reverses this on write.
149 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
150 # define TRANSFORM_RW_PACKSWAP TRANSFORM_RW
152 # define TRANSFORM_RW_PACKSWAP TRANSFORM_R
154 #ifdef PNG_READ_PACKSWAP_SUPPORTED
155 T(PACKSWAP, NONE, X, X, LOW, RW_PACKSWAP),
156 /* reverses the order of low-bit-depth components packed into a byte */
158 #ifdef PNG_READ_EXPAND_SUPPORTED
159 T(EXPAND, NONE, P, X, ALL, R),
160 /* expands PLTE PNG files to RGB (no tRNS) or RGBA (tRNS) *
161 * Note that the 'EXPAND' transform does lots of different things: */
162 T(EXPAND, NONE, X, C, ALL, R),
163 /* expands grayscale PNG files to RGB, or RGBA */
164 T(EXPAND, tRNS, X, A, ALL, R),
165 /* expands the tRNS chunk in files without alpha */
167 #ifdef PNG_WRITE_INVERT_SUPPORTED
168 # define TRANSFORM_RW_INVERT TRANSFORM_RW
170 # define TRANSFORM_RW_INVERT TRANSFORM_R
172 #ifdef PNG_READ_INVERT_SUPPORTED
173 T(INVERT_MONO, NONE, X, C, ALL, RW_INVERT),
174 /* converts gray-scale components to 1..0 from 0..1 */
176 #ifdef PNG_WRITE_SHIFT_SUPPORTED
177 # define TRANSFORM_RW_SHIFT TRANSFORM_RW
179 # define TRANSFORM_RW_SHIFT TRANSFORM_R
181 #ifdef PNG_READ_SHIFT_SUPPORTED
182 T(SHIFT, sBIT, X, X, ALL, RW_SHIFT),
183 /* reduces component values to the original range based on the sBIT chunk,
184 * this is only partially reversible - the low bits are lost and cannot be
185 * recovered on write. In fact write code replicates the bits to generate
186 * new low-order bits.
189 #ifdef PNG_WRITE_BGR_SUPPORTED
190 # define TRANSFORM_RW_BGR TRANSFORM_RW
192 # define TRANSFORM_RW_BGR TRANSFORM_R
194 #ifdef PNG_READ_BGR_SUPPORTED
195 T(BGR, NONE, C, P, TRUE, RW_BGR),
196 /* reverses the rgb component values of true-color pixels */
198 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
199 # define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_RW
201 # define TRANSFORM_RW_SWAP_ALPHA TRANSFORM_R
203 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
204 T(SWAP_ALPHA, NONE, A, X, TRUE, RW_SWAP_ALPHA),
205 /* swaps the alpha channel of RGBA or GA pixels to the front - ARGB or
206 * AG, on write reverses the process.
209 #ifdef PNG_WRITE_SWAP_SUPPORTED
210 # define TRANSFORM_RW_SWAP TRANSFORM_RW
212 # define TRANSFORM_RW_SWAP TRANSFORM_R
214 #ifdef PNG_READ_SWAP_SUPPORTED
215 T(SWAP_ENDIAN, NONE, X, P, 16, RW_SWAP),
216 /* byte-swaps 16-bit component values */
218 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
219 # define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_RW
221 # define TRANSFORM_RW_INVERT_ALPHA TRANSFORM_R
223 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
224 T(INVERT_ALPHA, NONE, A, X, TRUE, RW_INVERT_ALPHA),
225 /* converts an alpha channel from 0..1 to 1..0 */
227 #ifdef PNG_WRITE_FILLER_SUPPORTED
228 T(STRIP_FILLER_BEFORE, NONE, A, P, TRUE, W), /* 'A' for a filler! */
229 /* on write skips a leading filler channel; testing requires data with a
230 * filler channel so this is produced from RGBA or GA images by removing
231 * the 'alpha' flag from the color type in place.
233 T(STRIP_FILLER_AFTER, NONE, A, P, TRUE, W),
234 /* on write strips a trailing filler channel */
236 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
237 T(GRAY_TO_RGB, NONE, X, C, ALL, R),
238 /* expands grayscale images to RGB, also causes the palette part of
239 * 'EXPAND' to happen. Low bit depth grayscale images are expanded to
240 * 8-bits per component and no attempt is made to convert the image to a
241 * palette image. While this transform is partially reversible
242 * png_write_png does not currently support this.
244 T(GRAY_TO_RGB, NONE, P, X, ALL, R),
245 /* The 'palette' side effect mentioned above; a bit bogus but this is the
246 * way the libpng code works.
249 #ifdef PNG_READ_EXPAND_16_SUPPORTED
250 T(EXPAND_16, NONE, X, X, PAL, R),
251 /* expands images to 16-bits per component, as a side effect expands
252 * palette images to RGB and expands the tRNS chunk if present, so it can
253 * modify 16-bit per component images as well:
255 T(EXPAND_16, tRNS, X, A, 16, R),
256 /* side effect of EXPAND_16 - expands the tRNS chunk in an RGB or G 16-bit
260 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
261 T(SCALE_16, NONE, X, X, 16, R),
262 /* scales 16-bit components to 8-bits. */
265 { NULL /*name*/, 0, 0, 0, 0, 0, 0, 0/*!tested*/ }
270 #define ARRAY_SIZE(a) ((sizeof a)/(sizeof a[0]))
271 #define TTABLE_SIZE ARRAY_SIZE(transform_info)
273 /* Some combinations of options that should be reversible are not; these cases
276 static int known_bad_combos[][2] =
278 /* problem, antidote */
279 { PNG_TRANSFORM_SHIFT | PNG_TRANSFORM_INVERT_ALPHA, 0/*antidote*/ }
283 is_combo(int transforms)
285 return transforms & (transforms-1); /* non-zero if more than one set bit */
289 first_transform(int transforms)
291 return transforms & -transforms; /* lowest set bit */
295 is_bad_combo(int transforms)
299 for (i=0; i<ARRAY_SIZE(known_bad_combos); ++i)
301 int combo = known_bad_combos[i][0];
303 if ((combo & transforms) == combo &&
304 (transforms & known_bad_combos[i][1]) == 0)
308 return 0; /* combo is ok */
312 transform_name(int t)
313 /* The name, if 't' has multiple bits set the name of the lowest set bit is
319 t &= -t; /* first set bit */
321 for (i=0; i<TTABLE_SIZE; ++i)
322 if (transform_info[i].name != NULL)
323 if ((transform_info[i].transform & t) != 0)
324 return transform_info[i].name;
326 return "invalid transform";
329 /* Variables calculated by validate_T below and used to record all the supported
330 * transforms. Need (unsigned int) here because of the places where these
331 * values are used (unsigned compares in the 'exhaustive' iterator.)
333 static unsigned int read_transforms, write_transforms, rw_transforms;
337 /* Validate the above table - this just builds the above values */
341 for (i=0; i<TTABLE_SIZE; ++i)
343 if (transform_info[i].name != NULL)
345 if (transform_info[i].when & TRANSFORM_R)
346 read_transforms |= transform_info[i].transform;
348 if (transform_info[i].when & TRANSFORM_W)
349 write_transforms |= transform_info[i].transform;
353 /* Reversible transforms are those which are supported on both read and
356 rw_transforms = read_transforms & write_transforms;
359 /* FILE DATA HANDLING
360 * The original file is cached in memory. During write the output file is
363 * In both cases the file data is held in a linked list of buffers - not all
364 * of these are in use at any time.
366 #define NEW(type) ((type *)malloc(sizeof (type)))
367 #define DELETE(ptr) (free(ptr))
371 struct buffer_list *next; /* next buffer in list */
372 png_byte buffer[1024]; /* the actual buffer */
377 struct buffer_list *last; /* last buffer in use */
378 size_t end_count; /* bytes in the last buffer */
379 struct buffer_list *current; /* current buffer being read */
380 size_t read_count; /* count of bytes read from current */
381 struct buffer_list first; /* the very first buffer */
385 buffer_init(struct buffer *buffer)
386 /* Call this only once for a given buffer */
388 buffer->first.next = NULL;
390 buffer->current = NULL;
394 buffer_destroy_list(struct buffer_list *list)
398 struct buffer_list *next = list->next;
400 buffer_destroy_list(next);
405 buffer_destroy(struct buffer *buffer)
407 struct buffer_list *list = buffer->first.next;
409 buffer_destroy_list(list);
412 #ifdef PNG_WRITE_PNG_SUPPORTED
414 buffer_start_write(struct buffer *buffer)
416 buffer->last = &buffer->first;
417 buffer->end_count = 0;
418 buffer->current = NULL;
423 buffer_start_read(struct buffer *buffer)
425 buffer->current = &buffer->first;
426 buffer->read_count = 0;
429 #ifdef ENOMEM /* required by POSIX 1003.1 */
430 # define MEMORY ENOMEM
432 # define MEMORY ERANGE /* required by ANSI-C */
434 static struct buffer *
435 get_buffer(png_structp pp)
436 /* Used from libpng callbacks to get the current buffer */
438 return (struct buffer*)png_get_io_ptr(pp);
441 static struct buffer_list *
442 buffer_extend(struct buffer_list *current)
444 struct buffer_list *add;
446 assert(current->next == NULL);
448 add = NEW(struct buffer_list);
458 /* Load a buffer from a file; does the equivalent of buffer_start_write. On a
459 * read error returns an errno value, else returns 0.
462 buffer_from_file(struct buffer *buffer, FILE *fp)
464 struct buffer_list *last = &buffer->first;
469 size_t r = fread(last->buffer+count, 1/*size*/,
470 (sizeof last->buffer)-count, fp);
476 if (count >= sizeof last->buffer)
478 assert(count == sizeof last->buffer);
481 if (last->next == NULL)
483 last = buffer_extend(last);
493 else /* fread failed - probably end of file */
498 buffer->end_count = count;
499 return 0; /* no error */
502 /* Some kind of funky error; errno should be non-zero */
503 return errno == 0 ? ERANGE : errno;
508 /* This structure is used to control the test of a single file. */
511 VERBOSE, /* switches on all messages */
513 WARNINGS, /* switches on warnings */
516 ERRORS, /* just errors */
517 APP_FAIL, /* continuable error - no need to longjmp */
518 LIBPNG_ERROR, /* this and higher cause a longjmp */
519 LIBPNG_BUG, /* erroneous behavior in libpng */
520 APP_ERROR, /* such as out-of-memory in a callback */
521 QUIET, /* no normal messages */
522 USER_ERROR, /* such as file-not-found */
525 #define LEVEL_MASK 0xf /* where the level is in 'options' */
527 #define EXHAUSTIVE 0x010 /* Test all combinations of active options */
528 #define STRICT 0x020 /* Fail on warnings as well as errors */
529 #define LOG 0x040 /* Log pass/fail to stdout */
530 #define CONTINUE 0x080 /* Continue on APP_FAIL errors */
531 #define SKIP_BUGS 0x100 /* Skip over known bugs */
532 #define LOG_SKIPPED 0x200 /* Log skipped bugs */
533 #define FIND_BAD_COMBOS 0x400 /* Attempt to deduce bad combos */
534 #define LIST_COMBOS 0x800 /* List combos by name */
536 /* Result masks apply to the result bits in the 'results' field below; these
537 * bits are simple 1U<<error_level. A pass requires either nothing worse than
538 * warnings (--relaxes) or nothing worse than information (--strict)
540 #define RESULT_STRICT(r) (((r) & ~((1U<<WARNINGS)-1)) == 0)
541 #define RESULT_RELAXED(r) (((r) & ~((1U<<ERRORS)-1)) == 0)
545 jmp_buf error_return; /* Where to go to on error */
547 const char *filename; /* The name of the original file */
548 const char *operation; /* Operation being performed */
549 int transforms; /* Transform used in operation */
550 png_uint_32 options; /* See display_log below */
551 png_uint_32 results; /* A mask of errors seen */
554 png_structp original_pp; /* used on the original read */
555 png_infop original_ip; /* set by the original read */
557 size_t original_rowbytes; /* of the original rows: */
558 png_bytepp original_rows; /* from the original read */
560 /* Original chunks valid */
563 /* Original IHDR information */
568 int interlace_method;
569 int compression_method;
572 /* Derived information for the original image. */
573 int active_transforms; /* transforms that do something on read */
574 int ignored_transforms; /* transforms that should do nothing */
576 /* Used on a read, both the original read and when validating a written
582 # ifdef PNG_WRITE_PNG_SUPPORTED
583 /* Used to write a new image (the original info_ptr is used) */
584 png_structp write_pp;
585 struct buffer written_file; /* where the file gets written */
588 struct buffer original_file; /* Data read from the original file */
592 display_init(struct display *dp)
593 /* Call this only once right at the start to initialize the control
594 * structure, the (struct buffer) lists are maintained across calls - the
595 * memory is not freed.
598 memset(dp, 0, sizeof *dp);
599 dp->options = WARNINGS; /* default to !verbose, !quiet */
601 dp->operation = NULL;
602 dp->original_pp = NULL;
603 dp->original_ip = NULL;
604 dp->original_rows = NULL;
607 buffer_init(&dp->original_file);
609 # ifdef PNG_WRITE_PNG_SUPPORTED
611 buffer_init(&dp->written_file);
616 display_clean_read(struct display *dp)
618 if (dp->read_pp != NULL)
619 png_destroy_read_struct(&dp->read_pp, &dp->read_ip, NULL);
622 #ifdef PNG_WRITE_PNG_SUPPORTED
624 display_clean_write(struct display *dp)
626 if (dp->write_pp != NULL)
627 png_destroy_write_struct(&dp->write_pp, NULL);
632 display_clean(struct display *dp)
634 # ifdef PNG_WRITE_PNG_SUPPORTED
635 display_clean_write(dp);
637 display_clean_read(dp);
639 dp->original_rowbytes = 0;
640 dp->original_rows = NULL;
643 png_destroy_read_struct(&dp->original_pp, &dp->original_ip, NULL);
644 /* leave the filename for error detection */
645 dp->results = 0; /* reset for next time */
649 display_destroy(struct display *dp)
651 /* Release any memory held in the display. */
652 # ifdef PNG_WRITE_PNG_SUPPORTED
653 buffer_destroy(&dp->written_file);
656 buffer_destroy(&dp->original_file);
659 static struct display *
660 get_dp(png_structp pp)
661 /* The display pointer is always stored in the png_struct error pointer */
663 struct display *dp = (struct display*)png_get_error_ptr(pp);
667 fprintf(stderr, "pngimage: internal error (no display)\n");
668 exit(99); /* prevents a crash */
676 # define VGATTR __attribute__((__format__ (__printf__,3,4)))
677 /* Required to quiet GNUC warnings when the compiler sees a stdarg function
678 * that calls one of the stdio v APIs.
684 display_log(struct display *dp, error_level level, const char *fmt, ...)
685 /* 'level' is as above, fmt is a stdio style format string. This routine
686 * does not return if level is above LIBPNG_WARNING
689 dp->results |= 1U << level;
691 if (level > (error_level)(dp->options & LEVEL_MASK))
698 case INFORMATION: lp = "information"; break;
699 case LIBPNG_WARNING: lp = "warning(libpng)"; break;
700 case APP_WARNING: lp = "warning(pngimage)"; break;
701 case APP_FAIL: lp = "error(continuable)"; break;
702 case LIBPNG_ERROR: lp = "error(libpng)"; break;
703 case LIBPNG_BUG: lp = "bug(libpng)"; break;
704 case APP_ERROR: lp = "error(pngimage)"; break;
705 case USER_ERROR: lp = "error(user)"; break;
707 case INTERNAL_ERROR: /* anything unexpected is an internal error: */
708 case VERBOSE: case WARNINGS: case ERRORS: case QUIET:
709 default: lp = "bug(pngimage)"; break;
712 fprintf(stderr, "%s: %s: %s",
713 dp->filename != NULL ? dp->filename : "<stdin>", lp, dp->operation);
715 if (dp->transforms != 0)
717 int tr = dp->transforms;
721 if (dp->options & LIST_COMBOS)
725 fprintf(stderr, "(");
732 int trz = trx & -trx;
734 if (start) fprintf(stderr, "+");
735 fprintf(stderr, "%s", transform_name(trz));
742 fprintf(stderr, "-");
743 fprintf(stderr, ")");
747 fprintf(stderr, "(0x%x)", tr);
751 fprintf(stderr, "(%s)", transform_name(tr));
754 fprintf(stderr, ": ");
757 vfprintf(stderr, fmt, ap);
762 /* else do not output any message */
764 /* Errors cause this routine to exit to the fail code */
765 if (level > APP_FAIL || (level > ERRORS && !(dp->options & CONTINUE)))
766 longjmp(dp->error_return, level);
769 /* error handler callbacks for libpng */
771 display_warning(png_structp pp, png_const_charp warning)
773 display_log(get_dp(pp), LIBPNG_WARNING, "%s", warning);
777 display_error(png_structp pp, png_const_charp error)
779 struct display *dp = get_dp(pp);
781 display_log(dp, LIBPNG_ERROR, "%s", error);
785 display_cache_file(struct display *dp, const char *filename)
786 /* Does the initial cache of the file. */
791 dp->filename = filename;
793 if (filename != NULL)
795 fp = fopen(filename, "rb");
797 display_log(dp, USER_ERROR, "open failed: %s", strerror(errno));
803 ret = buffer_from_file(&dp->original_file, fp);
808 display_log(dp, APP_ERROR, "read failed: %s", strerror(ret));
812 buffer_read(struct display *dp, struct buffer *bp, png_bytep data,
815 struct buffer_list *last = bp->current;
816 size_t read_count = bp->read_count;
823 (last == bp->last && read_count >= bp->end_count))
825 display_log(dp, USER_ERROR, "file truncated (%lu bytes)",
826 (unsigned long)size);
831 else if (read_count >= sizeof last->buffer)
833 /* Move to the next buffer: */
836 bp->current = last; /* Avoid update outside the loop */
838 /* And do a sanity check (the EOF case is caught above) */
841 display_log(dp, INTERNAL_ERROR, "damaged buffer list");
847 avail = (sizeof last->buffer) - read_count;
851 memcpy(data, last->buffer + read_count, avail);
857 bp->read_count = read_count;
861 read_function(png_structp pp, png_bytep data, size_t size)
863 buffer_read(get_dp(pp), get_buffer(pp), data, size);
867 read_png(struct display *dp, struct buffer *bp, const char *operation,
873 /* This cleans out any previous read and sets operation and transforms to
876 display_clean_read(dp);
878 if (operation != NULL) /* else this is a verify and do not overwrite info */
880 dp->operation = operation;
881 dp->transforms = transforms;
884 dp->read_pp = pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, dp,
885 display_error, display_warning);
887 display_log(dp, LIBPNG_ERROR, "failed to create read struct");
889 /* The png_read_png API requires us to make the info struct, but it does the
890 * call to png_read_info.
892 dp->read_ip = ip = png_create_info_struct(pp);
894 display_log(dp, LIBPNG_ERROR, "failed to create info struct");
896 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
897 /* Remove the user limits, if any */
898 png_set_user_limits(pp, 0x7fffffff, 0x7fffffff);
901 /* Set the IO handling */
902 buffer_start_read(bp);
903 png_set_read_fn(pp, bp, read_function);
905 png_read_png(pp, ip, transforms, NULL/*params*/);
907 #if 0 /* crazy debugging */
909 png_bytep pr = png_get_rows(pp, ip)[0];
910 size_t rb = png_get_rowbytes(pp, ip);
914 fprintf(stderr, "%.4x %2d (%3lu bytes):", transforms, png_get_bit_depth(pp,ip), (unsigned long)rb);
916 for (cb=0; cb<rb; ++cb)
917 fputc(c, stderr), fprintf(stderr, "%.2x", pr[cb]), c='.';
925 update_display(struct display *dp)
926 /* called once after the first read to update all the info, original_pp and
927 * original_ip must have been filled in.
933 /* Now perform the initial read with a 0 transform. */
934 read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
936 /* Move the result to the 'original' fields */
937 dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
938 dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
940 dp->original_rowbytes = png_get_rowbytes(pp, ip);
941 if (dp->original_rowbytes == 0)
942 display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
944 dp->chunks = png_get_valid(pp, ip, 0xffffffff);
945 if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
946 display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
948 dp->original_rows = png_get_rows(pp, ip);
949 if (dp->original_rows == NULL)
950 display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
952 if (!png_get_IHDR(pp, ip,
953 &dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
954 &dp->interlace_method, &dp->compression_method, &dp->filter_method))
955 display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
957 /* 'active' transforms are discovered based on the original image format;
958 * running one active transform can activate others. At present the code
959 * does not attempt to determine the closure.
962 png_uint_32 chunks = dp->chunks;
963 int active = 0, inactive = 0;
964 int ct = dp->color_type;
965 int bd = dp->bit_depth;
968 for (i=0; i<TTABLE_SIZE; ++i)
970 if (transform_info[i].name != NULL)
972 int transform = transform_info[i].transform;
974 if ((transform_info[i].valid_chunks == 0 ||
975 (transform_info[i].valid_chunks & chunks) != 0) &&
976 (transform_info[i].color_mask_required & ct) ==
977 transform_info[i].color_mask_required &&
978 (transform_info[i].color_mask_absent & ct) == 0 &&
979 (transform_info[i].bit_depths & bd) != 0 &&
980 (transform_info[i].when & TRANSFORM_R) != 0)
983 else if ((transform_info[i].when & TRANSFORM_R) != 0)
984 inactive |= transform;
988 /* Some transforms appear multiple times in the table; the 'active' status
989 * is the logical OR of these and the inactive status must be adjusted to
990 * take this into account.
994 dp->active_transforms = active;
995 dp->ignored_transforms = inactive; /* excluding write-only transforms */
1000 compare_read(struct display *dp, int applied_transforms)
1002 /* Compare the png_info from read_ip with original_info */
1004 png_uint_32 width, height;
1005 int bit_depth, color_type;
1006 int interlace_method, compression_method, filter_method;
1007 const char *e = NULL;
1009 if (!png_get_IHDR(dp->read_pp, dp->read_ip, &width, &height, &bit_depth,
1010 &color_type, &interlace_method, &compression_method, &filter_method))
1011 display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
1013 # define C(item) if (item != dp->item) \
1014 display_log(dp, APP_WARNING, "IHDR " #item "(%lu) changed to %lu",\
1015 (unsigned long)dp->item, (unsigned long)item), e = #item
1017 /* The IHDR should be identical: */
1022 C(interlace_method);
1023 C(compression_method);
1026 /* 'e' remains set to the name of the last thing changed: */
1028 display_log(dp, APP_ERROR, "IHDR changed (%s)", e);
1030 /* All the chunks from the original PNG should be preserved in the output PNG
1031 * because the PNG format has not been changed.
1034 unsigned long chunks =
1035 png_get_valid(dp->read_pp, dp->read_ip, 0xffffffff);
1037 if (chunks != dp->chunks)
1038 display_log(dp, APP_FAIL, "PNG chunks changed from 0x%lx to 0x%lx",
1039 (unsigned long)dp->chunks, chunks);
1042 /* rowbytes should be the same */
1043 rowbytes = png_get_rowbytes(dp->read_pp, dp->read_ip);
1045 /* NOTE: on 64-bit systems this may trash the top bits of rowbytes,
1046 * which could lead to weird error messages.
1048 if (rowbytes != dp->original_rowbytes)
1049 display_log(dp, APP_ERROR, "PNG rowbytes changed from %lu to %lu",
1050 (unsigned long)dp->original_rowbytes, (unsigned long)rowbytes);
1052 /* The rows should be the same too, unless the applied transforms includes
1053 * the shift transform, in which case low bits may have been lost.
1056 png_bytepp rows = png_get_rows(dp->read_pp, dp->read_ip);
1057 unsigned int mask; /* mask (if not zero) for the final byte */
1061 /* Need the stray bits at the end, this depends only on the low bits
1062 * of the image width; overflow does not matter. If the width is an
1063 * exact multiple of 8 bits this gives a mask of 0, not 0xff.
1065 mask = 0xff & (0xff00 >> ((bit_depth * width) & 7));
1072 display_log(dp, LIBPNG_BUG, "png_get_rows returned NULL");
1074 if ((applied_transforms & PNG_TRANSFORM_SHIFT) == 0 ||
1075 (dp->active_transforms & PNG_TRANSFORM_SHIFT) == 0 ||
1076 color_type == PNG_COLOR_TYPE_PALETTE)
1080 for (y=0; y<height; ++y)
1082 png_bytep row = rows[y];
1083 png_bytep orig = dp->original_rows[y];
1085 if (memcmp(row, orig, rowbytes-(mask != 0)) != 0 || (mask != 0 &&
1086 ((row[rowbytes-1] & mask) != (orig[rowbytes-1] & mask))))
1090 /* Find the first error */
1091 for (x=0; x<rowbytes-1; ++x)
1092 if (row[x] != orig[x])
1095 display_log(dp, APP_FAIL,
1096 "byte(%lu,%lu) changed 0x%.2x -> 0x%.2x",
1097 (unsigned long)x, (unsigned long)y, orig[x], row[x]);
1098 return 0; /* don't keep reporting failed rows on 'continue' */
1104 # ifdef PNG_sBIT_SUPPORTED
1107 int bpp; /* bits-per-pixel then bytes-per-pixel */
1108 /* components are up to 8 bytes in size */
1109 png_byte sig_bits[8];
1112 if (png_get_sBIT(dp->read_pp, dp->read_ip, &sBIT) != PNG_INFO_sBIT)
1113 display_log(dp, INTERNAL_ERROR,
1114 "active shift transform but no sBIT in file");
1118 case PNG_COLOR_TYPE_GRAY:
1119 sig_bits[0] = sBIT->gray;
1123 case PNG_COLOR_TYPE_GA:
1124 sig_bits[0] = sBIT->gray;
1125 sig_bits[1] = sBIT->alpha;
1126 bpp = 2 * bit_depth;
1129 case PNG_COLOR_TYPE_RGB:
1130 sig_bits[0] = sBIT->red;
1131 sig_bits[1] = sBIT->green;
1132 sig_bits[2] = sBIT->blue;
1133 bpp = 3 * bit_depth;
1136 case PNG_COLOR_TYPE_RGBA:
1137 sig_bits[0] = sBIT->red;
1138 sig_bits[1] = sBIT->green;
1139 sig_bits[2] = sBIT->blue;
1140 sig_bits[3] = sBIT->alpha;
1141 bpp = 4 * bit_depth;
1145 display_log(dp, LIBPNG_ERROR, "invalid colour type %d",
1148 memset(sig_bits, 0, sizeof(sig_bits));
1156 for (b=0; 8*b<bpp; ++b)
1158 /* libpng should catch this; if not there is a security issue
1159 * because an app (like this one) may overflow an array. In fact
1160 * libpng doesn't catch this at present.
1162 if (sig_bits[b] == 0 || sig_bits[b] > bit_depth/*!palette*/)
1163 display_log(dp, LIBPNG_BUG,
1164 "invalid sBIT[%u] value %d returned for PNG bit depth %d",
1165 b, sig_bits[b], bit_depth);
1169 if (bpp < 8 && bpp != bit_depth)
1171 /* sanity check; this is a grayscale PNG; something is wrong in the
1174 display_log(dp, INTERNAL_ERROR, "invalid bpp %u for bit_depth %u",
1182 case 16: /* Two bytes per component, big-endian */
1183 for (b = (bpp >> 4); b > 0; --b)
1185 unsigned int sig = (unsigned int)(0xffff0000 >> sig_bits[b]);
1187 sig_bits[2*b+1] = (png_byte)sig;
1188 sig_bits[2*b+0] = (png_byte)(sig >> 8); /* big-endian */
1192 case 8: /* One byte per component */
1193 for (b=0; b*8 < bpp; ++b)
1194 sig_bits[b] = (png_byte)(0xff00 >> sig_bits[b]);
1197 case 1: /* allowed, but dumb */
1202 case 2: /* Replicate 4 times */
1203 /* Value is 1 or 2 */
1204 b = 0x3 & ((0x3<<2) >> sig_bits[0]);
1207 sig_bits[0] = (png_byte)b;
1210 case 4: /* Replicate twice */
1211 /* Value is 1, 2, 3 or 4 */
1212 b = 0xf & ((0xf << 4) >> sig_bits[0]);
1214 sig_bits[0] = (png_byte)b;
1218 display_log(dp, LIBPNG_BUG, "invalid bit depth %d", bit_depth);
1222 /* Convert bpp to bytes; this gives '1' for low-bit depth grayscale,
1223 * where there are multiple pixels per byte.
1227 /* The mask can be combined with sig_bits[0] */
1230 mask &= sig_bits[0];
1232 if (bpp != 1 || mask == 0)
1233 display_log(dp, INTERNAL_ERROR, "mask calculation error %u, %u",
1237 for (y=0; y<height; ++y)
1239 png_bytep row = rows[y];
1240 png_bytep orig = dp->original_rows[y];
1243 for (x=0; x<(width-(mask!=0)); ++x)
1247 for (b=0; b<bpp; ++b)
1249 if ((*row++ & sig_bits[b]) != (*orig++ & sig_bits[b]))
1251 display_log(dp, APP_FAIL,
1252 "significant bits at (%lu[%u],%lu) changed %.2x->%.2x",
1253 x, b, y, orig[-1], row[-1]);
1259 if (mask != 0 && (*row & mask) != (*orig & mask))
1261 display_log(dp, APP_FAIL,
1262 "significant bits at (%lu[end],%lu) changed", x, y);
1268 display_log(dp, INTERNAL_ERROR,
1269 "active shift transform but no sBIT support");
1273 return 1; /* compare succeeded */
1276 #ifdef PNG_WRITE_PNG_SUPPORTED
1278 buffer_write(struct display *dp, struct buffer *buffer, png_bytep data,
1280 /* Generic write function used both from the write callback provided to
1281 * libpng and from the generic read code.
1284 /* Write the data into the buffer, adding buffers as required */
1285 struct buffer_list *last = buffer->last;
1286 size_t end_count = buffer->end_count;
1292 if (end_count >= sizeof last->buffer)
1294 if (last->next == NULL)
1296 last = buffer_extend(last);
1299 display_log(dp, APP_ERROR, "out of memory saving file");
1305 buffer->last = last; /* avoid the need to rewrite every time */
1309 avail = (sizeof last->buffer) - end_count;
1313 memcpy(last->buffer + end_count, data, avail);
1319 buffer->end_count = end_count;
1322 static void PNGCBAPI
1323 write_function(png_structp pp, png_bytep data, size_t size)
1325 buffer_write(get_dp(pp), get_buffer(pp), data, size);
1329 write_png(struct display *dp, png_infop ip, int transforms)
1331 display_clean_write(dp); /* safety */
1333 buffer_start_write(&dp->written_file);
1334 dp->operation = "write";
1335 dp->transforms = transforms;
1337 dp->write_pp = png_create_write_struct(PNG_LIBPNG_VER_STRING, dp,
1338 display_error, display_warning);
1340 if (dp->write_pp == NULL)
1341 display_log(dp, APP_ERROR, "failed to create write png_struct");
1343 png_set_write_fn(dp->write_pp, &dp->written_file, write_function,
1346 # ifdef PNG_SET_USER_LIMITS_SUPPORTED
1347 /* Remove the user limits, if any */
1348 png_set_user_limits(dp->write_pp, 0x7fffffff, 0x7fffffff);
1351 /* Certain transforms require the png_info to be zapped to allow the
1352 * transform to work correctly.
1354 if (transforms & (PNG_TRANSFORM_PACKING|
1355 PNG_TRANSFORM_STRIP_FILLER|
1356 PNG_TRANSFORM_STRIP_FILLER_BEFORE))
1358 int ct = dp->color_type;
1360 if (transforms & (PNG_TRANSFORM_STRIP_FILLER|
1361 PNG_TRANSFORM_STRIP_FILLER_BEFORE))
1362 ct &= ~PNG_COLOR_MASK_ALPHA;
1364 png_set_IHDR(dp->write_pp, ip, dp->width, dp->height, dp->bit_depth, ct,
1365 dp->interlace_method, dp->compression_method, dp->filter_method);
1368 png_write_png(dp->write_pp, ip, transforms, NULL/*params*/);
1370 /* Clean it on the way out - if control returns to the caller then the
1371 * written_file contains the required data.
1373 display_clean_write(dp);
1375 #endif /* WRITE_PNG */
1378 skip_transform(struct display *dp, int tr)
1379 /* Helper to test for a bad combo and log it if it is skipped */
1381 if ((dp->options & SKIP_BUGS) != 0 && is_bad_combo(tr))
1383 /* Log this to stdout if logging is on, otherwise just do an information
1386 if ((dp->options & LOG_SKIPPED) != 0)
1388 printf("SKIP: %s transforms ", dp->filename);
1392 int next = first_transform(tr);
1395 printf("%s", transform_name(next));
1404 display_log(dp, INFORMATION, "%s: skipped known bad combo 0x%x",
1407 return 1; /* skip */
1410 return 0; /* don't skip */
1414 test_one_file(struct display *dp, const char *filename)
1416 /* First cache the file and update the display original file
1417 * information for the new file.
1419 dp->operation = "cache file";
1421 display_cache_file(dp, filename);
1424 /* First test: if there are options that should be ignored for this file
1425 * verify that they really are ignored.
1427 if (dp->ignored_transforms != 0)
1429 read_png(dp, &dp->original_file, "ignored transforms",
1430 dp->ignored_transforms);
1432 /* The result should be identical to the original_rows */
1433 if (!compare_read(dp, 0/*transforms applied*/))
1434 return; /* no point testing more */
1437 #ifdef PNG_WRITE_PNG_SUPPORTED
1438 /* Second test: write the original PNG data out to a new file (to test the
1439 * write side) then read the result back in and make sure that it hasn't
1442 dp->operation = "write";
1443 write_png(dp, dp->original_ip, 0/*transforms*/);
1444 read_png(dp, &dp->written_file, NULL, 0/*transforms*/);
1445 if (!compare_read(dp, 0/*transforms applied*/))
1449 /* Third test: the active options. Test each in turn, or, with the
1450 * EXHAUSTIVE option, test all possible combinations.
1453 /* Use unsigned int here because the code below to increment through all
1454 * the possibilities exhaustively has to use a compare and that must be
1455 * unsigned, because some transforms are negative on a 16-bit system.
1457 unsigned int active = dp->active_transforms;
1458 int exhaustive = (dp->options & EXHAUSTIVE) != 0;
1459 unsigned int current = first_transform(active);
1460 unsigned int bad_transforms = 0;
1461 unsigned int bad_combo = ~0U; /* bitwise AND of failing transforms */
1462 unsigned int bad_combo_list = 0; /* bitwise OR of failures */
1466 read_png(dp, &dp->original_file, "active transforms", current);
1468 /* If this involved any irreversible transformations then if we write
1469 * it out with just the reversible transformations and read it in again
1470 * with the same transforms we should get the same thing. At present
1471 * this isn't done - it just seems like a waste of time and it would
1472 * require two sets of read png_struct/png_info.
1474 * If there were no irreversible transformations then if we write it
1475 * out and read it back in again (without the reversible transforms)
1476 * we should get back to the place where we started.
1478 #ifdef PNG_WRITE_PNG_SUPPORTED
1479 if ((current & write_transforms) == current)
1481 /* All transforms reversible: write the PNG with the transformations
1482 * reversed, then read it back in with no transformations. The
1483 * result should be the same as the original apart from the loss of
1484 * low order bits because of the SHIFT/sBIT transform.
1486 dp->operation = "reversible transforms";
1487 write_png(dp, dp->read_ip, current);
1489 /* And if this is read back in, because all the transformations were
1490 * reversible, the result should be the same.
1492 read_png(dp, &dp->written_file, NULL, 0);
1493 if (!compare_read(dp, current/*for the SHIFT/sBIT transform*/))
1495 /* This set of transforms failed. If a single bit is set - if
1496 * there is just one transform - don't include this in further
1497 * 'exhaustive' tests. Notice that each transform is tested on
1498 * its own before testing combos in the exhaustive case.
1500 if (is_combo(current))
1502 bad_combo &= current;
1503 bad_combo_list |= current;
1507 bad_transforms |= current;
1512 /* Now move to the next transform */
1513 if (exhaustive) /* all combinations */
1515 unsigned int next = current;
1519 if (next == read_transforms) /* Everything tested */
1523 } /* skip known bad combos if the relevant option is set; skip
1524 * combos involving known bad single transforms in all cases.
1526 while ( (next & read_transforms) <= current
1527 || (next & active) == 0 /* skip cases that do nothing */
1528 || (next & bad_transforms) != 0
1529 || skip_transform(dp, next));
1531 assert((next & read_transforms) == next);
1535 else /* one at a time */
1542 current = first_transform(active);
1547 if (dp->options & FIND_BAD_COMBOS)
1549 /* bad_combos identifies the combos that occur in all failing cases;
1550 * bad_combo_list identifies transforms that do not prevent the
1553 if (bad_combo != ~0U)
1554 printf("%s[0x%x]: PROBLEM: 0x%x[0x%x] ANTIDOTE: 0x%x\n",
1555 dp->filename, active, bad_combo, bad_combo_list,
1556 rw_transforms & ~bad_combo_list);
1559 printf("%s: no %sbad combos found\n", dp->filename,
1560 (dp->options & SKIP_BUGS) ? "additional " : "");
1566 do_test(struct display *dp, const char *file)
1567 /* Exists solely to isolate the setjmp clobbers */
1569 int ret = setjmp(dp->error_return);
1573 test_one_file(dp, file);
1577 else if (ret < ERRORS) /* shouldn't longjmp on warnings */
1578 display_log(dp, INTERNAL_ERROR, "unexpected return code %d", ret);
1584 main(int argc, char **argv)
1586 /* For each file on the command line test it with a range of transforms */
1587 int option_end, ilog = 0;
1593 for (option_end=1; option_end<argc; ++option_end)
1595 const char *name = argv[option_end];
1597 if (strcmp(name, "--verbose") == 0)
1598 d.options = (d.options & ~LEVEL_MASK) | VERBOSE;
1600 else if (strcmp(name, "--warnings") == 0)
1601 d.options = (d.options & ~LEVEL_MASK) | WARNINGS;
1603 else if (strcmp(name, "--errors") == 0)
1604 d.options = (d.options & ~LEVEL_MASK) | ERRORS;
1606 else if (strcmp(name, "--quiet") == 0)
1607 d.options = (d.options & ~LEVEL_MASK) | QUIET;
1609 else if (strcmp(name, "--exhaustive") == 0)
1610 d.options |= EXHAUSTIVE;
1612 else if (strcmp(name, "--fast") == 0)
1613 d.options &= ~EXHAUSTIVE;
1615 else if (strcmp(name, "--strict") == 0)
1616 d.options |= STRICT;
1618 else if (strcmp(name, "--relaxed") == 0)
1619 d.options &= ~STRICT;
1621 else if (strcmp(name, "--log") == 0)
1623 ilog = option_end; /* prevent display */
1627 else if (strcmp(name, "--nolog") == 0)
1630 else if (strcmp(name, "--continue") == 0)
1631 d.options |= CONTINUE;
1633 else if (strcmp(name, "--stop") == 0)
1634 d.options &= ~CONTINUE;
1636 else if (strcmp(name, "--skip-bugs") == 0)
1637 d.options |= SKIP_BUGS;
1639 else if (strcmp(name, "--test-all") == 0)
1640 d.options &= ~SKIP_BUGS;
1642 else if (strcmp(name, "--log-skipped") == 0)
1643 d.options |= LOG_SKIPPED;
1645 else if (strcmp(name, "--nolog-skipped") == 0)
1646 d.options &= ~LOG_SKIPPED;
1648 else if (strcmp(name, "--find-bad-combos") == 0)
1649 d.options |= FIND_BAD_COMBOS;
1651 else if (strcmp(name, "--nofind-bad-combos") == 0)
1652 d.options &= ~FIND_BAD_COMBOS;
1654 else if (strcmp(name, "--list-combos") == 0)
1655 d.options |= LIST_COMBOS;
1657 else if (strcmp(name, "--nolist-combos") == 0)
1658 d.options &= ~LIST_COMBOS;
1660 else if (name[0] == '-' && name[1] == '-')
1662 fprintf(stderr, "pngimage: %s: unknown option\n", name);
1667 break; /* Not an option */
1674 for (i=option_end; i<argc; ++i)
1677 int ret = do_test(&d, argv[i]);
1679 if (ret > QUIET) /* abort on user or internal error */
1683 /* Here on any return, including failures, except user/internal issues
1686 int pass = (d.options & STRICT) ?
1687 RESULT_STRICT(d.results) : RESULT_RELAXED(d.results);
1692 if (d.options & LOG)
1696 printf("%s: pngimage ", pass ? "PASS" : "FAIL");
1698 for (j=1; j<option_end; ++j)
1700 printf("%s ", argv[j]);
1702 printf("%s\n", d.filename);
1709 /* Release allocated memory */
1710 display_destroy(&d);
1715 #else /* !READ_PNG */
1719 fprintf(stderr, "pngimage: no support for png_read/write_image\n");