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 "jsonparse_fuzzer.h"
17
18 #include "ecmascript/base/utf_helper.h"
19 #include "ecmascript/ecma_string-inl.h"
20 #include "ecmascript/napi/include/jsnapi.h"
21
22 using namespace panda;
23 using namespace panda::ecmascript;
24 using namespace panda::ecmascript::base::utf_helper;
25
26 #define MAXBYTELEN sizeof(uint32_t)
27
28 namespace OHOS {
JSONParseFuzzTest(const uint8_t* data, size_t size)29 void JSONParseFuzzTest(const uint8_t* data, size_t size)
30 {
31 RuntimeOption option;
32 option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR);
33 EcmaVM *vm = JSNApi::CreateJSVM(option);
34 const char *const test{R"({"orientation": "portrait"})"};
35 int32_t input = 0;
36 if (size <= 0) {
37 return;
38 }
39 if (size > MAXBYTELEN) {
40 JSNApi::DestroyJSVM(vm);
41 return;
42 }
43 if (memcpy_s(&input, MAXBYTELEN, data, size) != 0) {
44 std::cout << "memcpy_s failed!";
45 UNREACHABLE();
46 }
47 {
48 JsiFastNativeScope scope(vm);
49 Local<StringRef> res = StringRef::NewFromUtf8(vm, test, (int)size);
50 Local<JSValueRef> jsValue = JSON::Parse(vm, res);
51 JSON::Stringify(vm, jsValue);
52 }
53 JSNApi::DestroyJSVM(vm);
54 }
55 }
56
57 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)58 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
59 {
60 // Run your code on data.
61 OHOS::JSONParseFuzzTest(data, size);
62 return 0;
63 }