1 /*
2 * Copyright (c) 2022 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 "nativebuffer_fuzzer.h"
17
18 #include <securec.h>
19 #include <string>
20
21 #include "native_buffer.h"
22
23 namespace OHOS {
24 namespace {
25 constexpr size_t STR_LEN = 10;
26 const uint8_t* g_data = nullptr;
27 size_t g_size = 0;
28 size_t g_pos;
29 }
30
31 /*
32 * describe: get data from outside untrusted data(g_data) which size is according to sizeof(T)
33 * tips: only support basic type
34 */
35 template<class T>
GetData()36 T GetData()
37 {
38 T object {};
39 size_t objectSize = sizeof(object);
40 if (g_data == nullptr || objectSize > g_size - g_pos) {
41 return object;
42 }
43 errno_t ret = memcpy_s(&object, objectSize, g_data + g_pos, objectSize);
44 if (ret != EOK) {
45 return {};
46 }
47 g_pos += objectSize;
48 return object;
49 }
50
51 /*
52 * get a string from g_data
53 */
GetStringFromData(int strlen)54 std::string GetStringFromData(int strlen)
55 {
56 char cstr[strlen];
57 cstr[strlen - 1] = '\0';
58 for (int i = 0; i < strlen - 1; i++) {
59 cstr[i] = GetData<char>();
60 }
61 std::string str(cstr);
62 return str;
63 }
64
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)65 bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
66 {
67 if (data == nullptr) {
68 return false;
69 }
70
71 // initialize
72 g_data = data;
73 g_size = size;
74 g_pos = 0;
75
76 // get data
77 OH_NativeBuffer_Config config = GetData<OH_NativeBuffer_Config>();
78 config.width = 1920; // 1920 pixels
79 config.height = 1080; // 1080 pixels
80 OH_NativeBuffer_Config checkConfig = GetData<OH_NativeBuffer_Config>();
81 void *virAddr = static_cast<void*>(GetStringFromData(STR_LEN).data());
82
83 // test
84 OH_NativeBuffer* buffer = OH_NativeBuffer_Alloc(&config);
85 OH_NativeBuffer_GetSeqNum(buffer);
86 OH_NativeBuffer_GetConfig(buffer, &checkConfig);
87 OH_NativeBuffer_Reference(buffer);
88 OH_NativeBuffer_Unreference(buffer);
89 OH_NativeBuffer_Map(buffer, &virAddr);
90 OH_NativeBuffer_Unmap(buffer);
91 OH_NativeBuffer_Unreference(buffer);
92
93 return true;
94 }
95 } // namespace OHOS
96
97 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)98 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
99 {
100 /* Run your code on data */
101 OHOS::DoSomethingInterestingWithMyAPI(data, size);
102 return 0;
103 }
104
105