crc32.cc

Go to the documentation of this file.
00001 /* crc32.c -- compute the CRC-32 of a data stream
00002  * Copyright (C) 1995-2003 Mark Adler
00003  * For conditions of distribution and use, see copyright notice in zlib.h
00004  *
00005  * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
00006  * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
00007  * tables for updating the shift register in one step with three exclusive-ors
00008  * instead of four steps with four exclusive-ors.  This results about a factor
00009  * of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
00010  */
00011 
00012 /* @(#) $Id: crc32.cc,v 1.1 2005-05-12 21:04:53 duns Exp $ */
00013 
00014 /*
00015   Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
00016   protection on the static variables used to control the first-use generation
00017   of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
00018   first call get_crc_table() to initialize the tables before allowing more than
00019   one thread to use crc32().
00020  */
00021 
00022 #ifdef MAKECRCH
00023 #  include <stdio.h>
00024 #  ifndef DYNAMIC_CRC_TABLE
00025 #    define DYNAMIC_CRC_TABLE
00026 #  endif /* !DYNAMIC_CRC_TABLE */
00027 #endif /* MAKECRCH */
00028 
00029 #include "zutil.h"      /* for STDC and FAR definitions */
00030 
00031 #define local static
00032 
00033 /* Find a four-byte integer type for crc32_little() and crc32_big(). */
00034 #ifndef NOBYFOUR
00035 #  ifdef STDC           /* need ANSI C limits.h to determine sizes */
00036 #    include <limits.h>
00037 #    define BYFOUR
00038 #    if (UINT_MAX == 0xffffffffUL)
00039        typedef unsigned int u4;
00040 #    else
00041 #      if (ULONG_MAX == 0xffffffffUL)
00042          typedef unsigned long u4;
00043 #      else
00044 #        if (USHRT_MAX == 0xffffffffUL)
00045            typedef unsigned short u4;
00046 #        else
00047 #          undef BYFOUR     /* can't find a four-byte integer type! */
00048 #        endif
00049 #      endif
00050 #    endif
00051 #  endif /* STDC */
00052 #endif /* !NOBYFOUR */
00053 
00054 /* Definitions for doing the crc four data bytes at a time. */
00055 #ifdef BYFOUR
00056 #  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
00057                 (((w)&0xff00)<<8)+(((w)&0xff)<<24))
00058    local unsigned long crc32_little OF((unsigned long,
00059                         const unsigned char FAR *, unsigned));
00060    local unsigned long crc32_big OF((unsigned long,
00061                         const unsigned char FAR *, unsigned));
00062 #  define TBLS 8
00063 #else
00064 #  define TBLS 1
00065 #endif /* BYFOUR */
00066 
00067 #ifdef DYNAMIC_CRC_TABLE
00068 
00069 local volatile int crc_table_empty = 1;
00070 local unsigned long FAR crc_table[TBLS][256];
00071 local void make_crc_table OF((void));
00072 #ifdef MAKECRCH
00073    local void write_table OF((FILE *, const unsigned long FAR *));
00074 #endif /* MAKECRCH */
00075 
00076 /*
00077   Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
00078   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.
00079 
00080   Polynomials over GF(2) are represented in binary, one bit per coefficient,
00081   with the lowest powers in the most significant bit.  Then adding polynomials
00082   is just exclusive-or, and multiplying a polynomial by x is a right shift by
00083   one.  If we call the above polynomial p, and represent a byte as the
00084   polynomial q, also with the lowest power in the most significant bit (so the
00085   byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
00086   where a mod b means the remainder after dividing a by b.
00087 
00088   This calculation is done using the shift-register method of multiplying and
00089   taking the remainder.  The register is initialized to zero, and for each
00090   incoming bit, x^32 is added mod p to the register if the bit is a one (where
00091   x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
00092   x (which is shifting right by one and adding x^32 mod p if the bit shifted
00093   out is a one).  We start with the highest power (least significant bit) of
00094   q and repeat for all eight bits of q.
00095 
00096   The first table is simply the CRC of all possible eight bit values.  This is
00097   all the information needed to generate CRCs on data a byte at a time for all
00098   combinations of CRC register values and incoming bytes.  The remaining tables
00099   allow for word-at-a-time CRC calculation for both big-endian and little-
00100   endian machines, where a word is four bytes.
00101 */
00102 local void make_crc_table()
00103 {
00104     unsigned long c;
00105     int n, k;
00106     unsigned long poly;                 /* polynomial exclusive-or pattern */
00107     /* terms of polynomial defining this crc (except x^32): */
00108     static volatile int first = 1;      /* flag to limit concurrent making */
00109     static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
00110 
00111     /* See if another task is already doing this (not thread-safe, but better
00112        than nothing -- significantly reduces duration of vulnerability in
00113        case the advice about DYNAMIC_CRC_TABLE is ignored) */
00114     if (first) {
00115         first = 0;
00116 
00117         /* make exclusive-or pattern from polynomial (0xedb88320UL) */
00118         poly = 0UL;
00119         for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
00120             poly |= 1UL << (31 - p[n]);
00121 
00122         /* generate a crc for every 8-bit value */
00123         for (n = 0; n < 256; n++) {
00124             c = (unsigned long)n;
00125             for (k = 0; k < 8; k++)
00126                 c = c & 1 ? poly ^ (c >> 1) : c >> 1;
00127             crc_table[0][n] = c;
00128         }
00129 
00130 #ifdef BYFOUR
00131         /* generate crc for each value followed by one, two, and three zeros,
00132            and then the byte reversal of those as well as the first table */
00133         for (n = 0; n < 256; n++) {
00134             c = crc_table[0][n];
00135             crc_table[4][n] = REV(c);
00136             for (k = 1; k < 4; k++) {
00137                 c = crc_table[0][c & 0xff] ^ (c >> 8);
00138                 crc_table[k][n] = c;
00139                 crc_table[k + 4][n] = REV(c);
00140             }
00141         }
00142 #endif /* BYFOUR */
00143 
00144         crc_table_empty = 0;
00145     }
00146     else {      /* not first */
00147         /* wait for the other guy to finish (not efficient, but rare) */
00148         while (crc_table_empty)
00149             ;
00150     }
00151 
00152 #ifdef MAKECRCH
00153     /* write out CRC tables to crc32.h */
00154     {
00155         FILE *out;
00156 
00157         out = fopen("crc32.h", "w");
00158         if (out == NULL) return;
00159         fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
00160         fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
00161         fprintf(out, "local const unsigned long FAR ");
00162         fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
00163         write_table(out, crc_table[0]);
00164 #  ifdef BYFOUR
00165         fprintf(out, "#ifdef BYFOUR\n");
00166         for (k = 1; k < 8; k++) {
00167             fprintf(out, "  },\n  {\n");
00168             write_table(out, crc_table[k]);
00169         }
00170         fprintf(out, "#endif\n");
00171 #  endif /* BYFOUR */
00172         fprintf(out, "  }\n};\n");
00173         fclose(out);
00174     }
00175 #endif /* MAKECRCH */
00176 }
00177 
00178 #ifdef MAKECRCH
00179 local void write_table(FILE *out, const unsigned long FAR *table)
00180 {
00181     int n;
00182 
00183     for (n = 0; n < 256; n++)
00184         fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ", table[n],
00185                 n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
00186 }
00187 #endif /* MAKECRCH */
00188 
00189 #else /* !DYNAMIC_CRC_TABLE */
00190 /* ========================================================================
00191  * Tables of CRC-32s of all single-byte values, made by make_crc_table().
00192  */
00193 #include "crc32.h"
00194 #endif /* DYNAMIC_CRC_TABLE */
00195 
00196 /* =========================================================================
00197  * This function can be used by asm versions of crc32()
00198  */
00199 const unsigned long FAR * ZEXPORT get_crc_table()
00200 {
00201 #ifdef DYNAMIC_CRC_TABLE
00202     if (crc_table_empty)
00203         make_crc_table();
00204 #endif /* DYNAMIC_CRC_TABLE */
00205     return (const unsigned long FAR *)crc_table;
00206 }
00207 
00208 /* ========================================================================= */
00209 #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
00210 #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
00211 
00212 /* ========================================================================= */
00213 unsigned long ZEXPORT crc32(unsigned long crc, const unsigned char FAR *buf, unsigned len)
00214 {
00215     if (buf == Z_NULL) return 0UL;
00216 
00217 #ifdef DYNAMIC_CRC_TABLE
00218     if (crc_table_empty)
00219         make_crc_table();
00220 #endif /* DYNAMIC_CRC_TABLE */
00221 
00222 #ifdef BYFOUR
00223     if (sizeof(void *) == sizeof(ptrdiff_t)) {
00224         u4 endian;
00225 
00226         endian = 1;
00227         if (*((unsigned char *)(&endian)))
00228             return crc32_little(crc, buf, len);
00229         else
00230             return crc32_big(crc, buf, len);
00231     }
00232 #endif /* BYFOUR */
00233     crc = crc ^ 0xffffffffUL;
00234     while (len >= 8) {
00235         DO8;
00236         len -= 8;
00237     }
00238     if (len) do {
00239         DO1;
00240     } while (--len);
00241     return crc ^ 0xffffffffUL;
00242 }
00243 
00244 #ifdef BYFOUR
00245 
00246 /* ========================================================================= */
00247 #define DOLIT4 c ^= *buf4++; \
00248         c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
00249             crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
00250 #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
00251 
00252 /* ========================================================================= */
00253 local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
00254 {
00255     register u4 c;
00256     register const u4 FAR *buf4;
00257 
00258     c = (u4)crc;
00259     c = ~c;
00260     while (len && ((ptrdiff_t)buf & 3)) {
00261         c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
00262         len--;
00263     }
00264 
00265     buf4 = (const u4 FAR *)buf;
00266     while (len >= 32) {
00267         DOLIT32;
00268         len -= 32;
00269     }
00270     while (len >= 4) {
00271         DOLIT4;
00272         len -= 4;
00273     }
00274     buf = (const unsigned char FAR *)buf4;
00275 
00276     if (len) do {
00277         c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
00278     } while (--len);
00279     c = ~c;
00280     return (unsigned long)c;
00281 }
00282 
00283 /* ========================================================================= */
00284 #define DOBIG4 c ^= *++buf4; \
00285         c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
00286             crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
00287 #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
00288 
00289 /* ========================================================================= */
00290 local unsigned long crc32_big(unsigned long crc, const unsigned char FAR *buf, unsigned len)
00291 {
00292     register u4 c;
00293     register const u4 FAR *buf4;
00294 
00295     c = REV((u4)crc);
00296     c = ~c;
00297     while (len && ((ptrdiff_t)buf & 3)) {
00298         c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
00299         len--;
00300     }
00301 
00302     buf4 = (const u4 FAR *)buf;
00303     buf4--;
00304     while (len >= 32) {
00305         DOBIG32;
00306         len -= 32;
00307     }
00308     while (len >= 4) {
00309         DOBIG4;
00310         len -= 4;
00311     }
00312     buf4++;
00313     buf = (const unsigned char FAR *)buf4;
00314 
00315     if (len) do {
00316         c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
00317     } while (--len);
00318     c = ~c;
00319     return (unsigned long)(REV(c));
00320 }
00321 
00322 #endif /* BYFOUR */

Generated on Mon May 27 17:47:34 2013 for Geant4 by  doxygen 1.4.7