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 "executejsbin_fuzzer.h"
17#include "native_engine/impl/ark/ark_native_engine.h"
18#include "securec.h"
19
20using namespace panda;
21using namespace panda::ecmascript;
22using panda::RuntimeOption;
23
24
25#define MAXBYTELEN sizeof(uint32_t)
26
27class Engine {
28public:
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
37    void ExecuteJsBin(const std::string& fileName)
38    {
39        arkNativeEngine_->ExecuteJsBin(fileName, true);
40    }
41
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    }
53private:
54    EcmaVM* vm_ {nullptr};
55    ArkNativeEngine* arkNativeEngine_ {nullptr};
56};
57
58static Engine g_nativeEngine;
59
60namespace OHOS {
61    void ExecuteJsBinFuzzTest(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::string name(reinterpret_cast<const char*>(data), size);
76        g_nativeEngine.ExecuteJsBin(name);
77
78        const std::string path = "test.abc";
79        g_nativeEngine.ExecuteJsBin(path);
80    }
81}
82
83// Fuzzer entry point.
84extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
85{
86    // Run your code on data.
87    OHOS::ExecuteJsBinFuzzTest(data, size);
88    return 0;
89}