1 /*
2 * Copyright (C) 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
17 #include <android-base/logging.h>
18 #include <nnapi/TypeUtils.h>
19 #include <src/libfuzzer/libfuzzer_macro.h>
20
21 #include <algorithm>
22
23 #include "Converter.h"
24 #include "Model.pb.h"
25 #include "TestHarness.h"
26
27 // Fuzz test logic. This function will either run to completion and return, or crash.
28 extern void nnapiFuzzTest(const ::test_helper::TestModel& testModel);
29
30 namespace {
31
32 using ::android::nn::getNonExtensionSize;
33 using ::android::nn::OperandType;
34 using ::android::nn::fuzz::convertToTestModel;
35 using ::test_helper::TestModel;
36 using ::test_helper::TestOperand;
37 using ::test_helper::TestSubgraph;
38
operandOverflows(const TestOperand & operand)39 bool operandOverflows(const TestOperand& operand) {
40 const auto operandType = static_cast<OperandType>(operand.type);
41 return !getNonExtensionSize(operandType, operand.dimensions).has_value();
42 }
43
hasOperandThatOverflows(const TestSubgraph & subgraph)44 bool hasOperandThatOverflows(const TestSubgraph& subgraph) {
45 return std::any_of(subgraph.operands.begin(), subgraph.operands.end(), operandOverflows);
46 }
47
shouldSkip(const TestModel & model)48 bool shouldSkip(const TestModel& model) {
49 return hasOperandThatOverflows(model.main) ||
50 std::any_of(model.referenced.begin(), model.referenced.end(), hasOperandThatOverflows);
51 }
52
limitLoggingToCrashes()53 void limitLoggingToCrashes() {
54 [[maybe_unused]] static const auto oldSeverity = ::android::base::SetMinimumLogSeverity(
55 ::android::base::LogSeverity::FATAL_WITHOUT_ABORT);
56 }
57
58 } // namespace
59
DEFINE_PROTO_FUZZER(const::android::nn::fuzz::Test & model)60 DEFINE_PROTO_FUZZER(const ::android::nn::fuzz::Test& model) {
61 // Limit NNAPI fuzz test logging to crashes (which is what the test cares about) to reduce the
62 // noise and potentially speed up testing.
63 limitLoggingToCrashes();
64
65 const TestModel testModel = convertToTestModel(model);
66 if (!shouldSkip(testModel)) {
67 nnapiFuzzTest(testModel);
68 }
69 }
70