crc32.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /* crc32.c -- compute the CRC-32 of a data stream
  2. * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. *
  5. * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
  6. * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
  7. * tables for updating the shift register in one step with three exclusive-ors
  8. * instead of four steps with four exclusive-ors. This results in about a
  9. * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
  10. */
  11. /* @(#) $Id$ */
  12. /*
  13. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  14. protection on the static variables used to control the first-use generation
  15. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  16. first call get_crc_table() to initialize the tables before allowing more than
  17. one thread to use crc32().
  18. DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
  19. */
  20. #ifdef MAKECRCH
  21. # include <stdio.h>
  22. # ifndef DYNAMIC_CRC_TABLE
  23. # define DYNAMIC_CRC_TABLE
  24. # endif /* !DYNAMIC_CRC_TABLE */
  25. #endif /* MAKECRCH */
  26. #include "zutil.h" /* for STDC and FAR definitions */
  27. /* Definitions for doing the crc four data bytes at a time. */
  28. #if !defined(NOBYFOUR) && defined(Z_U4)
  29. # define BYFOUR
  30. #endif
  31. #ifdef BYFOUR
  32. local unsigned long crc32_little OF((unsigned long,
  33. const unsigned char FAR *, z_size_t));
  34. local unsigned long crc32_big OF((unsigned long,
  35. const unsigned char FAR *, z_size_t));
  36. # define TBLS 8
  37. #else
  38. # define TBLS 1
  39. #endif /* BYFOUR */
  40. /* Local functions for crc concatenation */
  41. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  42. unsigned long vec));
  43. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  44. local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
  45. #ifdef DYNAMIC_CRC_TABLE
  46. local volatile int crc_table_empty = 1;
  47. local z_crc_t FAR crc_table[TBLS][256];
  48. local void make_crc_table OF((void));
  49. #ifdef MAKECRCH
  50. local void write_table OF((FILE *, const z_crc_t FAR *));
  51. #endif /* MAKECRCH */
  52. /*
  53. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  54. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  55. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  56. with the lowest powers in the most significant bit. Then adding polynomials
  57. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  58. one. If we call the above polynomial p, and represent a byte as the
  59. polynomial q, also with the lowest power in the most significant bit (so the
  60. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  61. where a mod b means the remainder after dividing a by b.
  62. This calculation is done using the shift-register method of multiplying and
  63. taking the remainder. The register is initialized to zero, and for each
  64. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  65. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  66. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  67. out is a one). We start with the highest power (least significant bit) of
  68. q and repeat for all eight bits of q.
  69. The first table is simply the CRC of all possible eight bit values. This is
  70. all the information needed to generate CRCs on data a byte at a time for all
  71. combinations of CRC register values and incoming bytes. The remaining tables
  72. allow for word-at-a-time CRC calculation for both big-endian and little-
  73. endian machines, where a word is four bytes.
  74. */
  75. local void make_crc_table()
  76. {
  77. z_crc_t c;
  78. int n, k;
  79. z_crc_t poly; /* polynomial exclusive-or pattern */
  80. /* terms of polynomial defining this crc (except x^32): */
  81. static volatile int first = 1; /* flag to limit concurrent making */
  82. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  83. /* See if another task is already doing this (not thread-safe, but better
  84. than nothing -- significantly reduces duration of vulnerability in
  85. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  86. if (first) {
  87. first = 0;
  88. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  89. poly = 0;
  90. for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
  91. poly |= (z_crc_t)1 << (31 - p[n]);
  92. /* generate a crc for every 8-bit value */
  93. for (n = 0; n < 256; n++) {
  94. c = (z_crc_t)n;
  95. for (k = 0; k < 8; k++)
  96. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  97. crc_table[0][n] = c;
  98. }
  99. #ifdef BYFOUR
  100. /* generate crc for each value followed by one, two, and three zeros,
  101. and then the byte reversal of those as well as the first table */
  102. for (n = 0; n < 256; n++) {
  103. c = crc_table[0][n];
  104. crc_table[4][n] = ZSWAP32(c);
  105. for (k = 1; k < 4; k++) {
  106. c = crc_table[0][c & 0xff] ^ (c >> 8);
  107. crc_table[k][n] = c;
  108. crc_table[k + 4][n] = ZSWAP32(c);
  109. }
  110. }
  111. #endif /* BYFOUR */
  112. crc_table_empty = 0;
  113. }
  114. else { /* not first */
  115. /* wait for the other guy to finish (not efficient, but rare) */
  116. while (crc_table_empty)
  117. ;
  118. }
  119. #ifdef MAKECRCH
  120. /* write out CRC tables to crc32.h */
  121. {
  122. FILE *out;
  123. out = fopen("crc32.h", "w");
  124. if (out == NULL) return;
  125. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  126. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  127. fprintf(out, "local const z_crc_t FAR ");
  128. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  129. write_table(out, crc_table[0]);
  130. # ifdef BYFOUR
  131. fprintf(out, "#ifdef BYFOUR\n");
  132. for (k = 1; k < 8; k++) {
  133. fprintf(out, " },\n {\n");
  134. write_table(out, crc_table[k]);
  135. }
  136. fprintf(out, "#endif\n");
  137. # endif /* BYFOUR */
  138. fprintf(out, " }\n};\n");
  139. fclose(out);
  140. }
  141. #endif /* MAKECRCH */
  142. }
  143. #ifdef MAKECRCH
  144. local void write_table(out, table)
  145. FILE *out;
  146. const z_crc_t FAR *table;
  147. {
  148. int n;
  149. for (n = 0; n < 256; n++)
  150. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ",
  151. (unsigned long)(table[n]),
  152. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  153. }
  154. #endif /* MAKECRCH */
  155. #else /* !DYNAMIC_CRC_TABLE */
  156. /* ========================================================================
  157. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  158. */
  159. #include "crc32.h"
  160. #endif /* DYNAMIC_CRC_TABLE */
  161. /* =========================================================================
  162. * This function can be used by asm versions of crc32()
  163. */
  164. const z_crc_t FAR * ZEXPORT get_crc_table()
  165. {
  166. #ifdef DYNAMIC_CRC_TABLE
  167. if (crc_table_empty)
  168. make_crc_table();
  169. #endif /* DYNAMIC_CRC_TABLE */
  170. return (const z_crc_t FAR *)crc_table;
  171. }
  172. /* ========================================================================= */
  173. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  174. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  175. /* ========================================================================= */
  176. unsigned long ZEXPORT crc32_z(crc, buf, len)
  177. unsigned long crc;
  178. const unsigned char FAR *buf;
  179. z_size_t len;
  180. {
  181. if (buf == Z_NULL) return 0UL;
  182. #ifdef DYNAMIC_CRC_TABLE
  183. if (crc_table_empty)
  184. make_crc_table();
  185. #endif /* DYNAMIC_CRC_TABLE */
  186. #ifdef BYFOUR
  187. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  188. z_crc_t endian;
  189. endian = 1;
  190. if (*((unsigned char *)(&endian)))
  191. return crc32_little(crc, buf, len);
  192. else
  193. return crc32_big(crc, buf, len);
  194. }
  195. #endif /* BYFOUR */
  196. crc = crc ^ 0xffffffffUL;
  197. while (len >= 8) {
  198. DO8;
  199. len -= 8;
  200. }
  201. if (len) do {
  202. DO1;
  203. } while (--len);
  204. return crc ^ 0xffffffffUL;
  205. }
  206. /* ========================================================================= */
  207. unsigned long ZEXPORT crc32(crc, buf, len)
  208. unsigned long crc;
  209. const unsigned char FAR *buf;
  210. uInt len;
  211. {
  212. return crc32_z(crc, buf, len);
  213. }
  214. #ifdef BYFOUR
  215. /*
  216. This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit
  217. integer pointer type. This violates the strict aliasing rule, where a
  218. compiler can assume, for optimization purposes, that two pointers to
  219. fundamentally different types won't ever point to the same memory. This can
  220. manifest as a problem only if one of the pointers is written to. This code
  221. only reads from those pointers. So long as this code remains isolated in
  222. this compilation unit, there won't be a problem. For this reason, this code
  223. should not be copied and pasted into a compilation unit in which other code
  224. writes to the buffer that is passed to these routines.
  225. */
  226. /* ========================================================================= */
  227. #define DOLIT4 c ^= *buf4++; \
  228. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  229. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  230. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  231. /* ========================================================================= */
  232. local unsigned long crc32_little(crc, buf, len)
  233. unsigned long crc;
  234. const unsigned char FAR *buf;
  235. z_size_t len;
  236. {
  237. register z_crc_t c;
  238. register const z_crc_t FAR *buf4;
  239. c = (z_crc_t)crc;
  240. c = ~c;
  241. while (len && ((ptrdiff_t)buf & 3)) {
  242. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  243. len--;
  244. }
  245. buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
  246. while (len >= 32) {
  247. DOLIT32;
  248. len -= 32;
  249. }
  250. while (len >= 4) {
  251. DOLIT4;
  252. len -= 4;
  253. }
  254. buf = (const unsigned char FAR *)buf4;
  255. if (len) do {
  256. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  257. } while (--len);
  258. c = ~c;
  259. return (unsigned long)c;
  260. }
  261. /* ========================================================================= */
  262. #define DOBIG4 c ^= *buf4++; \
  263. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  264. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  265. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  266. /* ========================================================================= */
  267. local unsigned long crc32_big(crc, buf, len)
  268. unsigned long crc;
  269. const unsigned char FAR *buf;
  270. z_size_t len;
  271. {
  272. register z_crc_t c;
  273. register const z_crc_t FAR *buf4;
  274. c = ZSWAP32((z_crc_t)crc);
  275. c = ~c;
  276. while (len && ((ptrdiff_t)buf & 3)) {
  277. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  278. len--;
  279. }
  280. buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
  281. while (len >= 32) {
  282. DOBIG32;
  283. len -= 32;
  284. }
  285. while (len >= 4) {
  286. DOBIG4;
  287. len -= 4;
  288. }
  289. buf = (const unsigned char FAR *)buf4;
  290. if (len) do {
  291. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  292. } while (--len);
  293. c = ~c;
  294. return (unsigned long)(ZSWAP32(c));
  295. }
  296. #endif /* BYFOUR */
  297. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  298. /* ========================================================================= */
  299. local unsigned long gf2_matrix_times(mat, vec)
  300. unsigned long *mat;
  301. unsigned long vec;
  302. {
  303. unsigned long sum;
  304. sum = 0;
  305. while (vec) {
  306. if (vec & 1)
  307. sum ^= *mat;
  308. vec >>= 1;
  309. mat++;
  310. }
  311. return sum;
  312. }
  313. /* ========================================================================= */
  314. local void gf2_matrix_square(square, mat)
  315. unsigned long *square;
  316. unsigned long *mat;
  317. {
  318. int n;
  319. for (n = 0; n < GF2_DIM; n++)
  320. square[n] = gf2_matrix_times(mat, mat[n]);
  321. }
  322. /* ========================================================================= */
  323. local uLong crc32_combine_(crc1, crc2, len2)
  324. uLong crc1;
  325. uLong crc2;
  326. z_off64_t len2;
  327. {
  328. int n;
  329. unsigned long row;
  330. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  331. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  332. /* degenerate case (also disallow negative lengths) */
  333. if (len2 <= 0)
  334. return crc1;
  335. /* put operator for one zero bit in odd */
  336. odd[0] = 0xedb88320UL; /* CRC-32 polynomial */
  337. row = 1;
  338. for (n = 1; n < GF2_DIM; n++) {
  339. odd[n] = row;
  340. row <<= 1;
  341. }
  342. /* put operator for two zero bits in even */
  343. gf2_matrix_square(even, odd);
  344. /* put operator for four zero bits in odd */
  345. gf2_matrix_square(odd, even);
  346. /* apply len2 zeros to crc1 (first square will put the operator for one
  347. zero byte, eight zero bits, in even) */
  348. do {
  349. /* apply zeros operator for this bit of len2 */
  350. gf2_matrix_square(even, odd);
  351. if (len2 & 1)
  352. crc1 = gf2_matrix_times(even, crc1);
  353. len2 >>= 1;
  354. /* if no more bits set, then done */
  355. if (len2 == 0)
  356. break;
  357. /* another iteration of the loop with odd and even swapped */
  358. gf2_matrix_square(odd, even);
  359. if (len2 & 1)
  360. crc1 = gf2_matrix_times(odd, crc1);
  361. len2 >>= 1;
  362. /* if no more bits set, then done */
  363. } while (len2 != 0);
  364. /* return combined crc */
  365. crc1 ^= crc2;
  366. return crc1;
  367. }
  368. /* ========================================================================= */
  369. uLong ZEXPORT crc32_combine(crc1, crc2, len2)
  370. uLong crc1;
  371. uLong crc2;
  372. z_off_t len2;
  373. {
  374. return crc32_combine_(crc1, crc2, len2);
  375. }
  376. uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
  377. uLong crc1;
  378. uLong crc2;
  379. z_off64_t len2;
  380. {
  381. return crc32_combine_(crc1, crc2, len2);
  382. }