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 "sensor_fuzzer.h"
17 #include <cstddef>
18 #include <cstdint>
19 #include "hdf_log.h"
20 #include "v1_1/sensor_interface_stub.h"
21
22 using namespace OHOS::HDI::Sensor::V1_1;
23
24 namespace OHOS {
25 constexpr size_t THRESHOLD = 10;
26 constexpr int32_t OFFSET = 4;
27 const std::u16string SENSOR_INTERFACE_TOKEN = u"ohos.hdi.sensor.v1_1.ISensorInterface";
28
Convert2Uint32(const uint8_t * ptr)29 uint32_t Convert2Uint32(const uint8_t* ptr)
30 {
31 if (ptr == nullptr) {
32 return 0;
33 }
34 /*
35 * Move the 0th digit 24 to the left, the first digit 16 to the left, the second digit 8 to the left,
36 * and the third digit no left
37 */
38 return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]);
39 }
40
DoSomethingInterestingWithMyAPI(const uint8_t * rawData,size_t size)41 bool DoSomethingInterestingWithMyAPI(const uint8_t* rawData, size_t size)
42 {
43 if (rawData == nullptr) {
44 return false;
45 }
46 uint32_t code = Convert2Uint32(rawData);
47 rawData = rawData + OFFSET;
48 size = size - OFFSET;
49
50 MessageParcel data;
51 data.WriteInterfaceToken(SENSOR_INTERFACE_TOKEN);
52 data.WriteBuffer(rawData, size);
53 data.RewindRead(0);
54 MessageParcel reply;
55 MessageOption option;
56 sptr<ISensorInterface> g_sensorInterface = ISensorInterface::Get(false);
57 if (g_sensorInterface == nullptr) {
58 HDF_LOGE("%{public}s:ISensorInterface::Get() failed.", __func__);
59 return false;
60 }
61 sptr<SensorInterfaceStub> sensorInterface = new SensorInterfaceStub(g_sensorInterface);
62 if (sensorInterface == nullptr) {
63 HDF_LOGE("%{public}s:new SensorInterfaceStub failed.", __func__);
64 return false;
65 }
66 sensorInterface->OnRemoteRequest(code, data, reply, option);
67
68 return true;
69 }
70 }
71
72 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)73 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
74 {
75 if (size < OHOS::THRESHOLD) {
76 return 0;
77 }
78
79 /* Run your code on data */
80 OHOS::DoSomethingInterestingWithMyAPI(data, size);
81 return 0;
82 }
83
84