crc32.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /* crc32.c -- compute the CRC-32 of a data stream
  2. * Copyright (C) 1995-2005 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. */
  19. #ifdef MAKECRCH
  20. # include <stdio.h>
  21. # ifndef DYNAMIC_CRC_TABLE
  22. # define DYNAMIC_CRC_TABLE
  23. # endif /* !DYNAMIC_CRC_TABLE */
  24. #endif /* MAKECRCH */
  25. #include "zutil.h" /* for STDC and FAR definitions */
  26. #define local static
  27. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  28. #ifndef NOBYFOUR
  29. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  30. # include <limits.h>
  31. # define BYFOUR
  32. # if (UINT_MAX == 0xffffffffUL)
  33. typedef unsigned int u4;
  34. # else
  35. # if (ULONG_MAX == 0xffffffffUL)
  36. typedef unsigned long u4;
  37. # else
  38. # if (USHRT_MAX == 0xffffffffUL)
  39. typedef unsigned short u4;
  40. # else
  41. # undef BYFOUR /* can't find a four-byte integer type! */
  42. # endif
  43. # endif
  44. # endif
  45. # endif /* STDC */
  46. #endif /* !NOBYFOUR */
  47. /* Definitions for doing the crc four data bytes at a time. */
  48. #ifdef BYFOUR
  49. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  50. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  51. local unsigned long crc32_little OF((unsigned long,
  52. const unsigned char FAR *, unsigned));
  53. local unsigned long crc32_big OF((unsigned long,
  54. const unsigned char FAR *, unsigned));
  55. # define TBLS 8
  56. #else
  57. # define TBLS 1
  58. #endif /* BYFOUR */
  59. /* Local functions for crc concatenation */
  60. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  61. unsigned long vec));
  62. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  63. #ifdef DYNAMIC_CRC_TABLE
  64. local volatile int crc_table_empty = 1;
  65. local unsigned long FAR crc_table[TBLS][256];
  66. local void make_crc_table OF((void));
  67. #ifdef MAKECRCH
  68. local void write_table OF((FILE *, const unsigned long FAR *));
  69. #endif /* MAKECRCH */
  70. /*
  71. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  72. 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.
  73. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  74. with the lowest powers in the most significant bit. Then adding polynomials
  75. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  76. one. If we call the above polynomial p, and represent a byte as the
  77. polynomial q, also with the lowest power in the most significant bit (so the
  78. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79. where a mod b means the remainder after dividing a by b.
  80. This calculation is done using the shift-register method of multiplying and
  81. taking the remainder. The register is initialized to zero, and for each
  82. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  83. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  84. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  85. out is a one). We start with the highest power (least significant bit) of
  86. q and repeat for all eight bits of q.
  87. The first table is simply the CRC of all possible eight bit values. This is
  88. all the information needed to generate CRCs on data a byte at a time for all
  89. combinations of CRC register values and incoming bytes. The remaining tables
  90. allow for word-at-a-time CRC calculation for both big-endian and little-
  91. endian machines, where a word is four bytes.
  92. */
  93. local void make_crc_table()
  94. {
  95. unsigned long c;
  96. int n, k;
  97. unsigned long poly; /* polynomial exclusive-or pattern */
  98. /* terms of polynomial defining this crc (except x^32): */
  99. static volatile int first = 1; /* flag to limit concurrent making */
  100. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  101. /* See if another task is already doing this (not thread-safe, but better
  102. than nothing -- significantly reduces duration of vulnerability in
  103. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  104. if (first) {
  105. first = 0;
  106. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  107. poly = 0UL;
  108. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  109. poly |= 1UL << (31 - p[n]);
  110. /* generate a crc for every 8-bit value */
  111. for (n = 0; n < 256; n++) {
  112. c = (unsigned long)n;
  113. for (k = 0; k < 8; k++)
  114. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  115. crc_table[0][n] = c;
  116. }
  117. #ifdef BYFOUR
  118. /* generate crc for each value followed by one, two, and three zeros,
  119. and then the byte reversal of those as well as the first table */
  120. for (n = 0; n < 256; n++) {
  121. c = crc_table[0][n];
  122. crc_table[4][n] = REV(c);
  123. for (k = 1; k < 4; k++) {
  124. c = crc_table[0][c & 0xff] ^ (c >> 8);
  125. crc_table[k][n] = c;
  126. crc_table[k + 4][n] = REV(c);
  127. }
  128. }
  129. #endif /* BYFOUR */
  130. crc_table_empty = 0;
  131. }
  132. else { /* not first */
  133. /* wait for the other guy to finish (not efficient, but rare) */
  134. while (crc_table_empty)
  135. ;
  136. }
  137. #ifdef MAKECRCH
  138. /* write out CRC tables to crc32.h */
  139. {
  140. FILE *out;
  141. out = fopen("crc32.h", "w");
  142. if (out == NULL) return;
  143. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  144. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  145. fprintf(out, "local const unsigned long FAR ");
  146. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  147. write_table(out, crc_table[0]);
  148. # ifdef BYFOUR
  149. fprintf(out, "#ifdef BYFOUR\n");
  150. for (k = 1; k < 8; k++) {
  151. fprintf(out, " },\n {\n");
  152. write_table(out, crc_table[k]);
  153. }
  154. fprintf(out, "#endif\n");
  155. # endif /* BYFOUR */
  156. fprintf(out, " }\n};\n");
  157. fclose(out);
  158. }
  159. #endif /* MAKECRCH */
  160. }
  161. #ifdef MAKECRCH
  162. local void write_table(out, table)
  163. FILE *out;
  164. const unsigned long FAR *table;
  165. {
  166. int n;
  167. for (n = 0; n < 256; n++)
  168. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  169. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  170. }
  171. #endif /* MAKECRCH */
  172. #else /* !DYNAMIC_CRC_TABLE */
  173. /* ========================================================================
  174. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  175. */
  176. #include "crc32.h"
  177. #endif /* DYNAMIC_CRC_TABLE */
  178. /* =========================================================================
  179. * This function can be used by asm versions of crc32()
  180. */
  181. const unsigned long FAR * ZEXPORT get_crc_table()
  182. {
  183. #ifdef DYNAMIC_CRC_TABLE
  184. if (crc_table_empty)
  185. make_crc_table();
  186. #endif /* DYNAMIC_CRC_TABLE */
  187. return (const unsigned long FAR *)crc_table;
  188. }
  189. /* ========================================================================= */
  190. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  191. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  192. /* ========================================================================= */
  193. unsigned long ZEXPORT crc32(crc, buf, len)
  194. unsigned long crc;
  195. const unsigned char FAR *buf;
  196. unsigned len;
  197. {
  198. if (buf == Z_NULL) return 0UL;
  199. #ifdef DYNAMIC_CRC_TABLE
  200. if (crc_table_empty)
  201. make_crc_table();
  202. #endif /* DYNAMIC_CRC_TABLE */
  203. #ifdef BYFOUR
  204. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  205. u4 endian;
  206. endian = 1;
  207. if (*((unsigned char *)(&endian)))
  208. return crc32_little(crc, buf, len);
  209. else
  210. return crc32_big(crc, buf, len);
  211. }
  212. #endif /* BYFOUR */
  213. crc = crc ^ 0xffffffffUL;
  214. while (len >= 8) {
  215. DO8;
  216. len -= 8;
  217. }
  218. if (len) do {
  219. DO1;
  220. } while (--len);
  221. return crc ^ 0xffffffffUL;
  222. }
  223. #ifdef BYFOUR
  224. /* ========================================================================= */
  225. #define DOLIT4 c ^= *buf4++; \
  226. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  227. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  228. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  229. /* ========================================================================= */
  230. local unsigned long crc32_little(crc, buf, len)
  231. unsigned long crc;
  232. const unsigned char FAR *buf;
  233. unsigned len;
  234. {
  235. register u4 c;
  236. register const u4 FAR *buf4;
  237. c = (u4)crc;
  238. c = ~c;
  239. while (len && ((ptrdiff_t)buf & 3)) {
  240. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  241. len--;
  242. }
  243. buf4 = (const u4 FAR *)(const void FAR *)buf;
  244. while (len >= 32) {
  245. DOLIT32;
  246. len -= 32;
  247. }
  248. while (len >= 4) {
  249. DOLIT4;
  250. len -= 4;
  251. }
  252. buf = (const unsigned char FAR *)buf4;
  253. if (len) do {
  254. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  255. } while (--len);
  256. c = ~c;
  257. return (unsigned long)c;
  258. }
  259. /* ========================================================================= */
  260. #define DOBIG4 c ^= *++buf4; \
  261. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  262. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  263. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  264. /* ========================================================================= */
  265. local unsigned long crc32_big(crc, buf, len)
  266. unsigned long crc;
  267. const unsigned char FAR *buf;
  268. unsigned len;
  269. {
  270. register u4 c;
  271. register const u4 FAR *buf4;
  272. c = REV((u4)crc);
  273. c = ~c;
  274. while (len && ((ptrdiff_t)buf & 3)) {
  275. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  276. len--;
  277. }
  278. buf4 = (const u4 FAR *)(const void FAR *)buf;
  279. buf4--;
  280. while (len >= 32) {
  281. DOBIG32;
  282. len -= 32;
  283. }
  284. while (len >= 4) {
  285. DOBIG4;
  286. len -= 4;
  287. }
  288. buf4++;
  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)(REV(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. uLong ZEXPORT crc32_combine(crc1, crc2, len2)
  324. uLong crc1;
  325. uLong crc2;
  326. z_off_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 */
  333. if (len2 == 0)
  334. return crc1;
  335. /* put operator for one zero bit in odd */
  336. odd[0] = 0xedb88320L; /* 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. }