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 "runbufferscript_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
RunBufferScript(std::vector<uint8_t> & buffer)37 void RunBufferScript(std::vector<uint8_t>& buffer)
38 {
39 arkNativeEngine_->RunBufferScript(buffer);
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 {
RunBufferScriptFuzzTest(const uint8_t * data,size_t size)61 void RunBufferScriptFuzzTest(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 std::vector<uint8_t> vec(size, *data);
76 g_nativeEngine.RunBufferScript(vec);
77 }
78 }
79
80 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)81 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
82 {
83 // Run your code on data.
84 OHOS::RunBufferScriptFuzzTest(data, size);
85 return 0;
86 }