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 <google/protobuf/text_format.h>
18 
19 #include <algorithm>
20 #include <fstream>
21 #include <iostream>
22 #include <random>
23 #include <string>
24 #include <string_view>
25 #include <utility>
26 #include <vector>
27 
28 #include "Converter.h"
29 
30 namespace android::nn::fuzz {
31 namespace {
32 
33 using namespace test_helper;
34 
convert(TestOperandType type)35 OperandType convert(TestOperandType type) {
36     return static_cast<OperandType>(type);
37 }
38 
convert(TestOperationType type)39 OperationType convert(TestOperationType type) {
40     return static_cast<OperationType>(type);
41 }
42 
convert(TestOperandLifeTime lifetime)43 OperandLifeTime convert(TestOperandLifeTime lifetime) {
44     return static_cast<OperandLifeTime>(lifetime);
45 }
46 
convert(const std::vector<float> & scales)47 Scales convert(const std::vector<float>& scales) {
48     Scales protoScales;
49     for (float scale : scales) {
50         protoScales.add_scale(scale);
51     }
52     return protoScales;
53 }
54 
convert(const TestSymmPerChannelQuantParams & params)55 SymmPerChannelQuantParams convert(const TestSymmPerChannelQuantParams& params) {
56     SymmPerChannelQuantParams protoParams;
57     *protoParams.mutable_scales() = convert(params.scales);
58     protoParams.set_channel_dim(params.channelDim);
59     return protoParams;
60 }
61 
convertDimensions(const std::vector<uint32_t> & dimensions)62 Dimensions convertDimensions(const std::vector<uint32_t>& dimensions) {
63     Dimensions protoDimensions;
64     for (uint32_t dimension : dimensions) {
65         protoDimensions.add_dimension(dimension);
66     }
67     return protoDimensions;
68 }
69 
getHashValue(const TestBuffer & buffer)70 uint32_t getHashValue(const TestBuffer& buffer) {
71     const char* ptr = buffer.get<char>();
72     const size_t size = buffer.size();
73     const std::string_view view(ptr, size);
74     const size_t value = std::hash<std::string_view>{}(view);
75     return static_cast<uint32_t>(value & 0xFFFFFFFF);
76 }
77 
convert(bool noValue,const TestBuffer & buffer)78 Buffer convert(bool noValue, const TestBuffer& buffer) {
79     Buffer protoBuffer;
80     if (noValue) {
81         const EmptyBuffer empty{};
82         *protoBuffer.mutable_empty() = empty;
83     } else if (buffer.size() == sizeof(uint32_t)) {
84         const uint32_t scalar = *buffer.get<uint32_t>();
85         protoBuffer.set_scalar(scalar);
86     } else {
87         const uint32_t randomSeed = getHashValue(buffer);
88         protoBuffer.set_random_seed(randomSeed);
89     }
90     return protoBuffer;
91 }
92 
convert(const TestOperand & operand)93 Operand convert(const TestOperand& operand) {
94     Operand protoOperand;
95     protoOperand.set_type(convert(operand.type));
96     *protoOperand.mutable_dimensions() = convertDimensions(operand.dimensions);
97     protoOperand.set_scale(operand.scale);
98     protoOperand.set_zero_point(operand.zeroPoint);
99     protoOperand.set_lifetime(convert(operand.lifetime));
100     *protoOperand.mutable_channel_quant() = convert(operand.channelQuant);
101     const bool noValue = (operand.lifetime == TestOperandLifeTime::NO_VALUE);
102     *protoOperand.mutable_data() = convert(noValue, operand.data);
103     return protoOperand;
104 }
105 
convert(const std::vector<TestOperand> & operands)106 Operands convert(const std::vector<TestOperand>& operands) {
107     Operands protoOperands;
108     for (const auto& operand : operands) {
109         *protoOperands.add_operand() = convert(operand);
110     }
111     return protoOperands;
112 }
113 
convertIndexes(const std::vector<uint32_t> & indexes)114 Indexes convertIndexes(const std::vector<uint32_t>& indexes) {
115     Indexes protoIndexes;
116     for (uint32_t index : indexes) {
117         protoIndexes.add_index(index);
118     }
119     return protoIndexes;
120 }
121 
convert(const TestOperation & operation)122 Operation convert(const TestOperation& operation) {
123     Operation protoOperation;
124     protoOperation.set_type(convert(operation.type));
125     *protoOperation.mutable_inputs() = convertIndexes(operation.inputs);
126     *protoOperation.mutable_outputs() = convertIndexes(operation.outputs);
127     return protoOperation;
128 }
129 
convert(const std::vector<TestOperation> & operations)130 Operations convert(const std::vector<TestOperation>& operations) {
131     Operations protoOperations;
132     for (const auto& operation : operations) {
133         *protoOperations.add_operation() = convert(operation);
134     }
135     return protoOperations;
136 }
137 
convert(const TestSubgraph & subgraph)138 Subgraph convert(const TestSubgraph& subgraph) {
139     Subgraph protoSubgraph;
140     *protoSubgraph.mutable_operands() = convert(subgraph.operands);
141     *protoSubgraph.mutable_operations() = convert(subgraph.operations);
142     *protoSubgraph.mutable_input_indexes() = convertIndexes(subgraph.inputIndexes);
143     *protoSubgraph.mutable_output_indexes() = convertIndexes(subgraph.outputIndexes);
144     return protoSubgraph;
145 }
146 
convert(const std::vector<TestSubgraph> & subgraphs)147 Subgraphs convert(const std::vector<TestSubgraph>& subgraphs) {
148     Subgraphs protoSubgraphs;
149     for (const auto& subgraph : subgraphs) {
150         *protoSubgraphs.add_subgraph() = convert(subgraph);
151     }
152     return protoSubgraphs;
153 }
154 
convert(const TestModel & model)155 Model convert(const TestModel& model) {
156     Model protoModel;
157     *protoModel.mutable_main() = convert(model.main);
158     *protoModel.mutable_referenced() = convert(model.referenced);
159     protoModel.set_is_relaxed(model.isRelaxed);
160     return protoModel;
161 }
162 
convertToTest(const TestModel & model)163 Test convertToTest(const TestModel& model) {
164     Test protoTest;
165     *protoTest.mutable_model() = convert(model);
166     return protoTest;
167 }
168 
saveMessageAsText(const google::protobuf::Message & message)169 std::string saveMessageAsText(const google::protobuf::Message& message) {
170     std::string str;
171     if (!google::protobuf::TextFormat::PrintToString(message, &str)) {
172         return {};
173     }
174     return str;
175 }
176 
createCorpusEntry(const std::pair<std::string,const TestModel * > & testCase,const std::string & genDir)177 void createCorpusEntry(const std::pair<std::string, const TestModel*>& testCase,
178                        const std::string& genDir) {
179     const auto& [testName, testModel] = testCase;
180     const Test test = convertToTest(*testModel);
181     const std::string contents = saveMessageAsText(test);
182     const std::string fullName = genDir + "/" + testName;
183     std::ofstream file(fullName.c_str());
184     if (file.good()) {
185         file << contents;
186     }
187 }
188 
189 }  // anonymous namespace
190 }  // namespace android::nn::fuzz
191 
192 using ::android::nn::fuzz::createCorpusEntry;
193 using ::test_helper::TestModel;
194 using ::test_helper::TestModelManager;
195 
main(int argc,char * argv[])196 int main(int argc, char* argv[]) {
197     if (argc != 2) {
198         std::cerr << "error: nnapi_fuzz_generate_corpus requires one argument" << std::endl;
199         return -1;
200     }
201     const std::string genDir = argv[1];
202     const auto filter = [](const TestModel& testModel) { return !testModel.expectFailure; };
203     const auto testModels = TestModelManager::get().getTestModels(filter);
204     std::for_each(testModels.begin(), testModels.end(),
205                   [&genDir](const auto& testCase) { createCorpusEntry(testCase, genDir); });
206     return EXIT_SUCCESS;
207 }
208