| 1 | //===-- checksum_test.cpp ---------------------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "tests/scudo_unit_test.h" |
| 10 | |
| 11 | #include "checksum.h" |
| 12 | |
| 13 | #include <string.h> |
| 14 | |
| 15 | static scudo::u16 computeSoftwareChecksum(scudo::u32 Seed, scudo::uptr *Array, |
| 16 | scudo::uptr ArraySize) { |
| 17 | scudo::u16 Checksum = static_cast<scudo::u16>(Seed & 0xffff); |
| 18 | for (scudo::uptr I = 0; I < ArraySize; I++) |
| 19 | Checksum = scudo::computeBSDChecksum(Sum: Checksum, Data: Array[I]); |
| 20 | return Checksum; |
| 21 | } |
| 22 | |
| 23 | static scudo::u16 computeHardwareChecksum(scudo::u32 Seed, scudo::uptr *Array, |
| 24 | scudo::uptr ArraySize) { |
| 25 | scudo::u32 Crc = Seed; |
| 26 | for (scudo::uptr I = 0; I < ArraySize; I++) |
| 27 | Crc = scudo::computeHardwareCRC32(Crc, Data: Array[I]); |
| 28 | return static_cast<scudo::u16>((Crc & 0xffff) ^ (Crc >> 16)); |
| 29 | } |
| 30 | |
| 31 | typedef scudo::u16 (*ComputeChecksum)(scudo::u32, scudo::uptr *, scudo::uptr); |
| 32 | |
| 33 | // This verifies that flipping bits in the data being checksummed produces a |
| 34 | // different checksum. We do not use random data to avoid flakyness. |
| 35 | template <ComputeChecksum F> static void verifyChecksumFunctionBitFlip() { |
| 36 | scudo::uptr Array[sizeof(scudo::u64) / sizeof(scudo::uptr)]; |
| 37 | const scudo::uptr ArraySize = ARRAY_SIZE(Array); |
| 38 | memset(s: Array, c: 0xaa, n: sizeof(Array)); |
| 39 | const scudo::u32 Seed = 0x41424343U; |
| 40 | const scudo::u16 Reference = F(Seed, Array, ArraySize); |
| 41 | scudo::u8 IdenticalChecksums = 0; |
| 42 | for (scudo::uptr I = 0; I < ArraySize; I++) { |
| 43 | for (scudo::uptr J = 0; J < SCUDO_WORDSIZE; J++) { |
| 44 | Array[I] ^= scudo::uptr{1} << J; |
| 45 | if (F(Seed, Array, ArraySize) == Reference) |
| 46 | IdenticalChecksums++; |
| 47 | Array[I] ^= scudo::uptr{1} << J; |
| 48 | } |
| 49 | } |
| 50 | // Allow for a couple of identical checksums over the whole set of flips. |
| 51 | EXPECT_LE(IdenticalChecksums, 2); |
| 52 | } |
| 53 | |
| 54 | TEST(ScudoChecksumTest, ChecksumFunctions) { |
| 55 | verifyChecksumFunctionBitFlip<computeSoftwareChecksum>(); |
| 56 | if (&scudo::computeHardwareCRC32 && scudo::hasHardwareCRC32()) |
| 57 | verifyChecksumFunctionBitFlip<computeHardwareChecksum>(); |
| 58 | } |
| 59 | |