1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <chrono>
17 #include <thread>
18 
19 #include "fuzzer/FuzzedDataProvider.h"
20 #include "mediautils/TimeCheck.h"
21 
22 static constexpr int kMaxStringLen = 256;
23 
24 // While it might be interesting to test long-running
25 // jobs, it seems unlikely it'd lead to the types of crashes
26 // we're looking for, and would mean a significant increase in fuzzer time.
27 // Therefore, we are setting a low cap.
28 static constexpr uint32_t kMaxTimeoutMs = 1000;
29 static constexpr uint32_t kMinTimeoutMs = 200;
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)30 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
31     FuzzedDataProvider data_provider(data, size);
32 
33     // There's essentially 5 operations that we can access in this class
34     // 1. The time it takes to run this operation. As mentioned above,
35     //    long-running tasks are not good for fuzzing, but there will be
36     //    some change in the run time.
37     uint32_t timeoutMs =
38         data_provider.ConsumeIntegralInRange<uint32_t>(kMinTimeoutMs, kMaxTimeoutMs);
39     uint8_t pid_size = data_provider.ConsumeIntegral<uint8_t>();
40     std::vector<pid_t> pids(pid_size);
41     for (auto& pid : pids) {
42         pid = data_provider.ConsumeIntegral<pid_t>();
43     }
44 
45     // 2. We also have setAudioHalPids, which is populated with the pids set
46     // above.
47     android::TimeCheck::setAudioHalPids(pids);
48     std::string name = data_provider.ConsumeRandomLengthString(kMaxStringLen);
49 
50     // 3. The constructor, which is fuzzed here:
51     android::TimeCheck timeCheck(name.c_str(), timeoutMs);
52     // We will leave some buffer to avoid sleeping too long
53     uint8_t sleep_amount_ms = data_provider.ConsumeIntegralInRange<uint8_t>(0, timeoutMs / 2);
54 
55     // We want to make sure we can cover the time out functionality.
56     if (sleep_amount_ms) {
57         auto ms = std::chrono::milliseconds(sleep_amount_ms);
58         std::this_thread::sleep_for(ms);
59     }
60 
61     // 4. Finally, the destructor on timecheck. These seem to be the only factors
62     // in play.
63     return 0;
64 }
65