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 std::string randString = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
50 dealer->dump(randString.c_str());
51 },
52 [&]() -> void {
53 size_t allocSize = fdp.ConsumeIntegralInRange<size_t>(0, kMaxAllocSize);
54 sp<IMemory> allocated = dealer->allocate(allocSize);
55 // If the allocation was successful, try to write to it
56 if (allocated != nullptr && allocated->unsecurePointer() != nullptr) {
57 memset(allocated->unsecurePointer(), 1, allocated->size());
58
59 // Clear the address from freelist since it has been allocated over again.
60 free_list.erase(allocated->offset());
61 }
62 },
63 })();
64 }
65
66 return 0;
67 }
68 } // namespace android
69