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 "runactor_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
RunActor(uint8_t * buffer,size_t bufferSize,const char * descriptor,char * entryPoint)37 void RunActor(uint8_t* buffer, size_t bufferSize, const char* descriptor, char* entryPoint)
38 {
39 arkNativeEngine_->RunActor(buffer, bufferSize, descriptor, entryPoint, true);
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 {
RunActorFuzzTest(const uint8_t * data,size_t size)61 void RunActorFuzzTest(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 size_t randSize = std::rand()%(size + 1);
76 uint8_t* buffer = const_cast<uint8_t*>(data);
77 const char* descriptor = "";
78 std::string entry(reinterpret_cast<const char*>(data + randSize), size - randSize);
79 char* entryPoint = const_cast<char*>(entry.c_str());
80 g_nativeEngine.RunActor(buffer, randSize, descriptor, entryPoint);
81 }
82 }
83
84 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)85 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
86 {
87 // Run your code on data.
88 OHOS::RunActorFuzzTest(data, size);
89 return 0;
90 }