1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
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
16 #include "ashmem_fuzzer.h"
17 #include "fuzzer/FuzzedDataProvider.h"
18 #include "ashmem.h"
19
20 using namespace std;
21
22 namespace OHOS {
23 const int MAX_MEMORY_SIZE = 1024;
24 const int MAX_MEMORY_NAME_LEN = 10;
25
AshmemTestFunc(FuzzedDataProvider * dataProvider)26 void AshmemTestFunc(FuzzedDataProvider* dataProvider)
27 {
28 string name = dataProvider->ConsumeRandomLengthString(MAX_MEMORY_NAME_LEN);
29 int memorySize = dataProvider->ConsumeIntegralInRange(0, MAX_MEMORY_SIZE);
30 sptr<Ashmem> ashmem = Ashmem::CreateAshmem(name.c_str(), memorySize);
31 if (ashmem == nullptr) {
32 return;
33 }
34
35 bool ret = ashmem->MapReadAndWriteAshmem();
36 if (ret != true) {
37 return;
38 }
39
40 string memoryContent = dataProvider->ConsumeRandomLengthString(MAX_MEMORY_SIZE);
41 ret = ashmem->WriteToAshmem(memoryContent.c_str(), memoryContent.size(), 0);
42 if (ret != true) {
43 return;
44 }
45
46 string memoryContent2 = dataProvider->ConsumeRandomLengthString(MAX_MEMORY_SIZE);
47 ret = ashmem->WriteToAshmem(memoryContent2.c_str(), memoryContent2.size(), memoryContent.size());
48 if (ret != true) {
49 return;
50 }
51
52 ashmem->ReadFromAshmem(memoryContent.size(), 0);
53
54 ashmem->ReadFromAshmem(memoryContent2.size(), memoryContent.size());
55
56 int prot = dataProvider->ConsumeIntegral<int>();
57 ashmem->SetProtection(prot);
58
59 ashmem->UnmapAshmem();
60 ashmem->CloseAshmem();
61 }
62
63 } // namespace OHOS
64
65 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)66 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
67 {
68 FuzzedDataProvider dataProvider(data, size);
69 OHOS::AshmemTestFunc(&dataProvider);
70 return 0;
71 }
72