1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18 #ifndef _LIBHIDLBASE_FUZZER_HELPER_H
19 #define _LIBHIDLBASE_FUZZER_HELPER_H
20
21 #include <fuzzer/FuzzedDataProvider.h>
22 #include <hidl/HidlBinderSupport.h>
23
24 using namespace android;
25 using namespace hardware;
26 using namespace details;
27
28 constexpr uint32_t kMaxBytes = 256;
29 constexpr uint32_t kMin = 0;
30
createHidlString(FuzzedDataProvider & fdp)31 hidl_string createHidlString(FuzzedDataProvider& fdp) {
32 auto invokeHidlString = fdp.PickValueInArray<const std::function<hidl_string()>>({
33 [&]() { return hidl_string(fdp.ConsumeRandomLengthString(kMaxBytes)); },
34 [&]() { return hidl_string((fdp.ConsumeRandomLengthString(kMaxBytes)).c_str()); },
35 [&]() {
36 std::string testString = fdp.ConsumeRandomLengthString(kMaxBytes);
37 return hidl_string(testString.c_str(),
38 fdp.ConsumeIntegralInRange<uint32_t>(kMin, testString.length()));
39 },
40 [&]() { return fdp.ConsumeRandomLengthString(kMaxBytes); },
41 });
42 return invokeHidlString();
43 }
44
createHidlMemory(FuzzedDataProvider & fdp)45 hidl_memory createHidlMemory(FuzzedDataProvider& fdp) {
46 if (fdp.ConsumeBool()) {
47 return hidl_memory();
48 }
49 return hidl_memory(createHidlString(fdp), hidl_handle(),
50 fdp.ConsumeIntegral<uint64_t>() /* size */);
51 }
52
createStatus(FuzzedDataProvider & fdp)53 Status createStatus(FuzzedDataProvider& fdp) {
54 auto invokeStatus = fdp.PickValueInArray<const std::function<Status()>>({
55 [&]() { return Status::fromExceptionCode(fdp.ConsumeIntegral<uint32_t>()); },
56 [&]() {
57 return Status::fromExceptionCode(
58 fdp.ConsumeIntegral<uint32_t>(),
59 (fdp.ConsumeRandomLengthString(kMaxBytes)).c_str());
60 },
61 [&]() { return Status::fromStatusT(fdp.ConsumeIntegral<uint32_t>()); },
62 [&]() { return Status(); },
63 });
64 return invokeStatus();
65 }
66
67 #endif // _LIBHIDLBASE_FUZZER_HELPER_H
68