1 /*
2  * Copyright (C) 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 #include <fuzzbinder/libbinder_ndk_driver.h>
17 #include <fuzzer/FuzzedDataProvider.h>
18 
19 #include <fakeservicemanager/FakeServiceManager.h>
20 #include <android-base/logging.h>
21 #include <android/binder_interface_utils.h>
22 #include <fuzzbinder/random_binder.h>
23 #include <sensorserviceaidl/SensorManagerAidl.h>
24 
25 using android::fuzzService;
26 using android::frameworks::sensorservice::implementation::SensorManagerAidl;
27 using ndk::SharedRefBase;
28 
29 [[clang::no_destroy]] static std::once_flag gSmOnce;
30 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)31 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
32     static android::sp<android::FakeServiceManager> fakeServiceManager = new android::FakeServiceManager();
33     std::call_once(gSmOnce, [&] { setDefaultServiceManager(fakeServiceManager); });
34     fakeServiceManager->clear();
35 
36     FuzzedDataProvider fdp(data, size);
37     android::sp<android::IBinder> binder = android::getRandomBinder(&fdp);
38     if (binder == nullptr) {
39         // Nothing to do if we get a null binder. It will cause SensorManager to
40         // hang while trying to get sensorservice.
41         return 0;
42     }
43 
44     CHECK(android::NO_ERROR == fakeServiceManager->addService(android::String16("sensorservice"),
45                                    binder));
46 
47     std::shared_ptr<SensorManagerAidl> sensorService =
48             ndk::SharedRefBase::make<SensorManagerAidl>(nullptr);
49 
50     fuzzService(sensorService->asBinder().get(), std::move(fdp));
51 
52     return 0;
53 }
54