Coverage Report

Created: 2026-08-14 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/crc/internal/crc.cc
Line
Count
Source
1
// Copyright 2022 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
// Implementation of CRCs (aka Rabin Fingerprints).
16
// Treats the input as a polynomial with coefficients in Z(2),
17
// and finds the remainder when divided by an irreducible polynomial
18
// of the appropriate length.
19
// It handles all CRC sizes from 8 to 128 bits.
20
// It's somewhat complicated by having separate implementations optimized for
21
// CRC's <=32 bits, <= 64 bits, and <= 128 bits.
22
// The input string is prefixed with a "1" bit, and has "degree" "0" bits
23
// appended to it before the remainder is found.   This ensures that
24
// short strings are scrambled somewhat and that strings consisting
25
// of all nulls have a non-zero CRC.
26
//
27
// Uses the "interleaved word-by-word" method from
28
// "Everything we know about CRC but afraid to forget" by Andrew Kadatch
29
// and Bob Jenkins,
30
// http://crcutil.googlecode.com/files/crc-doc.1.0.pdf
31
//
32
// The idea is to compute kStride CRCs simultaneously, allowing the
33
// processor to more effectively use multiple execution units. Each of
34
// the CRCs is calculated on one word of data followed by kStride - 1
35
// words of zeroes; the CRC starting points are staggered by one word.
36
// Assuming a stride of 4 with data words "ABCDABCDABCD", the first
37
// CRC is over A000A000A, the second over 0B000B000B, and so on.
38
// The CRC of the whole data is then calculated by properly aligning the
39
// CRCs by appending zeroes until the data lengths agree then XORing
40
// the CRCs.
41
42
#include "absl/crc/internal/crc.h"
43
44
#include <cstdint>
45
46
#include "absl/base/internal/endian.h"
47
#include "absl/base/internal/raw_logging.h"
48
#include "absl/base/prefetch.h"
49
#include "absl/crc/internal/crc_internal.h"
50
#include "absl/numeric/bits.h"
51
52
namespace absl {
53
ABSL_NAMESPACE_BEGIN
54
namespace crc_internal {
55
56
namespace {
57
58
// Constants
59
#if defined(__i386__) || defined(__x86_64__)
60
constexpr bool kNeedAlignedLoads = false;
61
#else
62
constexpr bool kNeedAlignedLoads = true;
63
#endif
64
65
// We express the number of zeroes as a number in base ZEROES_BASE. By
66
// pre-computing the zero extensions for all possible components of such an
67
// expression (numbers in a form a*ZEROES_BASE**b), we can calculate the
68
// resulting extension by multiplying the extensions for individual components
69
// using log_{ZEROES_BASE}(num_zeroes) polynomial multiplications. The tables of
70
// zero extensions contain (ZEROES_BASE - 1) * (log_{ZEROES_BASE}(64)) entries.
71
constexpr int ZEROES_BASE_LG = 4;                   // log_2(ZEROES_BASE)
72
constexpr int ZEROES_BASE = (1 << ZEROES_BASE_LG);  // must be a power of 2
73
74
constexpr uint32_t kCrc32cPoly = 0x82f63b78;
75
76
0
uint32_t ReverseBits(uint32_t bits) {
77
0
  bits = (bits & 0xaaaaaaaau) >> 1 | (bits & 0x55555555u) << 1;
78
0
  bits = (bits & 0xccccccccu) >> 2 | (bits & 0x33333333u) << 2;
79
0
  bits = (bits & 0xf0f0f0f0u) >> 4 | (bits & 0x0f0f0f0fu) << 4;
80
0
  return absl::gbswap_32(bits);
81
0
}
82
83
// Polynomial long multiplication mod the polynomial of degree 32.
84
0
void PolyMultiply(uint32_t* val, uint32_t m, uint32_t poly) {
85
0
  uint32_t l = *val;
86
0
  uint32_t result = 0;
87
0
  auto onebit = uint32_t{0x80000000u};
88
0
  for (uint32_t one = onebit; one != 0; one >>= 1) {
89
0
    if ((l & one) != 0) {
90
0
      result ^= m;
91
0
    }
92
0
    if (m & 1) {
93
0
      m = (m >> 1) ^ poly;
94
0
    } else {
95
0
      m >>= 1;
96
0
    }
97
0
  }
98
0
  *val = result;
99
0
}
100
}  // namespace
101
102
void CRCImpl::FillWordTable(uint32_t poly, uint32_t last, int word_size,
103
0
                            Uint32By256* t) {
104
0
  for (int j = 0; j != word_size; j++) {  // for each byte of extension....
105
0
    t[j][0] = 0;                          // a zero has no effect
106
0
    for (int i = 128; i != 0; i >>= 1) {  // fill in entries for powers of 2
107
0
      if (j == 0 && i == 128) {
108
0
        t[j][i] = last;  // top bit in last byte is given
109
0
      } else {
110
        // each successive power of two is derived from the previous
111
        // one, either in this table, or the last table
112
0
        uint32_t pred;
113
0
        if (i == 128) {
114
0
          pred = t[j - 1][1];
115
0
        } else {
116
0
          pred = t[j][i << 1];
117
0
        }
118
        // Advance the CRC by one bit (multiply by X, and take remainder
119
        // through one step of polynomial long division)
120
0
        if (pred & 1) {
121
0
          t[j][i] = (pred >> 1) ^ poly;
122
0
        } else {
123
0
          t[j][i] = pred >> 1;
124
0
        }
125
0
      }
126
0
    }
127
    // CRCs have the property that CRC(a xor b) == CRC(a) xor CRC(b)
128
    // so we can make all the tables for non-powers of two by
129
    // xoring previously created entries.
130
0
    for (int i = 2; i != 256; i <<= 1) {
131
0
      for (int k = i + 1; k != (i << 1); k++) {
132
0
        t[j][k] = t[j][i] ^ t[j][k - i];
133
0
      }
134
0
    }
135
0
  }
136
0
}
137
138
0
int CRCImpl::FillZeroesTable(uint32_t poly, Uint32By256* t) {
139
0
  uint32_t inc = 1;
140
0
  inc <<= 31;
141
142
  // Extend by one zero bit. We know degree > 1 so (inc & 1) == 0.
143
0
  inc >>= 1;
144
145
  // Now extend by 2, 4, and 8 bits, so now `inc` is extended by one zero byte.
146
0
  for (int i = 0; i < 3; ++i) {
147
0
    PolyMultiply(&inc, inc, poly);
148
0
  }
149
150
0
  int j = 0;
151
0
  for (uint64_t inc_len = 1; inc_len != 0; inc_len <<= ZEROES_BASE_LG) {
152
    // Every entry in the table adds an additional inc_len zeroes.
153
0
    uint32_t v = inc;
154
0
    for (int a = 1; a != ZEROES_BASE; a++) {
155
0
      t[0][j] = v;
156
0
      PolyMultiply(&v, inc, poly);
157
0
      j++;
158
0
    }
159
0
    inc = v;
160
0
  }
161
0
  ABSL_RAW_CHECK(j <= 256, "");
162
0
  return j;
163
0
}
164
165
// Internal version of the "constructor".
166
0
CRCImpl* CRCImpl::NewInternal() {
167
  // Find an accelearated implementation first.
168
0
  CRCImpl* result = TryNewCRC32AcceleratedX86ARMCombined();
169
170
  // Fall back to generic implementions if no acceleration is available.
171
0
  if (result == nullptr) {
172
0
    result = new CRC32();
173
0
  }
174
175
0
  result->InitTables();
176
177
0
  return result;
178
0
}
179
180
//  The 32-bit implementation
181
182
0
void CRC32::InitTables() {
183
  // Compute the table for extending a CRC by one byte.
184
0
  Uint32By256* t = new Uint32By256[4];
185
0
  FillWordTable(kCrc32cPoly, kCrc32cPoly, 1, t);
186
0
  for (int i = 0; i != 256; i++) {
187
0
    this->table0_[i] = t[0][i];
188
0
  }
189
190
  // Construct a table for updating the CRC by 4 bytes data followed by
191
  // 12 bytes of zeroes.
192
  //
193
  // Note: the data word size could be larger than the CRC size; it might
194
  // be slightly faster to use a 64-bit data word, but doing so doubles the
195
  // table size.
196
0
  uint32_t last = kCrc32cPoly;
197
0
  const size_t size = 12;
198
0
  for (size_t i = 0; i < size; ++i) {
199
0
    last = (last >> 8) ^ this->table0_[last & 0xff];
200
0
  }
201
0
  FillWordTable(kCrc32cPoly, last, 4, t);
202
0
  for (size_t b = 0; b < 4; ++b) {
203
0
    for (int i = 0; i < 256; ++i) {
204
0
      this->table_[b][i] = t[b][i];
205
0
    }
206
0
  }
207
208
0
  int j = FillZeroesTable(kCrc32cPoly, t);
209
0
  ABSL_RAW_CHECK(j <= static_cast<int>(ABSL_ARRAYSIZE(this->zeroes_)), "");
210
0
  for (int i = 0; i < j; i++) {
211
0
    this->zeroes_[i] = t[0][i];
212
0
  }
213
214
0
  delete[] t;
215
216
  // Build up tables for _reversing_ the operation of doing CRC operations on
217
  // zero bytes.
218
219
  // In C++, extending `crc` by a single zero bit is done by the following:
220
  // (A)  bool low_bit_set = (crc & 1);
221
  //      crc >>= 1;
222
  //      if (low_bit_set) crc ^= kCrc32cPoly;
223
  //
224
  // In particular note that the high bit of `crc` after this operation will be
225
  // set if and only if the low bit of `crc` was set before it.  This means that
226
  // no information is lost, and the operation can be reversed, as follows:
227
  // (B)  bool high_bit_set = (crc & 0x80000000u);
228
  //      if (high_bit_set) crc ^= kCrc32cPoly;
229
  //      crc <<= 1;
230
  //      if (high_bit_set) crc ^= 1;
231
  //
232
  // Or, equivalently:
233
  // (C)  bool high_bit_set = (crc & 0x80000000u);
234
  //      crc <<= 1;
235
  //      if (high_bit_set) crc ^= ((kCrc32cPoly << 1) ^ 1);
236
  //
237
  // The last observation is, if we store our checksums in variable `rcrc`,
238
  // with order of the bits reversed, the inverse operation becomes:
239
  // (D)  bool low_bit_set = (rcrc & 1);
240
  //      rcrc >>= 1;
241
  //      if (low_bit_set) rcrc ^= ReverseBits((kCrc32cPoly << 1) ^ 1)
242
  //
243
  // This is the same algorithm (A) that we started with, only with a different
244
  // polynomial bit pattern.  This means that by building up our tables with
245
  // this alternate polynomial, we can apply the CRC algorithms to a
246
  // bit-reversed CRC checksum to perform inverse zero-extension.
247
248
0
  const uint32_t kCrc32cUnextendPoly =
249
0
      ReverseBits(static_cast<uint32_t>((kCrc32cPoly << 1) ^ 1));
250
0
  FillWordTable(kCrc32cUnextendPoly, kCrc32cUnextendPoly, 1, &reverse_table0_);
251
252
0
  j = FillZeroesTable(kCrc32cUnextendPoly, &reverse_zeroes_);
253
0
  ABSL_RAW_CHECK(j <= static_cast<int>(ABSL_ARRAYSIZE(this->reverse_zeroes_)),
254
0
                 "");
255
0
}
256
257
0
void CRC32::Extend(uint32_t* crc, const void* bytes, size_t length) const {
258
0
  const uint8_t* p = static_cast<const uint8_t*>(bytes);
259
0
  const uint8_t* e = p + length;
260
0
  uint32_t l = *crc;
261
262
0
  auto step_one_byte = [this, &p, &l]() {
263
0
    int c = (l & 0xff) ^ *p++;
264
0
    l = this->table0_[c] ^ (l >> 8);
265
0
  };
266
267
0
  if (kNeedAlignedLoads) {
268
    // point x at first 4-byte aligned byte in string. this might be past the
269
    // end of the string.
270
0
    const uint8_t* x = RoundUp<4>(p);
271
0
    if (x <= e) {
272
      // Process bytes until finished or p is 4-byte aligned
273
0
      while (p != x) {
274
0
        step_one_byte();
275
0
      }
276
0
    }
277
0
  }
278
279
0
  const size_t kSwathSize = 16;
280
0
  if (static_cast<size_t>(e - p) >= kSwathSize) {
281
    // Load one swath of data into the operating buffers.
282
0
    uint32_t buf0 = absl::little_endian::Load32(p) ^ l;
283
0
    uint32_t buf1 = absl::little_endian::Load32(p + 4);
284
0
    uint32_t buf2 = absl::little_endian::Load32(p + 8);
285
0
    uint32_t buf3 = absl::little_endian::Load32(p + 12);
286
0
    p += kSwathSize;
287
288
    // Increment a CRC value by a "swath"; this combines the four bytes
289
    // starting at `ptr` and twelve zero bytes, so that four CRCs can be
290
    // built incrementally and combined at the end.
291
0
    const auto step_swath = [this](uint32_t crc_in, const std::uint8_t* ptr) {
292
0
      return absl::little_endian::Load32(ptr) ^
293
0
             this->table_[3][crc_in & 0xff] ^
294
0
             this->table_[2][(crc_in >> 8) & 0xff] ^
295
0
             this->table_[1][(crc_in >> 16) & 0xff] ^
296
0
             this->table_[0][crc_in >> 24];
297
0
    };
298
299
    // Run one CRC calculation step over all swaths in one 16-byte stride
300
0
    const auto step_stride = [&]() {
301
0
      buf0 = step_swath(buf0, p);
302
0
      buf1 = step_swath(buf1, p + 4);
303
0
      buf2 = step_swath(buf2, p + 8);
304
0
      buf3 = step_swath(buf3, p + 12);
305
0
      p += 16;
306
0
    };
307
308
    // Process kStride interleaved swaths through the data in parallel.
309
0
    while ((e - p) > kPrefetchHorizon) {
310
0
      PrefetchToLocalCacheNta(
311
0
          reinterpret_cast<const void*>(p + kPrefetchHorizon));
312
      // Process 64 bytes at a time
313
0
      step_stride();
314
0
      step_stride();
315
0
      step_stride();
316
0
      step_stride();
317
0
    }
318
0
    while (static_cast<size_t>(e - p) >= kSwathSize) {
319
0
      step_stride();
320
0
    }
321
322
    // Now advance one word at a time as far as possible. This isn't worth
323
    // doing if we have word-advance tables.
324
0
    while (static_cast<size_t>(e - p) >= 4) {
325
0
      buf0 = step_swath(buf0, p);
326
0
      uint32_t tmp = buf0;
327
0
      buf0 = buf1;
328
0
      buf1 = buf2;
329
0
      buf2 = buf3;
330
0
      buf3 = tmp;
331
0
      p += 4;
332
0
    }
333
334
    // Combine the results from the different swaths. This is just a CRC
335
    // on the data values in the bufX words.
336
0
    auto combine_one_word = [this](uint32_t crc_in, uint32_t w) {
337
0
      w ^= crc_in;
338
0
      for (size_t i = 0; i < 4; ++i) {
339
0
        w = (w >> 8) ^ this->table0_[w & 0xff];
340
0
      }
341
0
      return w;
342
0
    };
343
344
0
    l = combine_one_word(0, buf0);
345
0
    l = combine_one_word(l, buf1);
346
0
    l = combine_one_word(l, buf2);
347
0
    l = combine_one_word(l, buf3);
348
0
  }
349
350
  // Process the last few bytes
351
0
  while (p != e) {
352
0
    step_one_byte();
353
0
  }
354
355
0
  *crc = l;
356
0
}
357
358
void CRC32::ExtendByZeroesImpl(uint32_t* crc, size_t length,
359
                               const uint32_t zeroes_table[256],
360
0
                               const uint32_t poly_table[256]) {
361
0
  if (length != 0) {
362
0
    uint32_t l = *crc;
363
    // For each ZEROES_BASE_LG bits in length
364
    // (after the low-order bits have been removed)
365
    // we lookup the appropriate polynomial in the zeroes_ array
366
    // and do a polynomial long multiplication (mod the CRC polynomial)
367
    // to extend the CRC by the appropriate number of bits.
368
0
    for (int i = 0; length != 0;
369
0
         i += ZEROES_BASE - 1, length >>= ZEROES_BASE_LG) {
370
0
      int c = length & (ZEROES_BASE - 1);  // pick next ZEROES_BASE_LG bits
371
0
      if (c != 0) {                        // if they are not zero,
372
                                           // multiply by entry in table
373
        // Build a table to aid in multiplying 2 bits at a time.
374
        // It takes too long to build tables for more bits.
375
0
        uint64_t m = zeroes_table[c + i - 1];
376
0
        m <<= 1;
377
0
        uint64_t m2 = m << 1;
378
0
        uint64_t mtab[4] = {0, m, m2, m2 ^ m};
379
380
        // Do the multiply one byte at a time.
381
0
        uint64_t result = 0;
382
0
        for (int x = 0; x < 32; x += 8) {
383
          // The carry-less multiply.
384
0
          result ^= mtab[l & 3] ^ (mtab[(l >> 2) & 3] << 2) ^
385
0
                    (mtab[(l >> 4) & 3] << 4) ^ (mtab[(l >> 6) & 3] << 6);
386
0
          l >>= 8;
387
388
          // Reduce modulo the polynomial
389
0
          result = (result >> 8) ^ poly_table[result & 0xff];
390
0
        }
391
0
        l = static_cast<uint32_t>(result);
392
0
      }
393
0
    }
394
0
    *crc = l;
395
0
  }
396
0
}
397
398
0
void CRC32::ExtendByZeroes(uint32_t* crc, size_t length) const {
399
0
  return CRC32::ExtendByZeroesImpl(crc, length, zeroes_, table0_);
400
0
}
401
402
0
void CRC32::UnextendByZeroes(uint32_t* crc, size_t length) const {
403
  // See the comment in CRC32::InitTables() for an explanation of the algorithm
404
  // below.
405
0
  *crc = ReverseBits(*crc);
406
0
  ExtendByZeroesImpl(crc, length, reverse_zeroes_, reverse_table0_);
407
0
  *crc = ReverseBits(*crc);
408
0
}
409
410
0
void CRC32::Scramble(uint32_t* crc) const {
411
  // Rotate by near half the word size plus 1.  See the scramble comment in
412
  // crc_internal.h for an explanation.
413
0
  constexpr int scramble_rotate = (32 / 2) + 1;
414
0
  *crc = absl::rotr(static_cast<uint32_t>(*crc + kScrambleLo), scramble_rotate);
415
0
}
416
417
0
void CRC32::Unscramble(uint32_t* crc) const {
418
0
  constexpr int scramble_rotate = (32 / 2) + 1;
419
0
  uint64_t rotated = absl::rotl(*crc, scramble_rotate);
420
0
  *crc = static_cast<uint32_t>(rotated - kScrambleLo);
421
0
}
422
423
// Constructor and destructor for base class CRC.
424
0
CRC::~CRC() {}
425
0
CRC::CRC() {}
426
427
// The "constructor" for a CRC32C with a standard polynomial.
428
0
CRC* CRC::Crc32c() {
429
0
  static CRC* singleton = CRCImpl::NewInternal();
430
0
  return singleton;
431
0
}
432
433
}  // namespace crc_internal
434
ABSL_NAMESPACE_END
435
}  // namespace absl