2
0

crc32.c 14 KB

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