pngimage.c 50 KB

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