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