blob: e9016bb0c6d08615f304a01a80e247fbd8fec182 [file] [log] [blame]
Michael Ensing910968d2020-07-19 17:19:31 -07001/*
2 * Copyright 2022 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
17#include <fuzzer/FuzzedDataProvider.h>
18#include <thread>
19#include "BlockingQueue.h"
20
21// Chosen to be a number large enough for variation in fuzzer runs, but not consume too much memory.
22static constexpr size_t MAX_CAPACITY = 1024;
23
24namespace android {
25
26extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
27 FuzzedDataProvider fdp(data, size);
28 size_t capacity = fdp.ConsumeIntegralInRange<size_t>(1, MAX_CAPACITY);
29 size_t filled = 0;
30 BlockingQueue<int32_t> queue(capacity);
31
32 while (fdp.remaining_bytes() > 0) {
33 fdp.PickValueInArray<std::function<void()>>({
34 [&]() -> void {
35 size_t numPushes = fdp.ConsumeIntegralInRange<size_t>(0, capacity + 1);
36 for (size_t i = 0; i < numPushes; i++) {
37 queue.push(fdp.ConsumeIntegral<int32_t>());
38 }
39 filled = std::min(capacity, filled + numPushes);
40 },
41 [&]() -> void {
42 // Pops blocks if it is empty, so only pop up to num elements inserted.
43 size_t numPops = fdp.ConsumeIntegralInRange<size_t>(0, filled);
44 for (size_t i = 0; i < numPops; i++) {
45 queue.pop();
46 }
47 filled > numPops ? filled -= numPops : filled = 0;
48 },
49 [&]() -> void {
Prabir Pradhand5678112023-05-18 01:57:10 +000050 // Pops blocks if it is empty, so only pop up to num elements inserted.
51 size_t numPops = fdp.ConsumeIntegralInRange<size_t>(0, filled);
52 for (size_t i = 0; i < numPops; i++) {
53 queue.popWithTimeout(
54 std::chrono::nanoseconds{fdp.ConsumeIntegral<int64_t>()});
55 }
56 filled > numPops ? filled -= numPops : filled = 0;
57 },
58 [&]() -> void {
Michael Ensing910968d2020-07-19 17:19:31 -070059 queue.clear();
60 filled = 0;
61 },
62 [&]() -> void {
63 int32_t eraseElement = fdp.ConsumeIntegral<int32_t>();
Prabir Pradhand5678112023-05-18 01:57:10 +000064 queue.erase_if([&](int32_t element) {
Michael Ensing910968d2020-07-19 17:19:31 -070065 if (element == eraseElement) {
66 filled--;
67 return true;
68 }
69 return false;
70 });
71 },
72 })();
73 }
74
75 return 0;
76}
77
78} // namespace android