crc32.c 13.7 KB
Newer Older
M
Mark Adler 已提交
1
/* crc32.c -- compute the CRC-32 of a data stream
M
Mark Adler 已提交
2
 * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler
M
Mark Adler 已提交
3 4 5 6 7
 * For conditions of distribution and use, see copyright notice in zlib.h
 *
 * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
 * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
 * tables for updating the shift register in one step with three exclusive-ors
M
Mark Adler 已提交
8 9
 * instead of four steps with four exclusive-ors.  This results in about a
 * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
M
Mark Adler 已提交
10 11
 */

M
Mark Adler 已提交
12
/* @(#) $Id$ */
M
Mark Adler 已提交
13

M
Mark Adler 已提交
14
/*
M
Mark Adler 已提交
15 16 17 18 19
  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  protection on the static variables used to control the first-use generation
  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  first call get_crc_table() to initialize the tables before allowing more than
  one thread to use crc32().
M
Mark Adler 已提交
20 21

  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
M
Mark Adler 已提交
22 23
 */

M
Mark Adler 已提交
24 25 26 27 28 29 30
#ifdef MAKECRCH
#  include <stdio.h>
#  ifndef DYNAMIC_CRC_TABLE
#    define DYNAMIC_CRC_TABLE
#  endif /* !DYNAMIC_CRC_TABLE */
#endif /* MAKECRCH */

M
Mark Adler 已提交
31
#include "zutil.h"      /* for STDC and FAR definitions */
M
Mark Adler 已提交
32

M
Mark Adler 已提交
33
/* Definitions for doing the crc four data bytes at a time. */
34 35 36
#if !defined(NOBYFOUR) && defined(Z_U4)
#  define BYFOUR
#endif
M
Mark Adler 已提交
37 38
#ifdef BYFOUR
   local unsigned long crc32_little OF((unsigned long,
39
                        const unsigned char FAR *, z_size_t));
M
Mark Adler 已提交
40
   local unsigned long crc32_big OF((unsigned long,
41
                        const unsigned char FAR *, z_size_t));
M
Mark Adler 已提交
42 43 44 45 46
#  define TBLS 8
#else
#  define TBLS 1
#endif /* BYFOUR */

M
Mark Adler 已提交
47 48 49 50
/* Local functions for crc concatenation */
local unsigned long gf2_matrix_times OF((unsigned long *mat,
                                         unsigned long vec));
local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
M
Mark Adler 已提交
51
local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
M
Mark Adler 已提交
52

M
Mark Adler 已提交
53

M
Mark Adler 已提交
54
#ifdef DYNAMIC_CRC_TABLE
M
Mark Adler 已提交
55

M
Mark Adler 已提交
56
local volatile int crc_table_empty = 1;
57
local z_crc_t FAR crc_table[TBLS][256];
M
Mark Adler 已提交
58
local void make_crc_table OF((void));
M
Mark Adler 已提交
59
#ifdef MAKECRCH
60
   local void write_table OF((FILE *, const z_crc_t FAR *));
M
Mark Adler 已提交
61
#endif /* MAKECRCH */
M
Mark Adler 已提交
62
/*
M
Mark Adler 已提交
63
  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
M
Mark Adler 已提交
64
  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.
M
Mark Adler 已提交
65

M
Mark Adler 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  Polynomials over GF(2) are represented in binary, one bit per coefficient,
  with the lowest powers in the most significant bit.  Then adding polynomials
  is just exclusive-or, and multiplying a polynomial by x is a right shift by
  one.  If we call the above polynomial p, and represent a byte as the
  polynomial q, also with the lowest power in the most significant bit (so the
  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  where a mod b means the remainder after dividing a by b.

  This calculation is done using the shift-register method of multiplying and
  taking the remainder.  The register is initialized to zero, and for each
  incoming bit, x^32 is added mod p to the register if the bit is a one (where
  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  x (which is shifting right by one and adding x^32 mod p if the bit shifted
  out is a one).  We start with the highest power (least significant bit) of
  q and repeat for all eight bits of q.

M
Mark Adler 已提交
82 83 84 85 86
  The first table is simply the CRC of all possible eight bit values.  This is
  all the information needed to generate CRCs on data a byte at a time for all
  combinations of CRC register values and incoming bytes.  The remaining tables
  allow for word-at-a-time CRC calculation for both big-endian and little-
  endian machines, where a word is four bytes.
M
Mark Adler 已提交
87
*/
M
Mark Adler 已提交
88
local void make_crc_table()
M
Mark Adler 已提交
89
{
90
    z_crc_t c;
M
Mark Adler 已提交
91
    int n, k;
92
    z_crc_t poly;                       /* polynomial exclusive-or pattern */
M
Mark Adler 已提交
93
    /* terms of polynomial defining this crc (except x^32): */
M
Mark Adler 已提交
94
    static volatile int first = 1;      /* flag to limit concurrent making */
M
Mark Adler 已提交
95 96
    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};

M
Mark Adler 已提交
97 98 99 100 101 102 103
    /* See if another task is already doing this (not thread-safe, but better
       than nothing -- significantly reduces duration of vulnerability in
       case the advice about DYNAMIC_CRC_TABLE is ignored) */
    if (first) {
        first = 0;

        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
M
Mark Adler 已提交
104 105
        poly = 0;
        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
106
            poly |= (z_crc_t)1 << (31 - p[n]);
M
Mark Adler 已提交
107 108 109

        /* generate a crc for every 8-bit value */
        for (n = 0; n < 256; n++) {
110
            c = (z_crc_t)n;
M
Mark Adler 已提交
111 112 113 114
            for (k = 0; k < 8; k++)
                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
            crc_table[0][n] = c;
        }
M
Mark Adler 已提交
115 116

#ifdef BYFOUR
M
Mark Adler 已提交
117 118 119 120
        /* generate crc for each value followed by one, two, and three zeros,
           and then the byte reversal of those as well as the first table */
        for (n = 0; n < 256; n++) {
            c = crc_table[0][n];
121
            crc_table[4][n] = ZSWAP32(c);
M
Mark Adler 已提交
122 123 124
            for (k = 1; k < 4; k++) {
                c = crc_table[0][c & 0xff] ^ (c >> 8);
                crc_table[k][n] = c;
125
                crc_table[k + 4][n] = ZSWAP32(c);
M
Mark Adler 已提交
126 127
            }
        }
M
Mark Adler 已提交
128 129
#endif /* BYFOUR */

M
Mark Adler 已提交
130 131 132 133 134 135 136
        crc_table_empty = 0;
    }
    else {      /* not first */
        /* wait for the other guy to finish (not efficient, but rare) */
        while (crc_table_empty)
            ;
    }
M
Mark Adler 已提交
137 138 139 140 141 142 143 144 145 146

#ifdef MAKECRCH
    /* write out CRC tables to crc32.h */
    {
        FILE *out;

        out = fopen("crc32.h", "w");
        if (out == NULL) return;
        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
147
        fprintf(out, "local const z_crc_t FAR ");
M
Mark Adler 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161
        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
        write_table(out, crc_table[0]);
#  ifdef BYFOUR
        fprintf(out, "#ifdef BYFOUR\n");
        for (k = 1; k < 8; k++) {
            fprintf(out, "  },\n  {\n");
            write_table(out, crc_table[k]);
        }
        fprintf(out, "#endif\n");
#  endif /* BYFOUR */
        fprintf(out, "  }\n};\n");
        fclose(out);
    }
#endif /* MAKECRCH */
M
Mark Adler 已提交
162
}
M
Mark Adler 已提交
163 164 165 166

#ifdef MAKECRCH
local void write_table(out, table)
    FILE *out;
167
    const z_crc_t FAR *table;
M
Mark Adler 已提交
168 169 170 171
{
    int n;

    for (n = 0; n < 256; n++)
M
Mark Adler 已提交
172 173
        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
                (unsigned long)(table[n]),
M
Mark Adler 已提交
174 175 176 177 178
                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
}
#endif /* MAKECRCH */

#else /* !DYNAMIC_CRC_TABLE */
M
Mark Adler 已提交
179
/* ========================================================================
M
Mark Adler 已提交
180
 * Tables of CRC-32s of all single-byte values, made by make_crc_table().
M
Mark Adler 已提交
181
 */
M
Mark Adler 已提交
182 183
#include "crc32.h"
#endif /* DYNAMIC_CRC_TABLE */
M
Mark Adler 已提交
184

M
Mark Adler 已提交
185 186 187
/* =========================================================================
 * This function can be used by asm versions of crc32()
 */
188
const z_crc_t FAR * ZEXPORT get_crc_table()
M
Mark Adler 已提交
189 190
{
#ifdef DYNAMIC_CRC_TABLE
M
Mark Adler 已提交
191 192
    if (crc_table_empty)
        make_crc_table();
M
Mark Adler 已提交
193
#endif /* DYNAMIC_CRC_TABLE */
194
    return (const z_crc_t FAR *)crc_table;
M
Mark Adler 已提交
195 196 197
}

/* ========================================================================= */
M
Mark Adler 已提交
198 199
#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
M
Mark Adler 已提交
200 201

/* ========================================================================= */
202
unsigned long ZEXPORT crc32_z(crc, buf, len)
M
Mark Adler 已提交
203 204
    unsigned long crc;
    const unsigned char FAR *buf;
205
    z_size_t len;
M
Mark Adler 已提交
206
{
M
Mark Adler 已提交
207 208
    if (buf == Z_NULL) return 0UL;

M
Mark Adler 已提交
209 210
#ifdef DYNAMIC_CRC_TABLE
    if (crc_table_empty)
M
Mark Adler 已提交
211 212 213 214
        make_crc_table();
#endif /* DYNAMIC_CRC_TABLE */

#ifdef BYFOUR
M
Mark Adler 已提交
215
    if (sizeof(void *) == sizeof(ptrdiff_t)) {
216
        z_crc_t endian;
M
Mark Adler 已提交
217 218 219 220 221 222 223

        endian = 1;
        if (*((unsigned char *)(&endian)))
            return crc32_little(crc, buf, len);
        else
            return crc32_big(crc, buf, len);
    }
M
Mark Adler 已提交
224
#endif /* BYFOUR */
M
Mark Adler 已提交
225 226 227 228 229 230 231 232 233 234 235
    crc = crc ^ 0xffffffffUL;
    while (len >= 8) {
        DO8;
        len -= 8;
    }
    if (len) do {
        DO1;
    } while (--len);
    return crc ^ 0xffffffffUL;
}

236 237 238 239 240 241 242 243 244
/* ========================================================================= */
unsigned long ZEXPORT crc32(crc, buf, len)
    unsigned long crc;
    const unsigned char FAR *buf;
    uInt len;
{
    return crc32_z(crc, buf, len);
}

M
Mark Adler 已提交
245 246
#ifdef BYFOUR

247 248 249 250 251 252 253 254 255 256 257 258
/*
   This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit
   integer pointer type. This violates the strict aliasing rule, where a
   compiler can assume, for optimization purposes, that two pointers to
   fundamentally different types won't ever point to the same memory. This can
   manifest as a problem only if one of the pointers is written to. This code
   only reads from those pointers. So long as this code remains isolated in
   this compilation unit, there won't be a problem. For this reason, this code
   should not be copied and pasted into a compilation unit in which other code
   writes to the buffer that is passed to these routines.
 */

M
Mark Adler 已提交
259 260 261 262 263 264 265 266 267 268
/* ========================================================================= */
#define DOLIT4 c ^= *buf4++; \
        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4

/* ========================================================================= */
local unsigned long crc32_little(crc, buf, len)
    unsigned long crc;
    const unsigned char FAR *buf;
269
    z_size_t len;
M
Mark Adler 已提交
270
{
271 272
    register z_crc_t c;
    register const z_crc_t FAR *buf4;
M
Mark Adler 已提交
273

274
    c = (z_crc_t)crc;
M
Mark Adler 已提交
275
    c = ~c;
M
Mark Adler 已提交
276
    while (len && ((ptrdiff_t)buf & 3)) {
M
Mark Adler 已提交
277 278 279 280
        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
        len--;
    }

281
    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
M
Mark Adler 已提交
282 283 284 285 286 287 288
    while (len >= 32) {
        DOLIT32;
        len -= 32;
    }
    while (len >= 4) {
        DOLIT4;
        len -= 4;
M
Mark Adler 已提交
289
    }
M
Mark Adler 已提交
290 291
    buf = (const unsigned char FAR *)buf4;

M
Mark Adler 已提交
292
    if (len) do {
M
Mark Adler 已提交
293
        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
M
Mark Adler 已提交
294
    } while (--len);
M
Mark Adler 已提交
295 296
    c = ~c;
    return (unsigned long)c;
M
Mark Adler 已提交
297
}
M
Mark Adler 已提交
298 299

/* ========================================================================= */
300
#define DOBIG4 c ^= *buf4++; \
M
Mark Adler 已提交
301 302 303 304 305 306 307 308
        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4

/* ========================================================================= */
local unsigned long crc32_big(crc, buf, len)
    unsigned long crc;
    const unsigned char FAR *buf;
309
    z_size_t len;
M
Mark Adler 已提交
310
{
311 312
    register z_crc_t c;
    register const z_crc_t FAR *buf4;
M
Mark Adler 已提交
313

314
    c = ZSWAP32((z_crc_t)crc);
M
Mark Adler 已提交
315
    c = ~c;
M
Mark Adler 已提交
316
    while (len && ((ptrdiff_t)buf & 3)) {
M
Mark Adler 已提交
317 318 319 320
        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
        len--;
    }

321
    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
M
Mark Adler 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335
    while (len >= 32) {
        DOBIG32;
        len -= 32;
    }
    while (len >= 4) {
        DOBIG4;
        len -= 4;
    }
    buf = (const unsigned char FAR *)buf4;

    if (len) do {
        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
    } while (--len);
    c = ~c;
336
    return (unsigned long)(ZSWAP32(c));
M
Mark Adler 已提交
337 338 339
}

#endif /* BYFOUR */
M
Mark Adler 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */

/* ========================================================================= */
local unsigned long gf2_matrix_times(mat, vec)
    unsigned long *mat;
    unsigned long vec;
{
    unsigned long sum;

    sum = 0;
    while (vec) {
        if (vec & 1)
            sum ^= *mat;
        vec >>= 1;
        mat++;
    }
    return sum;
}

/* ========================================================================= */
local void gf2_matrix_square(square, mat)
    unsigned long *square;
    unsigned long *mat;
{
    int n;

    for (n = 0; n < GF2_DIM; n++)
        square[n] = gf2_matrix_times(mat, mat[n]);
}

/* ========================================================================= */
M
Mark Adler 已提交
372
local uLong crc32_combine_(crc1, crc2, len2)
M
Mark Adler 已提交
373 374
    uLong crc1;
    uLong crc2;
M
Mark Adler 已提交
375
    z_off64_t len2;
M
Mark Adler 已提交
376 377 378 379 380 381
{
    int n;
    unsigned long row;
    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */

M
Mark Adler 已提交
382 383
    /* degenerate case (also disallow negative lengths) */
    if (len2 <= 0)
M
Mark Adler 已提交
384 385 386
        return crc1;

    /* put operator for one zero bit in odd */
M
Mark Adler 已提交
387
    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
M
Mark Adler 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    row = 1;
    for (n = 1; n < GF2_DIM; n++) {
        odd[n] = row;
        row <<= 1;
    }

    /* put operator for two zero bits in even */
    gf2_matrix_square(even, odd);

    /* put operator for four zero bits in odd */
    gf2_matrix_square(odd, even);

    /* apply len2 zeros to crc1 (first square will put the operator for one
       zero byte, eight zero bits, in even) */
    do {
        /* apply zeros operator for this bit of len2 */
        gf2_matrix_square(even, odd);
        if (len2 & 1)
            crc1 = gf2_matrix_times(even, crc1);
        len2 >>= 1;

        /* if no more bits set, then done */
        if (len2 == 0)
            break;

        /* another iteration of the loop with odd and even swapped */
        gf2_matrix_square(odd, even);
        if (len2 & 1)
            crc1 = gf2_matrix_times(odd, crc1);
        len2 >>= 1;

        /* if no more bits set, then done */
    } while (len2 != 0);

    /* return combined crc */
    crc1 ^= crc2;
    return crc1;
}
M
Mark Adler 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438

/* ========================================================================= */
uLong ZEXPORT crc32_combine(crc1, crc2, len2)
    uLong crc1;
    uLong crc2;
    z_off_t len2;
{
    return crc32_combine_(crc1, crc2, len2);
}

uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
    uLong crc1;
    uLong crc2;
M
Mark Adler 已提交
439
    z_off64_t len2;
M
Mark Adler 已提交
440 441 442
{
    return crc32_combine_(crc1, crc2, len2);
}