1 /*
2 * Copyright (C) 2020 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 #include <binder/MemoryDealer.h>
18 #include <commonFuzzHelpers.h>
19 #include <fuzzer/FuzzedDataProvider.h>
20 #include <string>
21 #include <unordered_set>
22
23 namespace android {
24
25 static constexpr size_t kMaxBufferSize = 10000;
26 static constexpr size_t kMaxDealerSize = 1024 * 512;
27 static constexpr size_t kMaxAllocSize = 1024;
28
29 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)30 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
31 if (size > kMaxBufferSize) {
32 return 0;
33 }
34
35 FuzzedDataProvider fdp(data, size);
36 size_t dSize = fdp.ConsumeIntegralInRange<size_t>(0, kMaxDealerSize);
37 std::string name = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
38 uint32_t flags = fdp.ConsumeIntegral<uint32_t>();
39 sp<MemoryDealer> dealer = new MemoryDealer(dSize, name.c_str(), flags);
40
41 // This is used to track offsets that have been freed already to avoid an expected fatal log.
42 std::unordered_set<size_t> free_list;
43
44 while (fdp.remaining_bytes() > 0) {
45 fdp.PickValueInArray<std::function<void()>>({
46 [&]() -> void { dealer->getAllocationAlignment(); },
47 [&]() -> void { dealer->getMemoryHeap(); },
48 [&]() -> void {
49 size_t offset = fdp.ConsumeIntegral<size_t>();
50
51 // Offset has already been freed, so return instead.
52 if (free_list.find(offset) != free_list.end()) return;
53
54 dealer->deallocate(offset);
55 free_list.insert(offset);
56 },
57 [&]() -> void {
58 std::string randString = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
59 dealer->dump(randString.c_str());
60 },
61 [&]() -> void {
62 size_t allocSize = fdp.ConsumeIntegralInRange<size_t>(0, kMaxAllocSize);
63 sp<IMemory> allocated = dealer->allocate(allocSize);
64 // If the allocation was successful, try to write to it
65 if (allocated != nullptr && allocated->unsecurePointer() != nullptr) {
66 memset(allocated->unsecurePointer(), 1, allocated->size());
67
68 // Clear the address from freelist since it has been allocated over again.
69 free_list.erase(allocated->offset());
70 }
71 },
72 })();
73 }
74
75 return 0;
76 }
77 } // namespace android
78