1 /*
2 * Copyright (c) 2025 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 "stringtablespecialstringintern_fuzzer.h"
17 #include "ecmascript/base/string_helper.h"
18 #include "ecmascript/ecma_string-inl.h"
19 #include "ecmascript/ecma_string_table_optimization-inl.h"
20 #include "common_components/base/utf_helper.h"
21 #include "ecmascript/napi/include/jsnapi.h"
22 #include "ecmascript/napi/jsnapi_helper.h"
23 #include <thread>
24 #include <vector>
25
26 using namespace panda;
27 using namespace panda::ecmascript;
28 using namespace common::utf_helper;
29
30 namespace OHOS {
31 constexpr size_t VALID_MIN_SIZE = 2;
32 constexpr int ALIGNMENT = 1;
33
StringTableSpecialStringInternFuzzTest(const uint8_t * data,size_t size)34 void StringTableSpecialStringInternFuzzTest(const uint8_t *data, size_t size)
35 {
36 if (data == nullptr || size <= VALID_MIN_SIZE) {
37 LOG_ECMA(ERROR) << "illegal input!";
38 return;
39 }
40 RuntimeOption option;
41 option.SetLogLevel(common::LOG_LEVEL::ERROR);
42 EcmaVM *vm = JSNApi::CreateJSVM(option);
43
44 JSThread *thread = vm->GetJSThread();
45 ObjectFactory *factory = vm->GetFactory();
46 EcmaStringTable *table = vm->GetEcmaStringTable();
47
48 // empty string
49 JSHandle<EcmaString> emptyStr(thread, EcmaStringAccessor::CreateEmptyString(vm));
50 table->GetOrInternFlattenString(vm, *emptyStr);
51 table->TryGetInternString(thread, emptyStr);
52
53 // no gc pattern
54 uint8_t tsData[] = {0x74, 0x65, 0x73, 0x74};
55 table->GetOrInternFlattenStringNoGC(vm, EcmaStringAccessor::CreateFromUtf8(vm, tsData, sizeof(tsData), true));
56
57 // substring, random offset
58 JSHandle<EcmaString> baseStr = factory->NewFromASCII("base_string_for_substring_testing");
59 uint32_t offset = data[0] % (EcmaStringAccessor(*baseStr).GetLength() + ALIGNMENT);
60 uint32_t length = data[1] % (EcmaStringAccessor(*baseStr).GetLength() - offset + ALIGNMENT);
61 table->GetOrInternStringFromCompressedSubString(vm, baseStr, offset, length);
62
63 JSNApi::DestroyJSVM(vm);
64 }
65 }
66
67 // Fuzzer entry point.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)68 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
69 {
70 // Run your code on data.
71 OHOS::StringTableSpecialStringInternFuzzTest(data, size);
72 return 0;
73 }