blob: 219b662ffb9f8d725af2098e6d7487e61dbdcb82 [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++) {
Kunal Raia9d6f892023-09-15 08:48:58 +000053 // Provide a random timeout up to 1 second
54 queue.popWithTimeout(std::chrono::nanoseconds(
55 fdp.ConsumeIntegralInRange<int64_t>(0, 1E9)));
Prabir Pradhand5678112023-05-18 01:57:10 +000056 }
57 filled > numPops ? filled -= numPops : filled = 0;
58 },
59 [&]() -> void {
Michael Ensing910968d2020-07-19 17:19:31 -070060 queue.clear();
61 filled = 0;
62 },
63 [&]() -> void {
64 int32_t eraseElement = fdp.ConsumeIntegral<int32_t>();
Prabir Pradhand5678112023-05-18 01:57:10 +000065 queue.erase_if([&](int32_t element) {
Michael Ensing910968d2020-07-19 17:19:31 -070066 if (element == eraseElement) {
67 filled--;
68 return true;
69 }
70 return false;
71 });
72 },
73 })();
74 }
75
76 return 0;
77}
78
79} // namespace android