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 // Authors: corbin.souffrant@leviathansecurity.com
17 //          brian.balling@leviathansecurity.com
18 
19 #include <fuzzer/FuzzedDataProvider.h>
20 #include <helpers.h>
21 #include <pdx/client_channel.h>
22 #include <pdx/service.h>
23 #include <pdx/service_dispatcher.h>
24 #include <stddef.h>
25 #include <stdint.h>
26 #include <sys/eventfd.h>
27 #include <thread>
28 
29 using namespace android::pdx;
30 
31 // Dispatch fuzzer entry point. This fuzzer creates a ServiceDispatcher
32 // and creates an endpoint that returns fuzzed messages that are passed
33 // to the ReceiveAndDispatch and DispatchLoop functions.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)34 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
35   eventfd_t wakeup_val = 1;
36   FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
37 
38   // Endpoint is only used to be immediately wrapped as a unique_ptr,
39   // so it is ok to be using a raw ptr and new here without freeing.
40   FuzzEndpoint* endpoint = new FuzzEndpoint(&fdp);
41   std::unique_ptr<ServiceDispatcher> dispatcher = ServiceDispatcher::Create();
42   std::shared_ptr<Channel> channel(nullptr);
43   std::shared_ptr<Client> client(nullptr);
44   std::shared_ptr<Service> service(
45       new Service("FuzzService", std::unique_ptr<Endpoint>(endpoint)));
46 
47   service->SetChannel(0, std::shared_ptr<Channel>(channel));
48   dispatcher->AddService(service);
49 
50   // Dispatcher blocks, so needs to run in its own thread.
51   std::thread run_dispatcher([&]() {
52     uint8_t opt = 0;
53 
54     // Right now the only operations block, so the while loop is pointless
55     // but leaving it in, just in case that ever changes.
56     while (fdp.remaining_bytes() > sizeof(MessageInfo)) {
57       opt = fdp.ConsumeIntegral<uint8_t>() % dispatcher_operations.size();
58       dispatcher_operations[opt](dispatcher, &fdp);
59     }
60   });
61 
62   // Continuously wake up the epoll so the dispatcher can run.
63   while (fdp.remaining_bytes() > sizeof(MessageInfo)) {
64     eventfd_write(endpoint->epoll_fd(), wakeup_val);
65   }
66 
67   // Cleanup the dispatcher and thread.
68   dispatcher->SetCanceled(true);
69   if (run_dispatcher.joinable())
70     run_dispatcher.join();
71   dispatcher->RemoveService(service);
72 
73   return 0;
74 }
75