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 "socperf_fuzzer.h"
17 
18 #include "iservice_registry.h"
19 #include "system_ability_definition.h"
20 
21 #include "i_socperf_service.h"
22 #include "socperf_log.h"
23 
24 namespace OHOS {
25 namespace SOCPERF {
26     constexpr int32_t MIN_LEN = 4;
27     std::mutex mutexLock;
28     sptr<IRemoteObject> remoteObj = nullptr;
29 
DoInit()30     bool DoInit()
31     {
32         std::lock_guard<std::mutex> lock(mutexLock);
33         if (remoteObj) {
34             return true;
35         }
36         auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
37         if (!samgr) {
38             return false;
39         }
40         remoteObj = samgr->GetSystemAbility(SOC_PERF_SERVICE_SA_ID);
41         if (!remoteObj) {
42             return false;
43         }
44         return true;
45     }
46 
onRemoteRequest(uint32_t code,MessageParcel & data)47     int32_t onRemoteRequest(uint32_t code, MessageParcel& data)
48     {
49         if (!DoInit()) {
50             return -1;
51         }
52         MessageParcel reply;
53         MessageOption option;
54         return remoteObj->SendRequest(code, data, reply, option);
55     }
56 
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)57     bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
58     {
59         if (size <= MIN_LEN) {
60             return false;
61         }
62 
63         MessageParcel dataMessageParcel;
64         if (!dataMessageParcel.WriteInterfaceToken(IRemoteStub<ISocPerfService>::GetDescriptor())) {
65             return false;
66         }
67 
68         uint32_t code = *(reinterpret_cast<const uint32_t*>(data));
69         size -= sizeof(uint32_t);
70 
71         dataMessageParcel.WriteBuffer(data + sizeof(uint32_t), size);
72         dataMessageParcel.RewindRead(0);
73 
74         onRemoteRequest(code, dataMessageParcel);
75         return true;
76     }
77 } // namespace SOCPERF
78 } // namespace OHOS
79 
80 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)81 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
82 {
83     /* Run your code on data */
84     OHOS::SOCPERF::DoSomethingInterestingWithMyAPI(data, size);
85     return 0;
86 }
87 
88