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