1 /*
2  * Copyright (C) 2021 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 <stddef.h>
18 #include <stdint.h>
19 #include <iostream>
20 #include <limits>
21 #include <thread>
22 
23 #include <android-base/logging.h>
24 #include <fmq/AidlMessageQueue.h>
25 #include <fmq/ConvertMQDescriptors.h>
26 #include <fmq/EventFlag.h>
27 #include <fmq/MessageQueue.h>
28 
29 #include "fuzzer/FuzzedDataProvider.h"
30 
31 using aidl::android::hardware::common::fmq::SynchronizedReadWrite;
32 using aidl::android::hardware::common::fmq::UnsynchronizedWrite;
33 using android::hardware::kSynchronizedReadWrite;
34 using android::hardware::kUnsynchronizedWrite;
35 
36 typedef int32_t payload_t;
37 
38 /*
39  * MessageQueueBase.h contains asserts when memory allocation fails. So we need
40  * to set a reasonable limit if we want to avoid those asserts.
41  */
42 static constexpr size_t kAlignment = 8;
43 static constexpr size_t kMaxNumElements = PAGE_SIZE * 10 / sizeof(payload_t) - kAlignment + 1;
44 
45 /*
46  * The read counter can be found in the shared memory 16 bytes before the start
47  * of the ring buffer.
48  */
49 static constexpr int kReadCounterOffsetBytes = 16;
50 /*
51  * The write counter can be found in the shared memory 8 bytes before the start
52  * of the ring buffer.
53  */
54 static constexpr int kWriteCounterOffsetBytes = 8;
55 
56 static constexpr int kMaxNumSyncReaders = 1;
57 static constexpr int kMaxNumUnsyncReaders = 5;
58 
59 typedef android::AidlMessageQueue<payload_t, SynchronizedReadWrite> AidlMessageQueueSync;
60 typedef android::AidlMessageQueue<payload_t, UnsynchronizedWrite> AidlMessageQueueUnsync;
61 typedef android::hardware::MessageQueue<payload_t, kSynchronizedReadWrite> MessageQueueSync;
62 typedef android::hardware::MessageQueue<payload_t, kUnsynchronizedWrite> MessageQueueUnsync;
63 typedef aidl::android::hardware::common::fmq::MQDescriptor<payload_t, SynchronizedReadWrite>
64         AidlMQDescSync;
65 typedef aidl::android::hardware::common::fmq::MQDescriptor<payload_t, UnsynchronizedWrite>
66         AidlMQDescUnsync;
67 typedef android::hardware::MQDescriptorSync<payload_t> MQDescSync;
68 typedef android::hardware::MQDescriptorUnsync<payload_t> MQDescUnsync;
69 
70 template <typename Queue, typename Desc>
reader(const Desc & desc,std::vector<uint8_t> readerData)71 void reader(const Desc& desc, std::vector<uint8_t> readerData) {
72     Queue readMq(desc);
73     if (!readMq.isValid()) {
74         LOG(ERROR) << "read mq invalid";
75         return;
76     }
77     FuzzedDataProvider fdp(&readerData[0], readerData.size());
78     while (fdp.remaining_bytes()) {
79         typename Queue::MemTransaction tx;
80         size_t numElements = fdp.ConsumeIntegralInRange<size_t>(0, kMaxNumElements);
81         if (!readMq.beginRead(numElements, &tx)) {
82             continue;
83         }
84         const auto& region = tx.getFirstRegion();
85         payload_t* firstStart = region.getAddress();
86 
87         // TODO add the debug function to get pointer to the ring buffer
88         uint64_t* writeCounter = reinterpret_cast<uint64_t*>(
89                 reinterpret_cast<uint8_t*>(firstStart) - kWriteCounterOffsetBytes);
90         *writeCounter = fdp.ConsumeIntegral<uint64_t>();
91 
92         (void)std::to_string(*firstStart);
93 
94         readMq.commitRead(numElements);
95     }
96 }
97 
98 template <typename Queue>
writer(Queue & writeMq,FuzzedDataProvider & fdp)99 void writer(Queue& writeMq, FuzzedDataProvider& fdp) {
100     while (fdp.remaining_bytes()) {
101         typename Queue::MemTransaction tx;
102         size_t numElements = 1;
103         if (!writeMq.beginWrite(numElements, &tx)) {
104             // need to consume something so we don't end up looping forever
105             fdp.ConsumeIntegral<uint8_t>();
106             continue;
107         }
108 
109         const auto& region = tx.getFirstRegion();
110         payload_t* firstStart = region.getAddress();
111 
112         // TODO add the debug function to get pointer to the ring buffer
113         uint64_t* readCounter = reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(firstStart) -
114                                                             kReadCounterOffsetBytes);
115         *readCounter = fdp.ConsumeIntegral<uint64_t>();
116 
117         *firstStart = fdp.ConsumeIntegral<payload_t>();
118 
119         writeMq.commitWrite(numElements);
120     }
121 }
122 
123 template <typename Queue, typename Desc>
fuzzAidlWithReaders(std::vector<uint8_t> & writerData,std::vector<std::vector<uint8_t>> & readerData)124 void fuzzAidlWithReaders(std::vector<uint8_t>& writerData,
125                          std::vector<std::vector<uint8_t>>& readerData) {
126     FuzzedDataProvider fdp(&writerData[0], writerData.size());
127     Queue writeMq(fdp.ConsumeIntegralInRange<size_t>(1, kMaxNumElements), fdp.ConsumeBool());
128     if (!writeMq.isValid()) {
129         LOG(ERROR) << "AIDL write mq invalid";
130         return;
131     }
132     const auto desc = writeMq.dupeDesc();
133     CHECK(desc.handle.fds[0].get() != -1);
134 
135     std::vector<std::thread> clients;
136     for (int i = 0; i < readerData.size(); i++) {
137         clients.emplace_back(reader<Queue, Desc>, std::ref(desc), std::ref(readerData[i]));
138     }
139 
140     writer<Queue>(writeMq, fdp);
141 
142     for (auto& client : clients) {
143         client.join();
144     }
145 }
146 
147 template <typename Queue, typename Desc>
fuzzHidlWithReaders(std::vector<uint8_t> & writerData,std::vector<std::vector<uint8_t>> & readerData)148 void fuzzHidlWithReaders(std::vector<uint8_t>& writerData,
149                          std::vector<std::vector<uint8_t>>& readerData) {
150     FuzzedDataProvider fdp(&writerData[0], writerData.size());
151     Queue writeMq(fdp.ConsumeIntegralInRange<size_t>(1, kMaxNumElements), fdp.ConsumeBool());
152     if (!writeMq.isValid()) {
153         LOG(ERROR) << "HIDL write mq invalid";
154         return;
155     }
156     const auto desc = writeMq.getDesc();
157     CHECK(desc->isHandleValid());
158 
159     std::vector<std::thread> clients;
160     for (int i = 0; i < readerData.size(); i++) {
161         clients.emplace_back(reader<Queue, Desc>, std::ref(*desc), std::ref(readerData[i]));
162     }
163 
164     writer<Queue>(writeMq, fdp);
165 
166     for (auto& client : clients) {
167         client.join();
168     }
169 }
170 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)171 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
172     if (size < 1 || size > 50000) {
173         return 0;
174     }
175     FuzzedDataProvider fdp(data, size);
176 
177     bool fuzzSync = fdp.ConsumeBool();
178     std::vector<std::vector<uint8_t>> readerData;
179     uint8_t numReaders = fuzzSync ? fdp.ConsumeIntegralInRange<uint8_t>(0, kMaxNumSyncReaders)
180                                   : fdp.ConsumeIntegralInRange<uint8_t>(0, kMaxNumUnsyncReaders);
181     for (int i = 0; i < numReaders; i++) {
182         readerData.emplace_back(fdp.ConsumeBytes<uint8_t>(5));
183     }
184     std::vector<uint8_t> writerData = fdp.ConsumeRemainingBytes<uint8_t>();
185 
186     if (fuzzSync) {
187         fuzzHidlWithReaders<MessageQueueSync, MQDescSync>(writerData, readerData);
188         fuzzAidlWithReaders<AidlMessageQueueSync, AidlMQDescSync>(writerData, readerData);
189     } else {
190         fuzzHidlWithReaders<MessageQueueUnsync, MQDescUnsync>(writerData, readerData);
191         fuzzAidlWithReaders<AidlMessageQueueUnsync, AidlMQDescUnsync>(writerData, readerData);
192     }
193 
194     return 0;
195 }
196