xref: /aosp_15_r20/external/pigweed/pw_random/get_int_bounded_fuzzer.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2022 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include <cstddef>
16 #include <cstdint>
17 #include <limits>
18 
19 #include "pw_assert/check.h"
20 #include "pw_fuzzer/fuzzed_data_provider.h"
21 #include "pw_random/fuzzer.h"
22 
23 namespace {
24 enum class IntegerType : uint8_t {
25   kUint8,
26   kUint16,
27   kUint32,
28   kUint64,
29   kMaxValue = kUint64,
30 };
31 
32 template <typename T>
FuzzGetInt(FuzzedDataProvider * provider)33 void FuzzGetInt(FuzzedDataProvider* provider) {
34   pw::random::FuzzerRandomGenerator rng(provider);
35   T value = 0;
36   T bound =
37       provider->ConsumeIntegralInRange<T>(1, std::numeric_limits<T>::max());
38   rng.GetInt(value, bound);
39   PW_CHECK(value < bound);
40 }
41 }  // namespace
42 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)43 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
44   FuzzedDataProvider provider(data, size);
45   switch (provider.ConsumeEnum<IntegerType>()) {
46     case IntegerType::kUint8:
47       FuzzGetInt<uint8_t>(&provider);
48       break;
49     case IntegerType::kUint16:
50       FuzzGetInt<uint16_t>(&provider);
51       break;
52     case IntegerType::kUint32:
53       FuzzGetInt<uint32_t>(&provider);
54       break;
55     case IntegerType::kUint64:
56       FuzzGetInt<uint64_t>(&provider);
57       break;
58   }
59   return 0;
60 }
61