tarith.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. /* tarith.c
  2. *
  3. * Copyright (c) 2021 Cosmin Truta
  4. * Copyright (c) 2011-2013 John Cunningham Bowler
  5. *
  6. * This code is released under the libpng license.
  7. * For conditions of distribution and use, see the disclaimer
  8. * and license in png.h
  9. *
  10. * Test internal arithmetic functions of libpng.
  11. *
  12. * This code must be linked against a math library (-lm), but does not require
  13. * libpng or zlib to work. Because it includes the complete source of 'png.c'
  14. * it tests the code with whatever compiler options are used to build it.
  15. * Changing these options can substantially change the errors in the
  16. * calculations that the compiler chooses!
  17. */
  18. #define _POSIX_SOURCE 1
  19. #define _ISOC99_SOURCE 1
  20. /* Obtain a copy of the code to be tested (plus other things), disabling
  21. * stuff that is not required.
  22. */
  23. #include <math.h>
  24. #include <stdlib.h>
  25. #include <ctype.h>
  26. #include <string.h>
  27. #include <assert.h>
  28. #include "../../pngpriv.h"
  29. #define png_error png_warning
  30. void png_warning(png_const_structrp png_ptr, png_const_charp msg)
  31. {
  32. fprintf(stderr, "validation: %s\n", msg);
  33. }
  34. #define png_fixed_error png_fixed_warning
  35. void png_fixed_warning(png_const_structrp png_ptr, png_const_charp msg)
  36. {
  37. fprintf(stderr, "overflow in: %s\n", msg);
  38. }
  39. #define png_set_error_fn(pp, ep, efp, wfp) ((void)0)
  40. #define png_malloc(pp, s) malloc(s)
  41. #define png_malloc_warn(pp, s) malloc(s)
  42. #define png_malloc_base(pp, s) malloc(s)
  43. #define png_calloc(pp, s) calloc(1, (s))
  44. #define png_free(pp, s) free(s)
  45. #define png_safecat(b, sb, pos, str) (pos)
  46. #define png_format_number(start, end, format, number) (start)
  47. #define crc32(crc, pp, s) (crc)
  48. #define inflateReset(zs) Z_OK
  49. #define png_create_struct(type) (0)
  50. #define png_destroy_struct(pp) ((void)0)
  51. #define png_create_struct_2(type, m, mm) (0)
  52. #define png_destroy_struct_2(pp, f, mm) ((void)0)
  53. #undef PNG_SIMPLIFIED_READ_SUPPORTED
  54. #undef PNG_SIMPLIFIED_WRITE_SUPPORTED
  55. #undef PNG_USER_MEM_SUPPORTED
  56. #include "../../png.c"
  57. /* Validate ASCII to fp routines. */
  58. static int verbose = 0;
  59. int validation_ascii_to_fp(int count, int argc, char **argv)
  60. {
  61. int showall = 0;
  62. double max_error=2; /* As a percentage error-in-last-digit/.5 */
  63. double max_error_abs=17; /* Used when precision is DBL_DIG */
  64. double max = 0;
  65. double max_abs = 0;
  66. double test = 0; /* Important to test this. */
  67. int precision = 5;
  68. int nonfinite = 0;
  69. int finite = 0;
  70. int ok = 0;
  71. int failcount = 0;
  72. int minorarith = 0;
  73. while (--argc > 0)
  74. {
  75. if (strcmp(*++argv, "-a") == 0)
  76. showall = 1;
  77. else if (strcmp(*argv, "-e") == 0 && argc > 0)
  78. {
  79. --argc;
  80. max_error = atof(*++argv);
  81. }
  82. else if (strcmp(*argv, "-E") == 0 && argc > 0)
  83. {
  84. --argc;
  85. max_error_abs = atof(*++argv);
  86. }
  87. else
  88. {
  89. fprintf(stderr, "unknown argument %s\n", *argv);
  90. return 1;
  91. }
  92. }
  93. do
  94. {
  95. size_t index;
  96. int state, failed = 0;
  97. char buffer[64];
  98. if (isfinite(test))
  99. ++finite;
  100. else
  101. ++nonfinite;
  102. if (verbose)
  103. fprintf(stderr, "%.*g %d\n", DBL_DIG, test, precision);
  104. /* Check for overflow in the buffer by setting a marker. */
  105. memset(buffer, 71, sizeof buffer);
  106. png_ascii_from_fp(0, buffer, precision+10, test, precision);
  107. /* Allow for a three digit exponent, this stuff will fail if
  108. * the exponent is bigger than this!
  109. */
  110. if (buffer[precision+7] != 71)
  111. {
  112. fprintf(stderr, "%g[%d] -> '%s'[%lu] buffer overflow\n",
  113. test, precision, buffer, (unsigned long)strlen(buffer));
  114. failed = 1;
  115. }
  116. /* Following are used for the number parser below and must be
  117. * initialized to zero.
  118. */
  119. state = 0;
  120. index = 0;
  121. if (!isfinite(test))
  122. {
  123. /* Expect 'inf' */
  124. if (test >= 0 && strcmp(buffer, "inf") ||
  125. test < 0 && strcmp(buffer, "-inf"))
  126. {
  127. fprintf(stderr, "%g[%d] -> '%s' but expected 'inf'\n",
  128. test, precision, buffer);
  129. failed = 1;
  130. }
  131. }
  132. else if (!png_check_fp_number(buffer, precision+10, &state, &index) ||
  133. buffer[index] != 0)
  134. {
  135. fprintf(stderr, "%g[%d] -> '%s' but has bad format ('%c')\n",
  136. test, precision, buffer, buffer[index]);
  137. failed = 1;
  138. }
  139. else if (PNG_FP_IS_NEGATIVE(state) && !(test < 0))
  140. {
  141. fprintf(stderr, "%g[%d] -> '%s' but negative value not so reported\n",
  142. test, precision, buffer);
  143. failed = 1;
  144. assert(!PNG_FP_IS_ZERO(state));
  145. assert(!PNG_FP_IS_POSITIVE(state));
  146. }
  147. else if (PNG_FP_IS_ZERO(state) && !(test == 0))
  148. {
  149. fprintf(stderr, "%g[%d] -> '%s' but zero value not so reported\n",
  150. test, precision, buffer);
  151. failed = 1;
  152. assert(!PNG_FP_IS_NEGATIVE(state));
  153. assert(!PNG_FP_IS_POSITIVE(state));
  154. }
  155. else if (PNG_FP_IS_POSITIVE(state) && !(test > 0))
  156. {
  157. fprintf(stderr, "%g[%d] -> '%s' but positive value not so reported\n",
  158. test, precision, buffer);
  159. failed = 1;
  160. assert(!PNG_FP_IS_NEGATIVE(state));
  161. assert(!PNG_FP_IS_ZERO(state));
  162. }
  163. else
  164. {
  165. /* Check the result against the original. */
  166. double out = atof(buffer);
  167. double change = fabs((out - test)/test);
  168. double allow = .5 / pow(10,
  169. (precision >= DBL_DIG) ? DBL_DIG-1 : precision-1);
  170. /* NOTE: if you hit this error case are you compiling with gcc
  171. * and -O0? Try -O2 - the errors can accumulate if the FP
  172. * code above is not optimized and may drift outside the .5 in
  173. * DBL_DIG allowed. In any case a small number of errors may
  174. * occur (very small ones - 1 or 2%) because of rounding in the
  175. * calculations, either in the conversion API or in atof.
  176. */
  177. if (change >= allow && (isfinite(out) ||
  178. fabs(test/DBL_MAX) <= 1-allow))
  179. {
  180. double percent = (precision >= DBL_DIG) ? max_error_abs : max_error;
  181. double allowp = (change-allow)*100/allow;
  182. if (precision >= DBL_DIG)
  183. {
  184. if (max_abs < allowp) max_abs = allowp;
  185. }
  186. else
  187. {
  188. if (max < allowp) max = allowp;
  189. }
  190. if (showall || allowp >= percent)
  191. {
  192. fprintf(stderr,
  193. "%.*g[%d] -> '%s' -> %.*g number changed (%g > %g (%d%%))\n",
  194. DBL_DIG, test, precision, buffer, DBL_DIG, out, change, allow,
  195. (int)round(allowp));
  196. failed = 1;
  197. }
  198. else
  199. ++minorarith;
  200. }
  201. }
  202. if (failed)
  203. ++failcount;
  204. else
  205. ++ok;
  206. skip:
  207. /* Generate a new number and precision. */
  208. precision = rand();
  209. if (precision & 1) test = -test;
  210. precision >>= 1;
  211. /* Generate random numbers. */
  212. if (test == 0 || !isfinite(test))
  213. test = precision+1;
  214. else
  215. {
  216. /* Derive the exponent from the previous rand() value. */
  217. int exponent = precision % (DBL_MAX_EXP - DBL_MIN_EXP) + DBL_MIN_EXP;
  218. int tmp;
  219. test = frexp(test * rand(), &tmp);
  220. test = ldexp(test, exponent);
  221. precision >>= 8; /* arbitrary */
  222. }
  223. /* This limits the precision to 32 digits, enough for standard
  224. * IEEE implementations which have at most 15 digits.
  225. */
  226. precision = (precision & 0x1f) + 1;
  227. }
  228. while (--count);
  229. printf("Tested %d finite values, %d non-finite, %d OK (%d failed) "
  230. "%d minor arithmetic errors\n",
  231. finite, nonfinite, ok, failcount, minorarith);
  232. printf(" Error with >=%d digit precision %.2f%%\n", DBL_DIG, max_abs);
  233. printf(" Error with < %d digit precision %.2f%%\n", DBL_DIG, max);
  234. return 0;
  235. }
  236. /* Observe that valid FP numbers have the forms listed in the PNG extensions
  237. * specification:
  238. *
  239. * [+,-]{integer,integer.fraction,.fraction}[{e,E}[+,-]integer]
  240. *
  241. * Test each of these in turn, including invalid cases.
  242. */
  243. typedef enum checkfp_state
  244. {
  245. start, fraction, exponent, states
  246. } checkfp_state;
  247. /* The characters (other than digits) that characterize the states: */
  248. static const char none[] = "";
  249. static const char hexdigits[16] = "0123456789ABCDEF";
  250. static const struct
  251. {
  252. const char *start; /* Characters valid at the start */
  253. const char *end; /* Valid characters that end the state */
  254. const char *tests; /* Characters to test after 2 digits seen */
  255. }
  256. state_characters[states] =
  257. {
  258. /* start: */ { "+-.", ".eE", "+-.e*0369" },
  259. /* fraction: */ { none, "eE", "+-.E#0147" },
  260. /* exponent: */ { "+-", none, "+-.eE^0258" }
  261. };
  262. typedef struct
  263. {
  264. char number[1024]; /* Buffer for number being tested */
  265. int limit; /* Command line limit */
  266. int verbose; /* Shadows global variable */
  267. int ctimes; /* Number of numbers tested */
  268. int cmillions; /* Count of millions of numbers */
  269. int cinvalid; /* Invalid strings checked */
  270. int cnoaccept; /* Characters not accepted */
  271. }
  272. checkfp_command;
  273. typedef struct
  274. {
  275. int cnumber; /* Index into number string */
  276. checkfp_state check_state; /* Current number state */
  277. int at_start; /* At start (first character) of state */
  278. int cdigits_in_state; /* Digits seen in that state */
  279. int limit; /* Limit on same for checking all chars */
  280. int state; /* Current parser state */
  281. int is_negative; /* Number is negative */
  282. int is_zero; /* Number is (still) zero */
  283. int number_was_valid; /* Previous character validity */
  284. }
  285. checkfp_control;
  286. static int check_all_characters(checkfp_command *co, checkfp_control c);
  287. static int check_some_characters(checkfp_command *co, checkfp_control c,
  288. const char *tests);
  289. static int check_one_character(checkfp_command *co, checkfp_control c, int ch)
  290. {
  291. /* Test this character (ch) to ensure the parser does the correct thing.
  292. */
  293. size_t index = 0;
  294. const char test = (char)ch;
  295. int number_is_valid = png_check_fp_number(&test, 1, &c.state, &index);
  296. int character_accepted = (index == 1);
  297. if (c.check_state != exponent && isdigit(ch) && ch != '0')
  298. c.is_zero = 0;
  299. if (c.check_state == start && c.at_start && ch == '-')
  300. c.is_negative = 1;
  301. if (isprint(ch))
  302. co->number[c.cnumber++] = (char)ch;
  303. else
  304. {
  305. co->number[c.cnumber++] = '<';
  306. co->number[c.cnumber++] = hexdigits[(ch >> 4) & 0xf];
  307. co->number[c.cnumber++] = hexdigits[ch & 0xf];
  308. co->number[c.cnumber++] = '>';
  309. }
  310. co->number[c.cnumber] = 0;
  311. if (co->verbose > 1)
  312. fprintf(stderr, "%s\n", co->number);
  313. if (++(co->ctimes) == 1000000)
  314. {
  315. if (co->verbose == 1)
  316. fputc('.', stderr);
  317. co->ctimes = 0;
  318. ++(co->cmillions);
  319. }
  320. if (!number_is_valid)
  321. ++(co->cinvalid);
  322. if (!character_accepted)
  323. ++(co->cnoaccept);
  324. /* This should never fail (it's a serious bug if it does): */
  325. if (index != 0 && index != 1)
  326. {
  327. fprintf(stderr, "%s: read beyond end of string (%lu)\n",
  328. co->number, (unsigned long)index);
  329. return 0;
  330. }
  331. /* Validate the new state, note that the PNG_FP_IS_ macros all return
  332. * false unless the number is valid.
  333. */
  334. if (PNG_FP_IS_NEGATIVE(c.state) !=
  335. (number_is_valid && !c.is_zero && c.is_negative))
  336. {
  337. fprintf(stderr, "%s: negative when it is not\n", co->number);
  338. return 0;
  339. }
  340. if (PNG_FP_IS_ZERO(c.state) != (number_is_valid && c.is_zero))
  341. {
  342. fprintf(stderr, "%s: zero when it is not\n", co->number);
  343. return 0;
  344. }
  345. if (PNG_FP_IS_POSITIVE(c.state) !=
  346. (number_is_valid && !c.is_zero && !c.is_negative))
  347. {
  348. fprintf(stderr, "%s: positive when it is not\n", co->number);
  349. return 0;
  350. }
  351. /* Testing a digit */
  352. if (isdigit(ch))
  353. {
  354. if (!character_accepted)
  355. {
  356. fprintf(stderr, "%s: digit '%c' not accepted\n", co->number, ch);
  357. return 0;
  358. }
  359. if (!number_is_valid)
  360. {
  361. fprintf(stderr, "%s: saw a digit (%c) but number not valid\n",
  362. co->number, ch);
  363. return 0;
  364. }
  365. ++c.cdigits_in_state;
  366. c.at_start = 0;
  367. c.number_was_valid = 1;
  368. /* Continue testing characters in this state. Either test all of
  369. * them or, if we have already seen one digit in this state, just test a
  370. * limited set.
  371. */
  372. if (c.cdigits_in_state < 1)
  373. return check_all_characters(co, c);
  374. else
  375. return check_some_characters(co, c,
  376. state_characters[c.check_state].tests);
  377. }
  378. /* A non-digit; is it allowed here? */
  379. else if (((ch == '+' || ch == '-') && c.check_state != fraction &&
  380. c.at_start) ||
  381. (ch == '.' && c.check_state == start) ||
  382. ((ch == 'e' || ch == 'E') && c.number_was_valid &&
  383. c.check_state != exponent))
  384. {
  385. if (!character_accepted)
  386. {
  387. fprintf(stderr, "%s: character '%c' not accepted\n", co->number, ch);
  388. return 0;
  389. }
  390. /* The number remains valid after start of fraction but nowhere else. */
  391. if (number_is_valid && (c.check_state != start || ch != '.'))
  392. {
  393. fprintf(stderr, "%s: saw a non-digit (%c) but number valid\n",
  394. co->number, ch);
  395. return 0;
  396. }
  397. c.number_was_valid = number_is_valid;
  398. /* Check for a state change. When changing to 'fraction' if the number
  399. * is valid at this point set the at_start to false to allow an exponent
  400. * 'e' to come next.
  401. */
  402. if (c.check_state == start && ch == '.')
  403. {
  404. c.check_state = fraction;
  405. c.at_start = !number_is_valid;
  406. c.cdigits_in_state = 0;
  407. c.limit = co->limit;
  408. return check_all_characters(co, c);
  409. }
  410. else if (c.check_state < exponent && (ch == 'e' || ch == 'E'))
  411. {
  412. c.check_state = exponent;
  413. c.at_start = 1;
  414. c.cdigits_in_state = 0;
  415. c.limit = co->limit;
  416. return check_all_characters(co, c);
  417. }
  418. /* Else it was a sign, and the state doesn't change. */
  419. else
  420. {
  421. if (ch != '-' && ch != '+')
  422. {
  423. fprintf(stderr, "checkfp: internal error (1)\n");
  424. return 0;
  425. }
  426. c.at_start = 0;
  427. return check_all_characters(co, c);
  428. }
  429. }
  430. /* Testing an invalid character */
  431. else
  432. {
  433. if (character_accepted)
  434. {
  435. fprintf(stderr, "%s: character '%c' [0x%.2x] accepted\n", co->number,
  436. ch, ch);
  437. return 0;
  438. }
  439. if (number_is_valid != c.number_was_valid)
  440. {
  441. fprintf(stderr,
  442. "%s: character '%c' [0x%.2x] changed number validity\n",
  443. co->number, ch, ch);
  444. return 0;
  445. }
  446. /* Do nothing - the parser has stuck; return success and keep going with
  447. * the next character.
  448. */
  449. }
  450. /* Successful return (the caller will try the next character.) */
  451. return 1;
  452. }
  453. static int check_all_characters(checkfp_command *co, checkfp_control c)
  454. {
  455. int ch;
  456. if (c.cnumber+4 < sizeof co->number)
  457. {
  458. for (ch=0; ch<256; ++ch)
  459. {
  460. if (!check_one_character(co, c, ch))
  461. return 0;
  462. }
  463. }
  464. return 1;
  465. }
  466. static int check_some_characters(checkfp_command *co, checkfp_control c,
  467. const char *tests)
  468. {
  469. int i;
  470. --(c.limit);
  471. if (c.cnumber+4 < sizeof co->number && c.limit >= 0)
  472. {
  473. if (c.limit > 0)
  474. {
  475. for (i=0; tests[i]; ++i)
  476. {
  477. if (!check_one_character(co, c, tests[i]))
  478. return 0;
  479. }
  480. }
  481. /* At the end check all the characters. */
  482. else
  483. return check_all_characters(co, c);
  484. }
  485. return 1;
  486. }
  487. int validation_checkfp(int count, int argc, char **argv)
  488. {
  489. int result;
  490. checkfp_command command;
  491. checkfp_control control;
  492. command.number[0] = 0;
  493. command.limit = 3;
  494. command.verbose = verbose;
  495. command.ctimes = 0;
  496. command.cmillions = 0;
  497. command.cinvalid = 0;
  498. command.cnoaccept = 0;
  499. while (--argc > 0)
  500. {
  501. ++argv;
  502. if (argc > 1 && strcmp(*argv, "-l") == 0)
  503. {
  504. --argc;
  505. command.limit = atoi(*++argv);
  506. }
  507. else
  508. {
  509. fprintf(stderr, "unknown argument %s\n", *argv);
  510. return 1;
  511. }
  512. }
  513. control.cnumber = 0;
  514. control.check_state = start;
  515. control.at_start = 1;
  516. control.cdigits_in_state = 0;
  517. control.limit = command.limit;
  518. control.state = 0;
  519. control.is_negative = 0;
  520. control.is_zero = 1;
  521. control.number_was_valid = 0;
  522. result = check_all_characters(&command, control);
  523. printf("checkfp: %s: checked %d,%.3d,%.3d,%.3d strings (%d invalid)\n",
  524. result ? "pass" : "FAIL", command.cmillions / 1000,
  525. command.cmillions % 1000, command.ctimes / 1000, command.ctimes % 1000,
  526. command.cinvalid);
  527. return result;
  528. }
  529. int validation_muldiv(int count, int argc, char **argv)
  530. {
  531. int tested = 0;
  532. int overflow = 0;
  533. int error = 0;
  534. int error64 = 0;
  535. int passed = 0;
  536. int randbits = 0;
  537. png_uint_32 randbuffer;
  538. png_fixed_point a;
  539. png_int_32 times, div;
  540. while (--argc > 0)
  541. {
  542. fprintf(stderr, "unknown argument %s\n", *++argv);
  543. return 1;
  544. }
  545. /* Find out about the random number generator. */
  546. randbuffer = RAND_MAX;
  547. while (randbuffer != 0) ++randbits, randbuffer >>= 1;
  548. printf("Using random number generator that makes %d bits\n", randbits);
  549. for (div=0; div<32; div += randbits)
  550. randbuffer = (randbuffer << randbits) ^ rand();
  551. a = 0;
  552. times = div = 0;
  553. do
  554. {
  555. png_fixed_point result;
  556. /* NOTE: your mileage may vary, a type is required below that can
  557. * hold 64 bits or more, if floating point is used a 64-bit or
  558. * better mantissa is required.
  559. */
  560. long long int fp, fpround;
  561. unsigned long hi, lo;
  562. int ok;
  563. /* Check the values, png_64bit_product can only handle positive
  564. * numbers, so correct for that here.
  565. */
  566. {
  567. long u1, u2;
  568. int n = 0;
  569. if (a < 0) u1 = -a, n = 1; else u1 = a;
  570. if (times < 0) u2 = -times, n = !n; else u2 = times;
  571. png_64bit_product(u1, u2, &hi, &lo);
  572. if (n)
  573. {
  574. /* -x = ~x+1 */
  575. lo = ((~lo) + 1) & 0xffffffff;
  576. hi = ~hi;
  577. if (lo == 0) ++hi;
  578. }
  579. }
  580. fp = a;
  581. fp *= times;
  582. if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
  583. {
  584. fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
  585. a, times, hi, lo, fp);
  586. ++error64;
  587. }
  588. if (div != 0)
  589. {
  590. /* Round - this is C round to zero. */
  591. if ((fp < 0) != (div < 0))
  592. fp -= div/2;
  593. else
  594. fp += div/2;
  595. fp /= div;
  596. fpround = fp;
  597. /* Assume 2's complement here: */
  598. ok = fpround <= PNG_UINT_31_MAX &&
  599. fpround >= -1-(long long int)PNG_UINT_31_MAX;
  600. if (!ok) ++overflow;
  601. }
  602. else
  603. ok = 0, ++overflow, fpround = fp/*misleading*/;
  604. if (verbose)
  605. fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n",
  606. a, times, div, fp, ok ? "ok" : "overflow");
  607. ++tested;
  608. if (png_muldiv(&result, a, times, div) != ok)
  609. {
  610. ++error;
  611. if (ok)
  612. fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n",
  613. a, times, div, fp);
  614. else
  615. fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n",
  616. a, times, div, result, fp);
  617. }
  618. else if (ok && result != fpround)
  619. {
  620. ++error;
  621. fprintf(stderr, "%d * %d / %d -> %d not %lld\n",
  622. a, times, div, result, fp);
  623. }
  624. else
  625. ++passed;
  626. /* Generate three new values, this uses rand() and rand() only returns
  627. * up to RAND_MAX.
  628. */
  629. /* CRUDE */
  630. a += times;
  631. times += div;
  632. div = randbuffer;
  633. randbuffer = (randbuffer << randbits) ^ rand();
  634. }
  635. while (--count > 0);
  636. printf("%d tests including %d overflows, %d passed, %d failed "
  637. "(%d 64-bit errors)\n", tested, overflow, passed, error, error64);
  638. return 0;
  639. }
  640. /* When FP is on this just becomes a speed test - compile without FP to get real
  641. * validation.
  642. */
  643. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  644. #define LN2 .000010576586617430806112933839 /* log(2)/65536 */
  645. #define L2INV 94548.46219969910586572651 /* 65536/log(2) */
  646. /* For speed testing, need the internal functions too: */
  647. static png_uint_32 png_log8bit(unsigned x)
  648. {
  649. if (x > 0)
  650. return (png_uint_32)floor(.5-log(x/255.)*L2INV);
  651. return 0xffffffff;
  652. }
  653. static png_uint_32 png_log16bit(png_uint_32 x)
  654. {
  655. if (x > 0)
  656. return (png_uint_32)floor(.5-log(x/65535.)*L2INV);
  657. return 0xffffffff;
  658. }
  659. static png_uint_32 png_exp(png_uint_32 x)
  660. {
  661. return (png_uint_32)floor(.5 + exp(x * -LN2) * 0xffffffffU);
  662. }
  663. static png_byte png_exp8bit(png_uint_32 log)
  664. {
  665. return (png_byte)floor(.5 + exp(log * -LN2) * 255);
  666. }
  667. static png_uint_16 png_exp16bit(png_uint_32 log)
  668. {
  669. return (png_uint_16)floor(.5 + exp(log * -LN2) * 65535);
  670. }
  671. #endif /* FLOATING_ARITHMETIC */
  672. int validation_gamma(int argc, char **argv)
  673. {
  674. double gamma[9] = { 2.2, 1.8, 1.52, 1.45, 1., 1/1.45, 1/1.52, 1/1.8, 1/2.2 };
  675. double maxerr;
  676. int i, silent=0, onlygamma=0;
  677. /* Silence the output with -s, just test the gamma functions with -g: */
  678. while (--argc > 0)
  679. if (strcmp(*++argv, "-s") == 0)
  680. silent = 1;
  681. else if (strcmp(*argv, "-g") == 0)
  682. onlygamma = 1;
  683. else
  684. {
  685. fprintf(stderr, "unknown argument %s\n", *argv);
  686. return 1;
  687. }
  688. if (!onlygamma)
  689. {
  690. /* First validate the log functions: */
  691. maxerr = 0;
  692. for (i=0; i<256; ++i)
  693. {
  694. double correct = -log(i/255.)/log(2.)*65536;
  695. double error = png_log8bit(i) - correct;
  696. if (i != 0 && fabs(error) > maxerr)
  697. maxerr = fabs(error);
  698. if (i == 0 && png_log8bit(i) != 0xffffffff ||
  699. i != 0 && png_log8bit(i) != floor(correct+.5))
  700. {
  701. fprintf(stderr, "8-bit log error: %d: got %u, expected %f\n",
  702. i, png_log8bit(i), correct);
  703. }
  704. }
  705. if (!silent)
  706. printf("maximum 8-bit log error = %f\n", maxerr);
  707. maxerr = 0;
  708. for (i=0; i<65536; ++i)
  709. {
  710. double correct = -log(i/65535.)/log(2.)*65536;
  711. double error = png_log16bit(i) - correct;
  712. if (i != 0 && fabs(error) > maxerr)
  713. maxerr = fabs(error);
  714. if (i == 0 && png_log16bit(i) != 0xffffffff ||
  715. i != 0 && png_log16bit(i) != floor(correct+.5))
  716. {
  717. if (error > .68) /* By experiment error is less than .68 */
  718. {
  719. fprintf(stderr,
  720. "16-bit log error: %d: got %u, expected %f error: %f\n",
  721. i, png_log16bit(i), correct, error);
  722. }
  723. }
  724. }
  725. if (!silent)
  726. printf("maximum 16-bit log error = %f\n", maxerr);
  727. /* Now exponentiations. */
  728. maxerr = 0;
  729. for (i=0; i<=0xfffff; ++i)
  730. {
  731. double correct = exp(-i/65536. * log(2.)) * (65536. * 65536);
  732. double error = png_exp(i) - correct;
  733. if (fabs(error) > maxerr)
  734. maxerr = fabs(error);
  735. if (fabs(error) > 1883) /* By experiment. */
  736. {
  737. fprintf(stderr,
  738. "32-bit exp error: %d: got %u, expected %f error: %f\n",
  739. i, png_exp(i), correct, error);
  740. }
  741. }
  742. if (!silent)
  743. printf("maximum 32-bit exp error = %f\n", maxerr);
  744. maxerr = 0;
  745. for (i=0; i<=0xfffff; ++i)
  746. {
  747. double correct = exp(-i/65536. * log(2.)) * 255;
  748. double error = png_exp8bit(i) - correct;
  749. if (fabs(error) > maxerr)
  750. maxerr = fabs(error);
  751. if (fabs(error) > .50002) /* By experiment */
  752. {
  753. fprintf(stderr,
  754. "8-bit exp error: %d: got %u, expected %f error: %f\n",
  755. i, png_exp8bit(i), correct, error);
  756. }
  757. }
  758. if (!silent)
  759. printf("maximum 8-bit exp error = %f\n", maxerr);
  760. maxerr = 0;
  761. for (i=0; i<=0xfffff; ++i)
  762. {
  763. double correct = exp(-i/65536. * log(2.)) * 65535;
  764. double error = png_exp16bit(i) - correct;
  765. if (fabs(error) > maxerr)
  766. maxerr = fabs(error);
  767. if (fabs(error) > .524) /* By experiment */
  768. {
  769. fprintf(stderr,
  770. "16-bit exp error: %d: got %u, expected %f error: %f\n",
  771. i, png_exp16bit(i), correct, error);
  772. }
  773. }
  774. if (!silent)
  775. printf("maximum 16-bit exp error = %f\n", maxerr);
  776. } /* !onlygamma */
  777. /* Test the overall gamma correction. */
  778. for (i=0; i<9; ++i)
  779. {
  780. unsigned j;
  781. double g = gamma[i];
  782. png_fixed_point gfp = floor(g * PNG_FP_1 + .5);
  783. if (!silent)
  784. printf("Test gamma %f\n", g);
  785. maxerr = 0;
  786. for (j=0; j<256; ++j)
  787. {
  788. double correct = pow(j/255., g) * 255;
  789. png_byte out = png_gamma_8bit_correct(j, gfp);
  790. double error = out - correct;
  791. if (fabs(error) > maxerr)
  792. maxerr = fabs(error);
  793. if (out != floor(correct+.5))
  794. {
  795. fprintf(stderr, "8bit %d ^ %f: got %d expected %f error %f\n",
  796. j, g, out, correct, error);
  797. }
  798. }
  799. if (!silent)
  800. printf("gamma %f: maximum 8-bit error %f\n", g, maxerr);
  801. maxerr = 0;
  802. for (j=0; j<65536; ++j)
  803. {
  804. double correct = pow(j/65535., g) * 65535;
  805. png_uint_16 out = png_gamma_16bit_correct(j, gfp);
  806. double error = out - correct;
  807. if (fabs(error) > maxerr)
  808. maxerr = fabs(error);
  809. if (fabs(error) > 1.62)
  810. {
  811. fprintf(stderr, "16bit %d ^ %f: got %d expected %f error %f\n",
  812. j, g, out, correct, error);
  813. }
  814. }
  815. if (!silent)
  816. printf("gamma %f: maximum 16-bit error %f\n", g, maxerr);
  817. }
  818. return 0;
  819. }
  820. /**************************** VALIDATION TESTS ********************************/
  821. /* Various validation routines are included herein, they require some
  822. * definition for png_warning and png_error, settings of VALIDATION:
  823. *
  824. * 1: validates the ASCII to floating point conversions
  825. * 2: validates png_muldiv
  826. * 3: accuracy test of fixed point gamma tables
  827. */
  828. /* The following COUNT (10^8) takes about 1 hour on a 1GHz Pentium IV
  829. * processor.
  830. */
  831. #define COUNT 1000000000
  832. int main(int argc, char **argv)
  833. {
  834. int count = COUNT;
  835. while (argc > 1)
  836. {
  837. if (argc > 2 && strcmp(argv[1], "-c") == 0)
  838. {
  839. count = atoi(argv[2]);
  840. argc -= 2;
  841. argv += 2;
  842. }
  843. else if (strcmp(argv[1], "-v") == 0)
  844. {
  845. ++verbose;
  846. --argc;
  847. ++argv;
  848. }
  849. else
  850. break;
  851. }
  852. if (count > 0 && argc > 1)
  853. {
  854. if (strcmp(argv[1], "ascii") == 0)
  855. return validation_ascii_to_fp(count, argc-1, argv+1);
  856. else if (strcmp(argv[1], "checkfp") == 0)
  857. return validation_checkfp(count, argc-1, argv+1);
  858. else if (strcmp(argv[1], "muldiv") == 0)
  859. return validation_muldiv(count, argc-1, argv+1);
  860. else if (strcmp(argv[1], "gamma") == 0)
  861. return validation_gamma(argc-1, argv+1);
  862. }
  863. /* Bad argument: */
  864. fprintf(stderr,
  865. "usage: tarith [-v] [-c count] {ascii,muldiv,gamma} [args]\n");
  866. fprintf(stderr, " arguments: ascii [-a (all results)] [-e error%%]\n");
  867. fprintf(stderr, " checkfp [-l max-number-chars]\n");
  868. fprintf(stderr, " muldiv\n");
  869. fprintf(stderr, " gamma -s (silent) -g (only gamma; no log)\n");
  870. return 1;
  871. }