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 
17 #define LOG_TAG "Fuzzer"
18 
19 #include <aidl/android/hardware/neuralnetworks/BnDevice.h>
20 #include <fuzzbinder/libbinder_ndk_driver.h>
21 #include <fuzzer/FuzzedDataProvider.h>
22 #include <nnapi/hal/aidl/Adapter.h>
23 
24 #include <memory>
25 #include <string>
26 
27 #include "CanonicalDevice.h"
28 
29 namespace aidl::android::hardware::neuralnetworks::fuzzer {
30 namespace {
31 
makeDevice()32 std::shared_ptr<BnDevice> makeDevice() {
33     const std::string name = "nnapi-sample";
34     auto device = std::make_shared<::android::nn::sample::Device>(name);
35     return adapter::adapt(std::move(device));
36 }
37 
limitLoggingToCrashes()38 void limitLoggingToCrashes() {
39     [[maybe_unused]] static const auto oldSeverity = ::android::base::SetMinimumLogSeverity(
40             ::android::base::LogSeverity::FATAL_WITHOUT_ABORT);
41 }
42 
43 }  // namespace
44 }  // namespace aidl::android::hardware::neuralnetworks::fuzzer
45 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)46 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
47     // Limit NNAPI fuzz test logging to crashes (which is what the test cares about) to reduce the
48     // noise and potentially speed up testing.
49     aidl::android::hardware::neuralnetworks::fuzzer::limitLoggingToCrashes();
50 
51     // Initialize the Device under test when LLVMFuzzerTestOneInput is first called, and reuse it in
52     // later calls.
53     static const auto device = aidl::android::hardware::neuralnetworks::fuzzer::makeDevice();
54 
55     android::fuzzService(device->asBinder().get(), FuzzedDataProvider(data, size));
56     return 0;
57 }
58