pngimage.c 51 KB

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