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 "securec.h"
17 #include <cstdint>
18 #include <cstdlib>
19 #include <memory>
20
21 #include "power_interface_impl.h"
22 #include "v1_1/ipower_interface.h"
23 #include "v1_1/power_interface_stub.h"
24 #include "v1_1/power_types.h"
25
26 using namespace OHOS::HDI;
27 using namespace OHOS::HDI::Power::V1_1;
28 using namespace std;
29
30 namespace OHOS {
31 namespace HDI {
32 namespace Power {
33 namespace V1_1 {
34 class PowerFuzzTest {
35 public:
PowerFuzzTest()36 PowerFuzzTest()
37 {
38 impl_ = new PowerInterfaceImpl();
39 impl_->SuspendBlock("PowerStubFuzzTest"); // Prevent device sleep
40 }
~PowerFuzzTest()41 ~PowerFuzzTest()
42 {
43 impl_->SuspendUnblock("PowerStubFuzzTest");
44 }
GetImpl() const45 sptr<PowerInterfaceImpl> GetImpl() const
46 {
47 return impl_;
48 }
49
50 private:
51 sptr<PowerInterfaceImpl> impl_ = nullptr;
52 };
53 namespace {
54 const int32_t REWIND_READ_DATA = 0;
55 shared_ptr<PowerInterfaceStub> g_fuzzService = nullptr;
56 shared_ptr<PowerFuzzTest> g_fuzzTest = nullptr;
57 } // namespace
58
PowerStubFuzzTest(const uint8_t * data,size_t size)59 static void PowerStubFuzzTest(const uint8_t *data, size_t size)
60 {
61 uint32_t code;
62 if (size < sizeof(code)) {
63 return;
64 }
65 if (memcpy_s(&code, sizeof(code), data, sizeof(code)) != EOK) {
66 return;
67 }
68
69 MessageParcel datas;
70 datas.WriteInterfaceToken(IPowerInterface::GetDescriptor());
71 datas.WriteBuffer(data, size);
72 datas.RewindRead(REWIND_READ_DATA);
73 MessageParcel reply;
74 MessageOption option;
75 if (g_fuzzService == nullptr) {
76 g_fuzzTest = make_shared<PowerFuzzTest>();
77 g_fuzzService = make_shared<PowerInterfaceStub>(g_fuzzTest->GetImpl());
78 }
79 // Filter force sleep calls
80 if (CMD_POWER_INTERFACE_FORCE_SUSPEND == code) {
81 return;
82 }
83 g_fuzzService->OnRemoteRequest(code, datas, reply, option);
84 }
85 } // namespace V1_1
86 } // namespace Power
87 } // namespace HDI
88 } // namespace OHOS
89
90 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)91 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
92 {
93 /* Run your code on data */
94 OHOS::HDI::Power::V1_1::PowerStubFuzzTest(data, size);
95 return 0;
96 }
97