1 /*
2 * Copyright (c) 2024 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 "compilerinterfacestub_fuzzer.h"
17
18 #include <cstddef>
19 #include <cstdint>
20 #include "aot_compiler_service.h"
21 #include "securec.h"
22 #include "system_ability_definition.h"
23
24 using namespace OHOS::ArkCompiler;
25
26 namespace OHOS {
27 constexpr int DATA_ZERO = 0;
28 constexpr int DATA_ONE = 1;
29 constexpr int DATA_TWO = 2;
30 constexpr int DATA_THREE = 3;
31 constexpr size_t OFFSET_ONE = 8;
32 constexpr size_t OFFSET_TWO = 16;
33 constexpr size_t OFFSET_THREE = 24;
34 constexpr size_t MESSAGE_SIZE = MIN_TRANSACTION_ID + 4; // 4 code methods OnRemoteRequest
35 constexpr size_t U32_AT_SIZE = 4;
36 static AotCompilerService compilerService(AOT_COMPILER_SERVICE_ID, false);
37
GetU32Data(const char * ptr)38 uint32_t GetU32Data(const char* ptr)
39 {
40 return (ptr[DATA_ZERO] << OFFSET_THREE) | (ptr[DATA_ONE] << OFFSET_TWO) |
41 (ptr[DATA_TWO] << OFFSET_ONE) | (ptr[DATA_THREE]);
42 }
43
DoSomethingInterestingWithMyAPI(const char * data,size_t size)44 bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
45 {
46 uint32_t code = (GetU32Data(data) % MESSAGE_SIZE);
47 MessageParcel datas;
48 std::u16string descriptor = AotCompilerService::GetDescriptor();
49 datas.WriteInterfaceToken(descriptor);
50 datas.WriteBuffer(data, size);
51 datas.RewindRead(0);
52 MessageParcel reply;
53 MessageOption option;
54 compilerService.OnRemoteRequest(code, datas, reply, option);
55 return true;
56 }
57 }
58
59 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)60 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
61 {
62 /* Run your code on data */
63 if (data == nullptr) {
64 return 0;
65 }
66
67 if (size < OHOS::U32_AT_SIZE) {
68 return 0;
69 }
70
71 char* dataPtr = static_cast<char*>(malloc(size + 1));
72 if (dataPtr == nullptr) {
73 return 0;
74 }
75
76 (void)memset_s(dataPtr, size + 1, 0x00, size + 1);
77 if (memcpy_s(dataPtr, size + 1, data, size) != EOK) {
78 free(dataPtr);
79 dataPtr = nullptr;
80 return 0;
81 }
82
83 OHOS::DoSomethingInterestingWithMyAPI(dataPtr, size);
84 free(dataPtr);
85 dataPtr = nullptr;
86 return 0;
87 }