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 "loadarkmodule_fuzzer.h"
17 #include "native_engine/impl/ark/ark_native_engine.h"
18 #include "securec.h"
19 
20 using namespace panda;
21 using namespace panda::ecmascript;
22 using panda::RuntimeOption;
23 
24 
25 #define MAXBYTELEN sizeof(uint32_t)
26 
27 class Engine {
28 public:
Engine()29     Engine()
30     {
31         RuntimeOption option;
32         option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR);
33         vm_ = JSNApi::CreateJSVM(option);
34         arkNativeEngine_ = new ArkNativeEngine(vm_, nullptr);
35     }
36 
LoadArkModule(const void * buffer,int32_t len,const std::string & fileName)37     void LoadArkModule(const void* buffer, int32_t len, const std::string& fileName)
38     {
39         arkNativeEngine_->LoadArkModule(buffer, len, fileName);
40     }
41 
~Engine()42     ~Engine()
43     {
44         if (arkNativeEngine_ != nullptr) {
45             delete arkNativeEngine_;
46             arkNativeEngine_ = nullptr;
47         }
48         if (vm_ != nullptr) {
49             JSNApi::DestroyJSVM(vm_);
50             vm_ = nullptr;
51         }
52     }
53 private:
54     EcmaVM* vm_ {nullptr};
55     ArkNativeEngine* arkNativeEngine_ {nullptr};
56 };
57 
58 static Engine g_nativeEngine;
59 
60 namespace OHOS {
LoadArkModuleFuzzTest(const uint8_t * data,size_t size)61     void LoadArkModuleFuzzTest(const uint8_t* data, size_t size)
62     {
63         if (size <= 0) {
64             return;
65         }
66         double input = 0;
67         if (size > MAXBYTELEN) {
68             size = MAXBYTELEN;
69         }
70         if (memcpy_s(&input, MAXBYTELEN, data, size) != 0) {
71             std::cout << "memcpy_s failed!" << std::endl;
72             UNREACHABLE();
73         }
74 
75         const void* buffer = reinterpret_cast<const void*>(data);
76         const std::string path = "test.abc";
77         g_nativeEngine.LoadArkModule(buffer, size, path);
78     }
79 }
80 
81 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)82 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
83 {
84     // Run your code on data.
85     OHOS::LoadArkModuleFuzzTest(data, size);
86     return 0;
87 }