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