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