1 /* 2 * Copyright (C) 2019 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 "fuzzing/OperationManager.h" 18 19 #include <vector> 20 21 #include "TestNeuralNetworksWrapper.h" 22 #include "fuzzing/RandomGraphGeneratorUtils.h" 23 24 namespace android { 25 namespace nn { 26 namespace fuzzing_test { 27 28 template <typename T> 29 inline bool hasValue(const std::vector<T>& vec, const T& val) { 30 // Empty vector indicates "no filter", i.e. always true. 31 return vec.empty() || std::count(vec.begin(), vec.end(), val) > 0; 32 } 33 34 bool OperationSignature::matchFilter(const OperationFilter& filter) { 35 if (!hasValue(filter.opcodes, opType) || !hasValue(filter.versions, version)) { 36 return false; 37 } 38 39 // Match data types. 40 std::vector<Type> combinedDataTypes; 41 for (auto dataType : supportedDataTypes) { 42 if (hasValue(filter.dataTypes, dataType)) combinedDataTypes.push_back(dataType); 43 } 44 if (combinedDataTypes.empty()) return false; 45 supportedDataTypes = combinedDataTypes; 46 47 // Match rank. 48 std::vector<uint32_t> combinedRanks; 49 for (auto rank : supportedRanks) { 50 if (hasValue(filter.ranks, rank)) combinedRanks.push_back(rank); 51 } 52 if (combinedRanks.empty()) return false; 53 supportedRanks = combinedRanks; 54 return true; 55 } 56 57 OperationManager* OperationManager::get() { 58 static OperationManager instance; 59 return &instance; 60 } 61 62 void OperationManager::addSignature(const std::string& name, const OperationSignature& signature) { 63 mOperationSignatures.emplace(name, signature); 64 } 65 66 void OperationManager::applyFilter(const OperationFilter& filter) { 67 mFilteredSignatures.clear(); 68 for (const auto& pair : mOperationSignatures) { 69 mFilteredSignatures.push_back(pair.second); 70 if (!mFilteredSignatures.back().matchFilter(filter)) mFilteredSignatures.pop_back(); 71 } 72 } 73 74 const OperationSignature& OperationManager::getRandomOperation() const { 75 NN_FUZZER_CHECK(!mFilteredSignatures.empty()); 76 return getRandomChoice(mFilteredSignatures); 77 } 78 79 } // namespace fuzzing_test 80 } // namespace nn 81 } // namespace android 82