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