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 #include <fuzzer/FuzzedDataProvider.h>
17 #include "snapshotserializedeserialize_fuzzer.h"
18
19 #include "ecmascript/log_wrapper.h"
20 #include "ecmascript/object_factory.h"
21 #include "ecmascript/snapshot/mem/snapshot.h"
22
23 using namespace panda;
24 using namespace panda::ecmascript;
25
26 namespace OHOS {
SnapshotSerializeDeserializeFuzzTest(const uint8_t * data,size_t size)27 void SnapshotSerializeDeserializeFuzzTest(const uint8_t* data, size_t size)
28 {
29 RuntimeOption option;
30 option.SetLogLevel(common::LOG_LEVEL::ERROR);
31 EcmaVM *vm = JSNApi::CreateJSVM(option);
32 {
33 JsiFastNativeScope scope(vm);
34 if (size <= 0) {
35 return;
36 }
37 auto factory = vm->GetFactory();
38 FuzzedDataProvider fdp(data, size);
39 const uint32_t len = fdp.ConsumeIntegralInRange<uint32_t>(0, 1024);
40 JSHandle<TaggedArray> array = factory->NewTaggedArray(len);
41 const bool anotherStr = fdp.ConsumeBool();
42 if (anotherStr) {
43 std::string str1 = fdp.ConsumeRandomLengthString(1024);
44 JSHandle<EcmaString> str = factory->NewFromStdString(str1);
45 array->Set(vm->GetAssociatedJSThread(), 0, str.GetTaggedValue());
46 }
47 const CString fileName = "snapshot";
48 Snapshot snapshotSerialize(vm);
49 // serialize
50 snapshotSerialize.Serialize(*array, nullptr, fileName);
51 // deserialize
52 Snapshot snapshotDeserialize(vm);
53 snapshotDeserialize.Deserialize(SnapshotType::VM_ROOT, fileName);
54 // remove snapshot file if exist
55 std::remove(fileName.c_str());
56 }
57 JSNApi::DestroyJSVM(vm);
58 }
59 }
60
61 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)62 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
63 {
64 // Run your code on data.
65 OHOS::SnapshotSerializeDeserializeFuzzTest(data, size);
66 return 0;
67 }