1/*
2 * Copyright (c) 2022 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#ifndef COMMON_FUZZER_H
17#define COMMON_FUZZER_H
18
19#include "ecmascript/napi/include/jsnapi.h"
20
21#define MAXBYTELEN sizeof(int32_t)
22
23namespace panda::ecmascript {
24class common_fuzzer {
25public:
26    common_fuzzer() = default;
27    ~common_fuzzer() = default;
28
29    EcmaVM* GetEcvm();
30    void DestroyEcvm(EcmaVM* vm);
31    std::string GetString(const uint8_t* data, size_t size);
32};
33
34EcmaVM* common_fuzzer::GetEcvm()
35{
36    RuntimeOption option;
37    option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR);
38    auto vm = JSNApi::CreateJSVM(option);
39    return vm;
40}
41
42void common_fuzzer::DestroyEcvm(EcmaVM* vm)
43{
44    JSNApi::DestroyJSVM(vm);
45}
46
47std::string common_fuzzer::GetString(const uint8_t* data, size_t size)
48{
49    int index = 0;
50    std::string str(data, data + size);
51    if (size <= 0) {
52        return "";
53    }
54    if (size > MAXBYTELEN) {
55        size = MAXBYTELEN;
56    }
57    if (memcpy_s(&index, MAXBYTELEN, data, size) != 0) {
58        std::cout << "memcpy_s failed!";
59        UNREACHABLE();
60    }
61    return str;
62}
63}
64
65#endif