random_generator.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) 2021 Google Inc.
  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. // http://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. #ifndef TEST_FUZZERS_RANDOM_GENERATOR_H_
  15. #define TEST_FUZZERS_RANDOM_GENERATOR_H_
  16. #include <cstdint>
  17. #include <random>
  18. #include "source/spirv_target_env.h"
  19. namespace spvtools {
  20. namespace fuzzers {
  21. /// Pseudo random generator utility class for fuzzing
  22. class RandomGenerator {
  23. public:
  24. /// @brief Initializes the internal engine
  25. /// @param seed - seed value passed to engine
  26. explicit RandomGenerator(uint64_t seed);
  27. /// @brief Initializes the internal engine
  28. /// @param data - data to calculate the seed from
  29. /// @param size - size of the data
  30. explicit RandomGenerator(const uint8_t* data, size_t size);
  31. ~RandomGenerator() {}
  32. /// Calculate a seed value based on a blob of data.
  33. /// Currently hashes bytes near the front of the buffer, after skipping N
  34. /// bytes.
  35. /// @param data - pointer to data to base calculation off of, must be !nullptr
  36. /// @param size - number of elements in |data|, must be > 0
  37. static uint64_t CalculateSeed(const uint8_t* data, size_t size);
  38. /// Get random valid target env.
  39. spv_target_env GetTargetEnv();
  40. /// Get uint32_t value from uniform distribution.
  41. /// @param lower - lower bound of integer generated
  42. /// @param upper - upper bound of integer generated
  43. /// @returns i, where lower <= i < upper
  44. uint32_t GetUInt32(uint32_t lower, uint32_t upper);
  45. /// Get uint32_t value from uniform distribution.
  46. /// @param bound - Upper bound of integer generated
  47. /// @returns i, where 0 <= i < bound
  48. uint32_t GetUInt32(uint32_t bound);
  49. private:
  50. std::mt19937_64 engine_;
  51. }; // class RandomGenerator
  52. } // namespace fuzzers
  53. } // namespace spvtools
  54. #endif // TEST_FUZZERS_RANDOM_GENERATOR_UTILS_H_