1 /*
2  * Copyright (c) 2022-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 "loadconfigxmlfile_fuzzer.h"
17 
18 #define private public
19 #include "socperf.h"
20 
21 namespace OHOS {
22 namespace SOCPERF {
23     const std::string fuzzedFile = "myFuzzed.xml";
24     const int32_t FILE_RETURN_SUCCESS = 1;
25     std::mutex mutexLock;
26     std::unique_ptr<SocPerf> socPerf = nullptr;
27 
DoInit()28     bool DoInit()
29     {
30         std::lock_guard<std::mutex> lock(mutexLock);
31         if (socPerf) {
32             return true;
33         }
34         socPerf = std::make_unique<SocPerf>();
35         return socPerf != nullptr;
36     }
37 
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)38     void DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
39     {
40         if (!DoInit()) {
41             return;
42         }
43 
44         // generate fuzzed xml
45         FILE *pFile = fopen(fuzzedFile.c_str(), "wb");
46         if (!pFile) {
47             return;
48         }
49 
50         int32_t retCode = fwrite(reinterpret_cast<const void*>(data), size, 1, pFile); // 1 means count=1
51         if (retCode < FILE_RETURN_SUCCESS) {
52             (void)fclose(pFile);
53             pFile = nullptr;
54             return;
55         }
56 
57         (void)fclose(pFile);
58         pFile = nullptr;
59         socPerf->socPerfConfig_.LoadConfigXmlFile(fuzzedFile);
60     }
61 } // namespace SOCPERF
62 } // namespace OHOS
63 
64 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)65 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
66 {
67     /* Run your code on data */
68     OHOS::SOCPERF::DoSomethingInterestingWithMyAPI(data, size);
69     return 0;
70 }
71