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 #include "scopedbytrace_fuzzer.h"
16
17 #include <securec.h>
18 #include <string>
19
20 #include "parameters.h"
21 #include "scoped_bytrace.h"
22
23 namespace OHOS {
24 namespace {
25 const uint8_t* g_data = nullptr;
26 size_t g_size = 0;
27 size_t g_pos;
28 const int STR_MAX_LEN = 1024;
29 const int STR_LEN = 10;
30 } // namespace
31
32 /*
33 * describe: get data from outside untrusted data(g_data) which size is according to sizeof(T)
34 * tips: only support basic type
35 */
36 template<class T>
GetData()37 T GetData()
38 {
39 T object {};
40 size_t objectSize = sizeof(object);
41 if (g_data == nullptr || objectSize > g_size - g_pos) {
42 return object;
43 }
44 errno_t ret = memcpy_s(&object, objectSize, g_data + g_pos, objectSize);
45 if (ret != EOK) {
46 return {};
47 }
48 g_pos += objectSize;
49 return object;
50 }
51
52 /*
53 * get a string from g_data
54 */
GetStringFromData(int strlen)55 std::string GetStringFromData(int strlen)
56 {
57 if (strlen <= 0) {
58 return "fuzz";
59 }
60 if (strlen > STR_MAX_LEN) {
61 strlen = STR_MAX_LEN;
62 }
63 char cstr[strlen];
64 cstr[strlen - 1] = '\0';
65 for (int i = 0; i < strlen - 1; i++) {
66 char tmp = GetData<char>();
67 if (tmp == '\0') {
68 tmp = '1';
69 }
70 cstr[i] = tmp;
71 }
72 std::string str(cstr);
73 return str;
74 }
75
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)76 bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
77 {
78 if (data == nullptr) {
79 return false;
80 }
81
82 // initialize
83 g_data = data;
84 g_size = size;
85 g_pos = 0;
86
87 std::string proc = GetStringFromData(STR_LEN);
88 ScopedBytrace scObject = ScopedBytrace(proc);
89 std::string traceStr = GetStringFromData(STR_LEN);
90 system::SetParameter("persist.sys.graphic.openDebugTrace", "1");
91 ScopedDebugTrace* scDebugObject = new ScopedDebugTrace(traceStr);
92
93 // test
94 scObject.End();
95 delete scDebugObject;
96 scDebugObject = nullptr;
97 system::SetParameter("persist.sys.graphic.openDebugTrace", "0");
98
99 return true;
100 }
101 } // namespace OHOS
102
103 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)104 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
105 {
106 /* Run your code on data */
107 OHOS::DoSomethingInterestingWithMyAPI(data, size);
108 return 0;
109 }
110
111