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 "thread_fuzzer.h" 17#include "fuzz_log.h" 18#include <iostream> 19#include <cstdio> 20#include <ctime> 21#include <unistd.h> 22#include <sys/prctl.h> 23#include <sys/resource.h> 24#include "fuzzer/FuzzedDataProvider.h" 25#include "thread_ex.h" 26 27using namespace std; 28 29namespace OHOS { 30const std::string& DEFAULT_THREAD_NAME = "default"; 31const int MAX_STACK_SIZE = 1024; 32const int MAX_PRIORITY = 10; 33using ThreadRunFunc = bool (*)(int& data); 34 35bool TestRun(int &data) 36{ 37 sleep(1); 38 ++data; 39 return false; 40} 41 42class TestThread : public OHOS::Thread { 43public: 44 TestThread(const int data, const bool readyToWork, int priority, ThreadRunFunc runFunc) 45 : data_(data), priority_(priority), name_(DEFAULT_THREAD_NAME), readyToWork_(readyToWork), runFunc_(runFunc) 46 {}; 47 48 TestThread() = delete; 49 ~TestThread() {} 50 51 bool ReadyToWork() override; 52 53 int data_; 54 int priority_; 55 std::string name_; 56protected: 57 bool Run() override; 58 59private: 60 bool readyToWork_; 61 ThreadRunFunc runFunc_; 62}; 63 64bool TestThread::ReadyToWork() 65{ 66 return readyToWork_; 67} 68 69bool TestThread::Run() 70{ 71 priority_ = getpriority(PRIO_PROCESS, 0); 72 char threadName[MAX_THREAD_NAME_LEN + 1] = {0}; 73 prctl(PR_GET_NAME, threadName, 0, 0); 74 name_ = threadName; 75 76 if (runFunc_ != nullptr) { 77 return (*runFunc_)(data_); 78 } 79 80 return false; 81} 82 83void ThreadTestFunc(FuzzedDataProvider* dataProvider) 84{ 85 bool readyToWork = dataProvider->ConsumeBool(); 86 bool priority = dataProvider->ConsumeIntegralInRange(0, MAX_PRIORITY); 87 auto t = std::make_unique<TestThread>(0, readyToWork, priority, TestRun); 88 89 int stacksize = dataProvider->ConsumeIntegralInRange(0, MAX_STACK_SIZE); 90 string name = dataProvider->ConsumeRandomLengthString(MAX_THREAD_NAME_LEN); 91 bool newPriority = dataProvider->ConsumeIntegralInRange(0, MAX_PRIORITY); 92 auto result = t->Start(name, newPriority, stacksize); 93 if (result != ThreadStatus::OK) { 94 return; 95 } 96 t->ReadyToWork(); 97 t->IsExitPending(); 98 t->IsRunning(); 99 t->NotifyExitSync(); 100} 101 102} // namespace OHOS 103 104/* Fuzzer entry point */ 105extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) 106{ 107 FuzzedDataProvider dataProvider(data, size); 108 OHOS::ThreadTestFunc(&dataProvider); 109 return 0; 110} 111