checksum.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //===-- checksum.h ----------------------------------------------*- 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. #ifndef SCUDO_CHECKSUM_H_
  9. #define SCUDO_CHECKSUM_H_
  10. #include "internal_defs.h"
  11. // Hardware CRC32 is supported at compilation via the following:
  12. // - for i386 & x86_64: -mcrc32 (earlier: -msse4.2)
  13. // - for ARM & AArch64: -march=armv8-a+crc or -mcrc
  14. // An additional check must be performed at runtime as well to make sure the
  15. // emitted instructions are valid on the target host.
  16. #if defined(__CRC32__)
  17. // NB: clang has <crc32intrin.h> but GCC does not
  18. #include <smmintrin.h>
  19. #define CRC32_INTRINSIC \
  20. FIRST_32_SECOND_64(__builtin_ia32_crc32si, __builtin_ia32_crc32di)
  21. #elif defined(__SSE4_2__)
  22. #include <smmintrin.h>
  23. #define CRC32_INTRINSIC FIRST_32_SECOND_64(_mm_crc32_u32, _mm_crc32_u64)
  24. #endif
  25. #ifdef __ARM_FEATURE_CRC32
  26. #include <arm_acle.h>
  27. #define CRC32_INTRINSIC FIRST_32_SECOND_64(__crc32cw, __crc32cd)
  28. #endif
  29. namespace scudo {
  30. enum class Checksum : u8 {
  31. BSD = 0,
  32. HardwareCRC32 = 1,
  33. };
  34. // BSD checksum, unlike a software CRC32, doesn't use any array lookup. We save
  35. // significantly on memory accesses, as well as 1K of CRC32 table, on platforms
  36. // that do no support hardware CRC32. The checksum itself is 16-bit, which is at
  37. // odds with CRC32, but enough for our needs.
  38. inline u16 computeBSDChecksum(u16 Sum, uptr Data) {
  39. for (u8 I = 0; I < sizeof(Data); I++) {
  40. Sum = static_cast<u16>((Sum >> 1) | ((Sum & 1) << 15));
  41. Sum = static_cast<u16>(Sum + (Data & 0xff));
  42. Data >>= 8;
  43. }
  44. return Sum;
  45. }
  46. bool hasHardwareCRC32();
  47. WEAK u32 computeHardwareCRC32(u32 Crc, uptr Data);
  48. } // namespace scudo
  49. #endif // SCUDO_CHECKSUM_H_