pngimage.c 50 KB

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