FuzzerValueBitMap.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //===- FuzzerValueBitMap.h - INTERNAL - Bit map -----------------*- 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. // ValueBitMap.
  9. //===----------------------------------------------------------------------===//
  10. #ifndef LLVM_FUZZER_VALUE_BIT_MAP_H
  11. #define LLVM_FUZZER_VALUE_BIT_MAP_H
  12. #include "FuzzerPlatform.h"
  13. #include <cstdint>
  14. namespace fuzzer {
  15. // A bit map containing kMapSizeInWords bits.
  16. struct ValueBitMap {
  17. static const size_t kMapSizeInBits = 1 << 16;
  18. static const size_t kMapPrimeMod = 65371; // Largest Prime < kMapSizeInBits;
  19. static const size_t kBitsInWord = (sizeof(uintptr_t) * 8);
  20. static const size_t kMapSizeInWords = kMapSizeInBits / kBitsInWord;
  21. public:
  22. // Clears all bits.
  23. void Reset() { memset(Map, 0, sizeof(Map)); }
  24. // Computes a hash function of Value and sets the corresponding bit.
  25. // Returns true if the bit was changed from 0 to 1.
  26. ATTRIBUTE_NO_SANITIZE_ALL
  27. inline bool AddValue(uintptr_t Value) {
  28. uintptr_t Idx = Value % kMapSizeInBits;
  29. uintptr_t WordIdx = Idx / kBitsInWord;
  30. uintptr_t BitIdx = Idx % kBitsInWord;
  31. uintptr_t Old = Map[WordIdx];
  32. uintptr_t New = Old | (1ULL << BitIdx);
  33. Map[WordIdx] = New;
  34. return New != Old;
  35. }
  36. ATTRIBUTE_NO_SANITIZE_ALL
  37. inline bool AddValueModPrime(uintptr_t Value) {
  38. return AddValue(Value % kMapPrimeMod);
  39. }
  40. inline bool Get(uintptr_t Idx) {
  41. assert(Idx < kMapSizeInBits);
  42. uintptr_t WordIdx = Idx / kBitsInWord;
  43. uintptr_t BitIdx = Idx % kBitsInWord;
  44. return Map[WordIdx] & (1ULL << BitIdx);
  45. }
  46. size_t SizeInBits() const { return kMapSizeInBits; }
  47. template <class Callback>
  48. ATTRIBUTE_NO_SANITIZE_ALL
  49. void ForEach(Callback CB) const {
  50. for (size_t i = 0; i < kMapSizeInWords; i++)
  51. if (uintptr_t M = Map[i])
  52. for (size_t j = 0; j < sizeof(M) * 8; j++)
  53. if (M & ((uintptr_t)1 << j))
  54. CB(i * sizeof(M) * 8 + j);
  55. }
  56. private:
  57. ATTRIBUTE_ALIGNED(512) uintptr_t Map[kMapSizeInWords];
  58. };
  59. } // namespace fuzzer
  60. #endif // LLVM_FUZZER_VALUE_BIT_MAP_H