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 "taskscheduler_fuzzer.h"
17 
18 #include <chrono>
19 #include <thread>
20 
21 #include "task_scheduler.h"
22 
23 namespace OHOS {
24 static constexpr int MAX_DELAY_TIME = 5;
25 static constexpr int MAX_INTERVAL_TIME = 3;
AtFuzz(size_t time)26 void AtFuzz(size_t time)
27 {
28     TaskScheduler taskScheduler;
29     std::chrono::steady_clock::time_point tp = std::chrono::steady_clock::now() +
30                                                std::chrono::duration<int>(time % MAX_DELAY_TIME);
31     auto task = taskScheduler.At(tp, []() { });
32     std::this_thread::sleep_for(std::chrono::seconds(MAX_INTERVAL_TIME));
33     taskScheduler.Remove(task);
34 }
35 
EveryFUZZ(size_t time)36 void EveryFUZZ(size_t time)
37 {
38     TaskScheduler taskScheduler;
39     std::chrono::duration<int> delay(time % MAX_DELAY_TIME);
40     std::chrono::duration<int> interval(time % MAX_INTERVAL_TIME);
41     taskScheduler.Every(delay, interval, []() { });
42     std::this_thread::sleep_for(std::chrono::seconds(MAX_INTERVAL_TIME));
43     taskScheduler.Every(0, delay, interval, []() { });
44     taskScheduler.Every(1, delay, interval, []() { });
45     std::this_thread::sleep_for(std::chrono::seconds(MAX_INTERVAL_TIME));
46     taskScheduler.Every(interval, []() { });
47     taskScheduler.Clean();
48 }
49 
ResetFuzz(size_t time)50 void ResetFuzz(size_t time)
51 {
52     TaskScheduler taskScheduler;
53     std::chrono::duration<int> interval(time % MAX_INTERVAL_TIME);
54     std::chrono::steady_clock::time_point tp1 = std::chrono::steady_clock::now() +
55                                                 std::chrono::duration<int>(MAX_DELAY_TIME / 2);
56     auto schedulerTask = taskScheduler.At(tp1, []() {});
57     taskScheduler.Reset(schedulerTask,  interval);
58 }
59 } // namespace OHOS
60 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)61 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
62 {
63     /* Run your code on data */
64     OHOS::AtFuzz(size);
65     OHOS::EveryFUZZ(size);
66     OHOS::ResetFuzz(size);
67     return 0;
68 }
69