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 #include "hdinnrtpreparedmodel_fuzzer.h"
16 #include "../data.h"
17 #include "../nnrt_prepare_model_impl.h"
18 #include "../../../common/log.h"
19 
20 #include <v2_0/prepared_model_stub.h>
21 #include "message_parcel.h"
22 #include "message_option.h"
23 #include "securec.h"
24 
25 namespace V2_0 = OHOS::HDI::Nnrt::V2_0;
26 
27 namespace OHOS {
28 namespace NeuralNetworkRuntime {
29 constexpr size_t U32_AT_SIZE = 4;
HdiNnrtPreparedModelFuzzTest(const uint8_t * data,size_t size)30 bool HdiNnrtPreparedModelFuzzTest(const uint8_t* data, size_t size)
31 {
32     OHOS::sptr<V2_0::IPreparedModel> preparedModel = new V2_0::NnrtPrepareModelImpl();
33     if (preparedModel == nullptr) {
34         LOGE("[HdiNnrtPreparedModelFuzzTest]Prepare model make failed.");
35         return false;
36     }
37 
38     Data dataFuzz(data, size);
39     uint32_t code = dataFuzz.GetData<uint32_t>()
40         % (V2_0::CMD_PREPARED_MODEL_RUN - V2_0::CMD_PREPARED_MODEL_GET_VERSION + 1);
41     MessageParcel datas;
42     datas.WriteInterfaceToken(V2_0::IPreparedModel::GetDescriptor());
43     datas.WriteBuffer(dataFuzz.GetNowData(), dataFuzz.GetNowDataSize());
44     datas.RewindRead(0);
45     MessageParcel reply;
46     MessageOption option;
47     OHOS::sptr<V2_0::PreparedModelStub> preparedModelStub = new V2_0::PreparedModelStub(preparedModel);
48     if (preparedModelStub == nullptr) {
49         LOGE("[HdiNnrtPreparedModelFuzzTest]Nnrt preparemodel stub make failed.");
50         return false;
51     }
52     preparedModelStub->OnRemoteRequest(code, datas, reply, option);
53     return true;
54 }
55 } // namespace NeuralNetworkRuntime
56 } // namespace OHOS
57 
58 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)59 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
60 {
61     if (data == nullptr) {
62         LOGE("Pass data is nullptr.");
63         return 0;
64     }
65 
66     if (size < OHOS::NeuralNetworkRuntime::U32_AT_SIZE) {
67         LOGE("Pass size is too small.");
68         return 0;
69     }
70 
71     OHOS::NeuralNetworkRuntime::HdiNnrtPreparedModelFuzzTest(data, size);
72     return 0;
73 }