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