blob: 0ac4738fff244e86a592b6ff1239088f0708cf64 [file] [log] [blame]
Lev Proleev13fdfcd2019-08-30 11:35:34 +01001/*
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#define LOG_TAG "neuralnetworks_hidl_hal_test"
18
19#include <android-base/logging.h>
20#include <fcntl.h>
21#include <ftw.h>
22#include <gtest/gtest.h>
23#include <hidlmemory/mapping.h>
24#include <unistd.h>
25
26#include <cstdio>
27#include <cstdlib>
28#include <random>
29#include <thread>
30
31#include "1.2/Callbacks.h"
32#include "GeneratedTestHarness.h"
33#include "MemoryUtils.h"
34#include "TestHarness.h"
35#include "Utils.h"
36#include "VtsHalNeuralnetworks.h"
37
38// Forward declaration of the mobilenet generated test models in
39// frameworks/ml/nn/runtime/test/generated/.
40namespace generated_tests::mobilenet_224_gender_basic_fixed {
41const test_helper::TestModel& get_test_model();
42} // namespace generated_tests::mobilenet_224_gender_basic_fixed
43
44namespace generated_tests::mobilenet_quantized {
45const test_helper::TestModel& get_test_model();
46} // namespace generated_tests::mobilenet_quantized
47
Lev Proleev26d1bc82019-08-30 11:57:18 +010048namespace android::hardware::neuralnetworks::V1_3::vts::functional {
Lev Proleev13fdfcd2019-08-30 11:35:34 +010049
50using namespace test_helper;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010051using V1_0::ErrorStatus;
52using V1_1::ExecutionPreference;
Lev Proleev26d1bc82019-08-30 11:57:18 +010053using V1_2::Constant;
54using V1_2::IPreparedModel;
55using V1_2::OperationType;
56using V1_2::implementation::PreparedModelCallback;
Lev Proleev13fdfcd2019-08-30 11:35:34 +010057
58namespace float32_model {
59
60constexpr auto get_test_model = generated_tests::mobilenet_224_gender_basic_fixed::get_test_model;
61
62} // namespace float32_model
63
64namespace quant8_model {
65
66constexpr auto get_test_model = generated_tests::mobilenet_quantized::get_test_model;
67
68} // namespace quant8_model
69
70namespace {
71
72enum class AccessMode { READ_WRITE, READ_ONLY, WRITE_ONLY };
73
74// Creates cache handles based on provided file groups.
75// The outer vector corresponds to handles and the inner vector is for fds held by each handle.
76void createCacheHandles(const std::vector<std::vector<std::string>>& fileGroups,
77 const std::vector<AccessMode>& mode, hidl_vec<hidl_handle>* handles) {
78 handles->resize(fileGroups.size());
79 for (uint32_t i = 0; i < fileGroups.size(); i++) {
80 std::vector<int> fds;
81 for (const auto& file : fileGroups[i]) {
82 int fd;
83 if (mode[i] == AccessMode::READ_ONLY) {
84 fd = open(file.c_str(), O_RDONLY);
85 } else if (mode[i] == AccessMode::WRITE_ONLY) {
86 fd = open(file.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
87 } else if (mode[i] == AccessMode::READ_WRITE) {
88 fd = open(file.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
89 } else {
90 FAIL();
91 }
92 ASSERT_GE(fd, 0);
93 fds.push_back(fd);
94 }
95 native_handle_t* cacheNativeHandle = native_handle_create(fds.size(), 0);
96 ASSERT_NE(cacheNativeHandle, nullptr);
97 std::copy(fds.begin(), fds.end(), &cacheNativeHandle->data[0]);
98 (*handles)[i].setTo(cacheNativeHandle, /*shouldOwn=*/true);
99 }
100}
101
102void createCacheHandles(const std::vector<std::vector<std::string>>& fileGroups, AccessMode mode,
103 hidl_vec<hidl_handle>* handles) {
104 createCacheHandles(fileGroups, std::vector<AccessMode>(fileGroups.size(), mode), handles);
105}
106
107// Create a chain of broadcast operations. The second operand is always constant tensor [1].
108// For simplicity, activation scalar is shared. The second operand is not shared
109// in the model to let driver maintain a non-trivial size of constant data and the corresponding
110// data locations in cache.
111//
112// --------- activation --------
113// ↓ ↓ ↓ ↓
114// E.g. input -> ADD -> ADD -> ADD -> ... -> ADD -> output
115// ↑ ↑ ↑ ↑
116// [1] [1] [1] [1]
117//
118// This function assumes the operation is either ADD or MUL.
119template <typename CppType, TestOperandType operandType>
120TestModel createLargeTestModelImpl(TestOperationType op, uint32_t len) {
121 EXPECT_TRUE(op == TestOperationType::ADD || op == TestOperationType::MUL);
122
123 // Model operations and operands.
124 std::vector<TestOperation> operations(len);
125 std::vector<TestOperand> operands(len * 2 + 2);
126
127 // The activation scalar, value = 0.
128 operands[0] = {
129 .type = TestOperandType::INT32,
130 .dimensions = {},
131 .numberOfConsumers = len,
132 .scale = 0.0f,
133 .zeroPoint = 0,
134 .lifetime = TestOperandLifeTime::CONSTANT_COPY,
135 .data = TestBuffer::createFromVector<int32_t>({0}),
136 };
137
138 // The buffer value of the constant second operand. The logical value is always 1.0f.
139 CppType bufferValue;
140 // The scale of the first and second operand.
141 float scale1, scale2;
142 if (operandType == TestOperandType::TENSOR_FLOAT32) {
143 bufferValue = 1.0f;
144 scale1 = 0.0f;
145 scale2 = 0.0f;
146 } else if (op == TestOperationType::ADD) {
147 bufferValue = 1;
148 scale1 = 1.0f;
149 scale2 = 1.0f;
150 } else {
151 // To satisfy the constraint on quant8 MUL: input0.scale * input1.scale < output.scale,
152 // set input1 to have scale = 0.5f and bufferValue = 2, i.e. 1.0f in floating point.
153 bufferValue = 2;
154 scale1 = 1.0f;
155 scale2 = 0.5f;
156 }
157
158 for (uint32_t i = 0; i < len; i++) {
159 const uint32_t firstInputIndex = i * 2 + 1;
160 const uint32_t secondInputIndex = firstInputIndex + 1;
161 const uint32_t outputIndex = secondInputIndex + 1;
162
163 // The first operation input.
164 operands[firstInputIndex] = {
165 .type = operandType,
166 .dimensions = {1},
167 .numberOfConsumers = 1,
168 .scale = scale1,
169 .zeroPoint = 0,
170 .lifetime = (i == 0 ? TestOperandLifeTime::MODEL_INPUT
171 : TestOperandLifeTime::TEMPORARY_VARIABLE),
172 .data = (i == 0 ? TestBuffer::createFromVector<CppType>({1}) : TestBuffer()),
173 };
174
175 // The second operation input, value = 1.
176 operands[secondInputIndex] = {
177 .type = operandType,
178 .dimensions = {1},
179 .numberOfConsumers = 1,
180 .scale = scale2,
181 .zeroPoint = 0,
182 .lifetime = TestOperandLifeTime::CONSTANT_COPY,
183 .data = TestBuffer::createFromVector<CppType>({bufferValue}),
184 };
185
186 // The operation. All operations share the same activation scalar.
187 // The output operand is created as an input in the next iteration of the loop, in the case
188 // of all but the last member of the chain; and after the loop as a model output, in the
189 // case of the last member of the chain.
190 operations[i] = {
191 .type = op,
192 .inputs = {firstInputIndex, secondInputIndex, /*activation scalar*/ 0},
193 .outputs = {outputIndex},
194 };
195 }
196
197 // For TestOperationType::ADD, output = 1 + 1 * len = len + 1
198 // For TestOperationType::MUL, output = 1 * 1 ^ len = 1
199 CppType outputResult = static_cast<CppType>(op == TestOperationType::ADD ? len + 1u : 1u);
200
201 // The model output.
202 operands.back() = {
203 .type = operandType,
204 .dimensions = {1},
205 .numberOfConsumers = 0,
206 .scale = scale1,
207 .zeroPoint = 0,
208 .lifetime = TestOperandLifeTime::MODEL_OUTPUT,
209 .data = TestBuffer::createFromVector<CppType>({outputResult}),
210 };
211
212 return {
213 .operands = std::move(operands),
214 .operations = std::move(operations),
215 .inputIndexes = {1},
216 .outputIndexes = {len * 2 + 1},
217 .isRelaxed = false,
218 };
219}
220
221} // namespace
222
223// Tag for the compilation caching tests.
224class CompilationCachingTestBase : public testing::Test {
225 protected:
226 CompilationCachingTestBase(sp<IDevice> device, OperandType type)
227 : kDevice(std::move(device)), kOperandType(type) {}
228
229 void SetUp() override {
230 testing::Test::SetUp();
231 ASSERT_NE(kDevice.get(), nullptr);
232
233 // Create cache directory. The cache directory and a temporary cache file is always created
234 // to test the behavior of prepareModelFromCache, even when caching is not supported.
235 char cacheDirTemp[] = "/data/local/tmp/TestCompilationCachingXXXXXX";
236 char* cacheDir = mkdtemp(cacheDirTemp);
237 ASSERT_NE(cacheDir, nullptr);
238 mCacheDir = cacheDir;
239 mCacheDir.push_back('/');
240
241 Return<void> ret = kDevice->getNumberOfCacheFilesNeeded(
242 [this](ErrorStatus status, uint32_t numModelCache, uint32_t numDataCache) {
243 EXPECT_EQ(ErrorStatus::NONE, status);
244 mNumModelCache = numModelCache;
245 mNumDataCache = numDataCache;
246 });
247 EXPECT_TRUE(ret.isOk());
248 mIsCachingSupported = mNumModelCache > 0 || mNumDataCache > 0;
249
250 // Create empty cache files.
251 mTmpCache = mCacheDir + "tmp";
252 for (uint32_t i = 0; i < mNumModelCache; i++) {
253 mModelCache.push_back({mCacheDir + "model" + std::to_string(i)});
254 }
255 for (uint32_t i = 0; i < mNumDataCache; i++) {
256 mDataCache.push_back({mCacheDir + "data" + std::to_string(i)});
257 }
258 // Dummy handles, use AccessMode::WRITE_ONLY for createCacheHandles to create files.
259 hidl_vec<hidl_handle> modelHandle, dataHandle, tmpHandle;
260 createCacheHandles(mModelCache, AccessMode::WRITE_ONLY, &modelHandle);
261 createCacheHandles(mDataCache, AccessMode::WRITE_ONLY, &dataHandle);
262 createCacheHandles({{mTmpCache}}, AccessMode::WRITE_ONLY, &tmpHandle);
263
264 if (!mIsCachingSupported) {
265 LOG(INFO) << "NN VTS: Early termination of test because vendor service does not "
266 "support compilation caching.";
267 std::cout << "[ ] Early termination of test because vendor service does not "
268 "support compilation caching."
269 << std::endl;
270 }
271 }
272
273 void TearDown() override {
274 // If the test passes, remove the tmp directory. Otherwise, keep it for debugging purposes.
275 if (!testing::Test::HasFailure()) {
276 // Recursively remove the cache directory specified by mCacheDir.
277 auto callback = [](const char* entry, const struct stat*, int, struct FTW*) {
278 return remove(entry);
279 };
280 nftw(mCacheDir.c_str(), callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
281 }
282 testing::Test::TearDown();
283 }
284
285 // Model and examples creators. According to kOperandType, the following methods will return
286 // either float32 model/examples or the quant8 variant.
287 TestModel createTestModel() {
288 if (kOperandType == OperandType::TENSOR_FLOAT32) {
289 return float32_model::get_test_model();
290 } else {
291 return quant8_model::get_test_model();
292 }
293 }
294
295 TestModel createLargeTestModel(OperationType op, uint32_t len) {
296 if (kOperandType == OperandType::TENSOR_FLOAT32) {
297 return createLargeTestModelImpl<float, TestOperandType::TENSOR_FLOAT32>(
298 static_cast<TestOperationType>(op), len);
299 } else {
300 return createLargeTestModelImpl<uint8_t, TestOperandType::TENSOR_QUANT8_ASYMM>(
301 static_cast<TestOperationType>(op), len);
302 }
303 }
304
305 // See if the service can handle the model.
306 bool isModelFullySupported(const Model& model) {
307 bool fullySupportsModel = false;
Lev Proleev26d1bc82019-08-30 11:57:18 +0100308 Return<void> supportedCall = kDevice->getSupportedOperations_1_3(
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100309 model,
310 [&fullySupportsModel, &model](ErrorStatus status, const hidl_vec<bool>& supported) {
311 ASSERT_EQ(ErrorStatus::NONE, status);
312 ASSERT_EQ(supported.size(), model.operations.size());
313 fullySupportsModel = std::all_of(supported.begin(), supported.end(),
314 [](bool valid) { return valid; });
315 });
316 EXPECT_TRUE(supportedCall.isOk());
317 return fullySupportsModel;
318 }
319
320 void saveModelToCache(const Model& model, const hidl_vec<hidl_handle>& modelCache,
321 const hidl_vec<hidl_handle>& dataCache,
322 sp<IPreparedModel>* preparedModel = nullptr) {
323 if (preparedModel != nullptr) *preparedModel = nullptr;
324
325 // Launch prepare model.
326 sp<PreparedModelCallback> preparedModelCallback = new PreparedModelCallback();
327 hidl_array<uint8_t, sizeof(mToken)> cacheToken(mToken);
328 Return<ErrorStatus> prepareLaunchStatus =
Lev Proleev26d1bc82019-08-30 11:57:18 +0100329 kDevice->prepareModel_1_3(model, ExecutionPreference::FAST_SINGLE_ANSWER,
Lev Proleev13fdfcd2019-08-30 11:35:34 +0100330 modelCache, dataCache, cacheToken, preparedModelCallback);
331 ASSERT_TRUE(prepareLaunchStatus.isOk());
332 ASSERT_EQ(static_cast<ErrorStatus>(prepareLaunchStatus), ErrorStatus::NONE);
333
334 // Retrieve prepared model.
335 preparedModelCallback->wait();
336 ASSERT_EQ(preparedModelCallback->getStatus(), ErrorStatus::NONE);
337 if (preparedModel != nullptr) {
338 *preparedModel = IPreparedModel::castFrom(preparedModelCallback->getPreparedModel())
339 .withDefault(nullptr);
340 }
341 }
342
343 bool checkEarlyTermination(ErrorStatus status) {
344 if (status == ErrorStatus::GENERAL_FAILURE) {
345 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
346 "save the prepared model that it does not support.";
347 std::cout << "[ ] Early termination of test because vendor service cannot "
348 "save the prepared model that it does not support."
349 << std::endl;
350 return true;
351 }
352 return false;
353 }
354
355 bool checkEarlyTermination(const Model& model) {
356 if (!isModelFullySupported(model)) {
357 LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot "
358 "prepare model that it does not support.";
359 std::cout << "[ ] Early termination of test because vendor service cannot "
360 "prepare model that it does not support."
361 << std::endl;
362 return true;
363 }
364 return false;
365 }
366
367 void prepareModelFromCache(const hidl_vec<hidl_handle>& modelCache,
368 const hidl_vec<hidl_handle>& dataCache,
369 sp<IPreparedModel>* preparedModel, ErrorStatus* status) {
370 // Launch prepare model from cache.
371 sp<PreparedModelCallback> preparedModelCallback = new PreparedModelCallback();
372 hidl_array<uint8_t, sizeof(mToken)> cacheToken(mToken);
373 Return<ErrorStatus> prepareLaunchStatus = kDevice->prepareModelFromCache(
374 modelCache, dataCache, cacheToken, preparedModelCallback);
375 ASSERT_TRUE(prepareLaunchStatus.isOk());
376 if (static_cast<ErrorStatus>(prepareLaunchStatus) != ErrorStatus::NONE) {
377 *preparedModel = nullptr;
378 *status = static_cast<ErrorStatus>(prepareLaunchStatus);
379 return;
380 }
381
382 // Retrieve prepared model.
383 preparedModelCallback->wait();
384 *status = preparedModelCallback->getStatus();
385 *preparedModel = IPreparedModel::castFrom(preparedModelCallback->getPreparedModel())
386 .withDefault(nullptr);
387 }
388
389 // Absolute path to the temporary cache directory.
390 std::string mCacheDir;
391
392 // Groups of file paths for model and data cache in the tmp cache directory, initialized with
393 // outer_size = mNum{Model|Data}Cache, inner_size = 1. The outer vector corresponds to handles
394 // and the inner vector is for fds held by each handle.
395 std::vector<std::vector<std::string>> mModelCache;
396 std::vector<std::vector<std::string>> mDataCache;
397
398 // A separate temporary file path in the tmp cache directory.
399 std::string mTmpCache;
400
401 uint8_t mToken[static_cast<uint32_t>(Constant::BYTE_SIZE_OF_CACHE_TOKEN)] = {};
402 uint32_t mNumModelCache;
403 uint32_t mNumDataCache;
404 uint32_t mIsCachingSupported;
405
406 const sp<IDevice> kDevice;
407 // The primary data type of the testModel.
408 const OperandType kOperandType;
409};
410
411using CompilationCachingTestParam = std::tuple<NamedDevice, OperandType>;
412
413// A parameterized fixture of CompilationCachingTestBase. Every test will run twice, with the first
414// pass running with float32 models and the second pass running with quant8 models.
415class CompilationCachingTest : public CompilationCachingTestBase,
416 public testing::WithParamInterface<CompilationCachingTestParam> {
417 protected:
418 CompilationCachingTest()
419 : CompilationCachingTestBase(getData(std::get<NamedDevice>(GetParam())),
420 std::get<OperandType>(GetParam())) {}
421};
422
423TEST_P(CompilationCachingTest, CacheSavingAndRetrieval) {
424 // Create test HIDL model and compile.
425 const TestModel& testModel = createTestModel();
426 const Model model = createModel(testModel);
427 if (checkEarlyTermination(model)) return;
428 sp<IPreparedModel> preparedModel = nullptr;
429
430 // Save the compilation to cache.
431 {
432 hidl_vec<hidl_handle> modelCache, dataCache;
433 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
434 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
435 saveModelToCache(model, modelCache, dataCache);
436 }
437
438 // Retrieve preparedModel from cache.
439 {
440 preparedModel = nullptr;
441 ErrorStatus status;
442 hidl_vec<hidl_handle> modelCache, dataCache;
443 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
444 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
445 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
446 if (!mIsCachingSupported) {
447 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
448 ASSERT_EQ(preparedModel, nullptr);
449 return;
450 } else if (checkEarlyTermination(status)) {
451 ASSERT_EQ(preparedModel, nullptr);
452 return;
453 } else {
454 ASSERT_EQ(status, ErrorStatus::NONE);
455 ASSERT_NE(preparedModel, nullptr);
456 }
457 }
458
459 // Execute and verify results.
460 EvaluatePreparedModel(preparedModel, testModel,
461 /*testDynamicOutputShape=*/false);
462}
463
464TEST_P(CompilationCachingTest, CacheSavingAndRetrievalNonZeroOffset) {
465 // Create test HIDL model and compile.
466 const TestModel& testModel = createTestModel();
467 const Model model = createModel(testModel);
468 if (checkEarlyTermination(model)) return;
469 sp<IPreparedModel> preparedModel = nullptr;
470
471 // Save the compilation to cache.
472 {
473 hidl_vec<hidl_handle> modelCache, dataCache;
474 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
475 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
476 uint8_t dummyBytes[] = {0, 0};
477 // Write a dummy integer to the cache.
478 // The driver should be able to handle non-empty cache and non-zero fd offset.
479 for (uint32_t i = 0; i < modelCache.size(); i++) {
480 ASSERT_EQ(write(modelCache[i].getNativeHandle()->data[0], &dummyBytes,
481 sizeof(dummyBytes)),
482 sizeof(dummyBytes));
483 }
484 for (uint32_t i = 0; i < dataCache.size(); i++) {
485 ASSERT_EQ(
486 write(dataCache[i].getNativeHandle()->data[0], &dummyBytes, sizeof(dummyBytes)),
487 sizeof(dummyBytes));
488 }
489 saveModelToCache(model, modelCache, dataCache);
490 }
491
492 // Retrieve preparedModel from cache.
493 {
494 preparedModel = nullptr;
495 ErrorStatus status;
496 hidl_vec<hidl_handle> modelCache, dataCache;
497 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
498 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
499 uint8_t dummyByte = 0;
500 // Advance the offset of each handle by one byte.
501 // The driver should be able to handle non-zero fd offset.
502 for (uint32_t i = 0; i < modelCache.size(); i++) {
503 ASSERT_GE(read(modelCache[i].getNativeHandle()->data[0], &dummyByte, 1), 0);
504 }
505 for (uint32_t i = 0; i < dataCache.size(); i++) {
506 ASSERT_GE(read(dataCache[i].getNativeHandle()->data[0], &dummyByte, 1), 0);
507 }
508 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
509 if (!mIsCachingSupported) {
510 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
511 ASSERT_EQ(preparedModel, nullptr);
512 return;
513 } else if (checkEarlyTermination(status)) {
514 ASSERT_EQ(preparedModel, nullptr);
515 return;
516 } else {
517 ASSERT_EQ(status, ErrorStatus::NONE);
518 ASSERT_NE(preparedModel, nullptr);
519 }
520 }
521
522 // Execute and verify results.
523 EvaluatePreparedModel(preparedModel, testModel,
524 /*testDynamicOutputShape=*/false);
525}
526
527TEST_P(CompilationCachingTest, SaveToCacheInvalidNumCache) {
528 // Create test HIDL model and compile.
529 const TestModel& testModel = createTestModel();
530 const Model model = createModel(testModel);
531 if (checkEarlyTermination(model)) return;
532
533 // Test with number of model cache files greater than mNumModelCache.
534 {
535 hidl_vec<hidl_handle> modelCache, dataCache;
536 // Pass an additional cache file for model cache.
537 mModelCache.push_back({mTmpCache});
538 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
539 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
540 mModelCache.pop_back();
541 sp<IPreparedModel> preparedModel = nullptr;
542 saveModelToCache(model, modelCache, dataCache, &preparedModel);
543 ASSERT_NE(preparedModel, nullptr);
544 // Execute and verify results.
545 EvaluatePreparedModel(preparedModel, testModel,
546 /*testDynamicOutputShape=*/false);
547 // Check if prepareModelFromCache fails.
548 preparedModel = nullptr;
549 ErrorStatus status;
550 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
551 if (status != ErrorStatus::INVALID_ARGUMENT) {
552 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
553 }
554 ASSERT_EQ(preparedModel, nullptr);
555 }
556
557 // Test with number of model cache files smaller than mNumModelCache.
558 if (mModelCache.size() > 0) {
559 hidl_vec<hidl_handle> modelCache, dataCache;
560 // Pop out the last cache file.
561 auto tmp = mModelCache.back();
562 mModelCache.pop_back();
563 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
564 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
565 mModelCache.push_back(tmp);
566 sp<IPreparedModel> preparedModel = nullptr;
567 saveModelToCache(model, modelCache, dataCache, &preparedModel);
568 ASSERT_NE(preparedModel, nullptr);
569 // Execute and verify results.
570 EvaluatePreparedModel(preparedModel, testModel,
571 /*testDynamicOutputShape=*/false);
572 // Check if prepareModelFromCache fails.
573 preparedModel = nullptr;
574 ErrorStatus status;
575 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
576 if (status != ErrorStatus::INVALID_ARGUMENT) {
577 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
578 }
579 ASSERT_EQ(preparedModel, nullptr);
580 }
581
582 // Test with number of data cache files greater than mNumDataCache.
583 {
584 hidl_vec<hidl_handle> modelCache, dataCache;
585 // Pass an additional cache file for data cache.
586 mDataCache.push_back({mTmpCache});
587 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
588 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
589 mDataCache.pop_back();
590 sp<IPreparedModel> preparedModel = nullptr;
591 saveModelToCache(model, modelCache, dataCache, &preparedModel);
592 ASSERT_NE(preparedModel, nullptr);
593 // Execute and verify results.
594 EvaluatePreparedModel(preparedModel, testModel,
595 /*testDynamicOutputShape=*/false);
596 // Check if prepareModelFromCache fails.
597 preparedModel = nullptr;
598 ErrorStatus status;
599 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
600 if (status != ErrorStatus::INVALID_ARGUMENT) {
601 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
602 }
603 ASSERT_EQ(preparedModel, nullptr);
604 }
605
606 // Test with number of data cache files smaller than mNumDataCache.
607 if (mDataCache.size() > 0) {
608 hidl_vec<hidl_handle> modelCache, dataCache;
609 // Pop out the last cache file.
610 auto tmp = mDataCache.back();
611 mDataCache.pop_back();
612 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
613 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
614 mDataCache.push_back(tmp);
615 sp<IPreparedModel> preparedModel = nullptr;
616 saveModelToCache(model, modelCache, dataCache, &preparedModel);
617 ASSERT_NE(preparedModel, nullptr);
618 // Execute and verify results.
619 EvaluatePreparedModel(preparedModel, testModel,
620 /*testDynamicOutputShape=*/false);
621 // Check if prepareModelFromCache fails.
622 preparedModel = nullptr;
623 ErrorStatus status;
624 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
625 if (status != ErrorStatus::INVALID_ARGUMENT) {
626 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
627 }
628 ASSERT_EQ(preparedModel, nullptr);
629 }
630}
631
632TEST_P(CompilationCachingTest, PrepareModelFromCacheInvalidNumCache) {
633 // Create test HIDL model and compile.
634 const TestModel& testModel = createTestModel();
635 const Model model = createModel(testModel);
636 if (checkEarlyTermination(model)) return;
637
638 // Save the compilation to cache.
639 {
640 hidl_vec<hidl_handle> modelCache, dataCache;
641 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
642 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
643 saveModelToCache(model, modelCache, dataCache);
644 }
645
646 // Test with number of model cache files greater than mNumModelCache.
647 {
648 sp<IPreparedModel> preparedModel = nullptr;
649 ErrorStatus status;
650 hidl_vec<hidl_handle> modelCache, dataCache;
651 mModelCache.push_back({mTmpCache});
652 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
653 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
654 mModelCache.pop_back();
655 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
656 if (status != ErrorStatus::GENERAL_FAILURE) {
657 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
658 }
659 ASSERT_EQ(preparedModel, nullptr);
660 }
661
662 // Test with number of model cache files smaller than mNumModelCache.
663 if (mModelCache.size() > 0) {
664 sp<IPreparedModel> preparedModel = nullptr;
665 ErrorStatus status;
666 hidl_vec<hidl_handle> modelCache, dataCache;
667 auto tmp = mModelCache.back();
668 mModelCache.pop_back();
669 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
670 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
671 mModelCache.push_back(tmp);
672 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
673 if (status != ErrorStatus::GENERAL_FAILURE) {
674 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
675 }
676 ASSERT_EQ(preparedModel, nullptr);
677 }
678
679 // Test with number of data cache files greater than mNumDataCache.
680 {
681 sp<IPreparedModel> preparedModel = nullptr;
682 ErrorStatus status;
683 hidl_vec<hidl_handle> modelCache, dataCache;
684 mDataCache.push_back({mTmpCache});
685 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
686 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
687 mDataCache.pop_back();
688 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
689 if (status != ErrorStatus::GENERAL_FAILURE) {
690 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
691 }
692 ASSERT_EQ(preparedModel, nullptr);
693 }
694
695 // Test with number of data cache files smaller than mNumDataCache.
696 if (mDataCache.size() > 0) {
697 sp<IPreparedModel> preparedModel = nullptr;
698 ErrorStatus status;
699 hidl_vec<hidl_handle> modelCache, dataCache;
700 auto tmp = mDataCache.back();
701 mDataCache.pop_back();
702 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
703 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
704 mDataCache.push_back(tmp);
705 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
706 if (status != ErrorStatus::GENERAL_FAILURE) {
707 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
708 }
709 ASSERT_EQ(preparedModel, nullptr);
710 }
711}
712
713TEST_P(CompilationCachingTest, SaveToCacheInvalidNumFd) {
714 // Create test HIDL model and compile.
715 const TestModel& testModel = createTestModel();
716 const Model model = createModel(testModel);
717 if (checkEarlyTermination(model)) return;
718
719 // Go through each handle in model cache, test with NumFd greater than 1.
720 for (uint32_t i = 0; i < mNumModelCache; i++) {
721 hidl_vec<hidl_handle> modelCache, dataCache;
722 // Pass an invalid number of fds for handle i.
723 mModelCache[i].push_back(mTmpCache);
724 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
725 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
726 mModelCache[i].pop_back();
727 sp<IPreparedModel> preparedModel = nullptr;
728 saveModelToCache(model, modelCache, dataCache, &preparedModel);
729 ASSERT_NE(preparedModel, nullptr);
730 // Execute and verify results.
731 EvaluatePreparedModel(preparedModel, testModel,
732 /*testDynamicOutputShape=*/false);
733 // Check if prepareModelFromCache fails.
734 preparedModel = nullptr;
735 ErrorStatus status;
736 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
737 if (status != ErrorStatus::INVALID_ARGUMENT) {
738 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
739 }
740 ASSERT_EQ(preparedModel, nullptr);
741 }
742
743 // Go through each handle in model cache, test with NumFd equal to 0.
744 for (uint32_t i = 0; i < mNumModelCache; i++) {
745 hidl_vec<hidl_handle> modelCache, dataCache;
746 // Pass an invalid number of fds for handle i.
747 auto tmp = mModelCache[i].back();
748 mModelCache[i].pop_back();
749 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
750 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
751 mModelCache[i].push_back(tmp);
752 sp<IPreparedModel> preparedModel = nullptr;
753 saveModelToCache(model, modelCache, dataCache, &preparedModel);
754 ASSERT_NE(preparedModel, nullptr);
755 // Execute and verify results.
756 EvaluatePreparedModel(preparedModel, testModel,
757 /*testDynamicOutputShape=*/false);
758 // Check if prepareModelFromCache fails.
759 preparedModel = nullptr;
760 ErrorStatus status;
761 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
762 if (status != ErrorStatus::INVALID_ARGUMENT) {
763 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
764 }
765 ASSERT_EQ(preparedModel, nullptr);
766 }
767
768 // Go through each handle in data cache, test with NumFd greater than 1.
769 for (uint32_t i = 0; i < mNumDataCache; i++) {
770 hidl_vec<hidl_handle> modelCache, dataCache;
771 // Pass an invalid number of fds for handle i.
772 mDataCache[i].push_back(mTmpCache);
773 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
774 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
775 mDataCache[i].pop_back();
776 sp<IPreparedModel> preparedModel = nullptr;
777 saveModelToCache(model, modelCache, dataCache, &preparedModel);
778 ASSERT_NE(preparedModel, nullptr);
779 // Execute and verify results.
780 EvaluatePreparedModel(preparedModel, testModel,
781 /*testDynamicOutputShape=*/false);
782 // Check if prepareModelFromCache fails.
783 preparedModel = nullptr;
784 ErrorStatus status;
785 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
786 if (status != ErrorStatus::INVALID_ARGUMENT) {
787 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
788 }
789 ASSERT_EQ(preparedModel, nullptr);
790 }
791
792 // Go through each handle in data cache, test with NumFd equal to 0.
793 for (uint32_t i = 0; i < mNumDataCache; i++) {
794 hidl_vec<hidl_handle> modelCache, dataCache;
795 // Pass an invalid number of fds for handle i.
796 auto tmp = mDataCache[i].back();
797 mDataCache[i].pop_back();
798 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
799 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
800 mDataCache[i].push_back(tmp);
801 sp<IPreparedModel> preparedModel = nullptr;
802 saveModelToCache(model, modelCache, dataCache, &preparedModel);
803 ASSERT_NE(preparedModel, nullptr);
804 // Execute and verify results.
805 EvaluatePreparedModel(preparedModel, testModel,
806 /*testDynamicOutputShape=*/false);
807 // Check if prepareModelFromCache fails.
808 preparedModel = nullptr;
809 ErrorStatus status;
810 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
811 if (status != ErrorStatus::INVALID_ARGUMENT) {
812 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
813 }
814 ASSERT_EQ(preparedModel, nullptr);
815 }
816}
817
818TEST_P(CompilationCachingTest, PrepareModelFromCacheInvalidNumFd) {
819 // Create test HIDL model and compile.
820 const TestModel& testModel = createTestModel();
821 const Model model = createModel(testModel);
822 if (checkEarlyTermination(model)) return;
823
824 // Save the compilation to cache.
825 {
826 hidl_vec<hidl_handle> modelCache, dataCache;
827 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
828 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
829 saveModelToCache(model, modelCache, dataCache);
830 }
831
832 // Go through each handle in model cache, test with NumFd greater than 1.
833 for (uint32_t i = 0; i < mNumModelCache; i++) {
834 sp<IPreparedModel> preparedModel = nullptr;
835 ErrorStatus status;
836 hidl_vec<hidl_handle> modelCache, dataCache;
837 mModelCache[i].push_back(mTmpCache);
838 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
839 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
840 mModelCache[i].pop_back();
841 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
842 if (status != ErrorStatus::GENERAL_FAILURE) {
843 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
844 }
845 ASSERT_EQ(preparedModel, nullptr);
846 }
847
848 // Go through each handle in model cache, test with NumFd equal to 0.
849 for (uint32_t i = 0; i < mNumModelCache; i++) {
850 sp<IPreparedModel> preparedModel = nullptr;
851 ErrorStatus status;
852 hidl_vec<hidl_handle> modelCache, dataCache;
853 auto tmp = mModelCache[i].back();
854 mModelCache[i].pop_back();
855 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
856 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
857 mModelCache[i].push_back(tmp);
858 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
859 if (status != ErrorStatus::GENERAL_FAILURE) {
860 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
861 }
862 ASSERT_EQ(preparedModel, nullptr);
863 }
864
865 // Go through each handle in data cache, test with NumFd greater than 1.
866 for (uint32_t i = 0; i < mNumDataCache; i++) {
867 sp<IPreparedModel> preparedModel = nullptr;
868 ErrorStatus status;
869 hidl_vec<hidl_handle> modelCache, dataCache;
870 mDataCache[i].push_back(mTmpCache);
871 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
872 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
873 mDataCache[i].pop_back();
874 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
875 if (status != ErrorStatus::GENERAL_FAILURE) {
876 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
877 }
878 ASSERT_EQ(preparedModel, nullptr);
879 }
880
881 // Go through each handle in data cache, test with NumFd equal to 0.
882 for (uint32_t i = 0; i < mNumDataCache; i++) {
883 sp<IPreparedModel> preparedModel = nullptr;
884 ErrorStatus status;
885 hidl_vec<hidl_handle> modelCache, dataCache;
886 auto tmp = mDataCache[i].back();
887 mDataCache[i].pop_back();
888 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
889 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
890 mDataCache[i].push_back(tmp);
891 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
892 if (status != ErrorStatus::GENERAL_FAILURE) {
893 ASSERT_EQ(status, ErrorStatus::INVALID_ARGUMENT);
894 }
895 ASSERT_EQ(preparedModel, nullptr);
896 }
897}
898
899TEST_P(CompilationCachingTest, SaveToCacheInvalidAccessMode) {
900 // Create test HIDL model and compile.
901 const TestModel& testModel = createTestModel();
902 const Model model = createModel(testModel);
903 if (checkEarlyTermination(model)) return;
904 std::vector<AccessMode> modelCacheMode(mNumModelCache, AccessMode::READ_WRITE);
905 std::vector<AccessMode> dataCacheMode(mNumDataCache, AccessMode::READ_WRITE);
906
907 // Go through each handle in model cache, test with invalid access mode.
908 for (uint32_t i = 0; i < mNumModelCache; i++) {
909 hidl_vec<hidl_handle> modelCache, dataCache;
910 modelCacheMode[i] = AccessMode::READ_ONLY;
911 createCacheHandles(mModelCache, modelCacheMode, &modelCache);
912 createCacheHandles(mDataCache, dataCacheMode, &dataCache);
913 modelCacheMode[i] = AccessMode::READ_WRITE;
914 sp<IPreparedModel> preparedModel = nullptr;
915 saveModelToCache(model, modelCache, dataCache, &preparedModel);
916 ASSERT_NE(preparedModel, nullptr);
917 // Execute and verify results.
918 EvaluatePreparedModel(preparedModel, testModel,
919 /*testDynamicOutputShape=*/false);
920 // Check if prepareModelFromCache fails.
921 preparedModel = nullptr;
922 ErrorStatus status;
923 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
924 if (status != ErrorStatus::INVALID_ARGUMENT) {
925 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
926 }
927 ASSERT_EQ(preparedModel, nullptr);
928 }
929
930 // Go through each handle in data cache, test with invalid access mode.
931 for (uint32_t i = 0; i < mNumDataCache; i++) {
932 hidl_vec<hidl_handle> modelCache, dataCache;
933 dataCacheMode[i] = AccessMode::READ_ONLY;
934 createCacheHandles(mModelCache, modelCacheMode, &modelCache);
935 createCacheHandles(mDataCache, dataCacheMode, &dataCache);
936 dataCacheMode[i] = AccessMode::READ_WRITE;
937 sp<IPreparedModel> preparedModel = nullptr;
938 saveModelToCache(model, modelCache, dataCache, &preparedModel);
939 ASSERT_NE(preparedModel, nullptr);
940 // Execute and verify results.
941 EvaluatePreparedModel(preparedModel, testModel,
942 /*testDynamicOutputShape=*/false);
943 // Check if prepareModelFromCache fails.
944 preparedModel = nullptr;
945 ErrorStatus status;
946 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
947 if (status != ErrorStatus::INVALID_ARGUMENT) {
948 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
949 }
950 ASSERT_EQ(preparedModel, nullptr);
951 }
952}
953
954TEST_P(CompilationCachingTest, PrepareModelFromCacheInvalidAccessMode) {
955 // Create test HIDL model and compile.
956 const TestModel& testModel = createTestModel();
957 const Model model = createModel(testModel);
958 if (checkEarlyTermination(model)) return;
959 std::vector<AccessMode> modelCacheMode(mNumModelCache, AccessMode::READ_WRITE);
960 std::vector<AccessMode> dataCacheMode(mNumDataCache, AccessMode::READ_WRITE);
961
962 // Save the compilation to cache.
963 {
964 hidl_vec<hidl_handle> modelCache, dataCache;
965 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
966 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
967 saveModelToCache(model, modelCache, dataCache);
968 }
969
970 // Go through each handle in model cache, test with invalid access mode.
971 for (uint32_t i = 0; i < mNumModelCache; i++) {
972 sp<IPreparedModel> preparedModel = nullptr;
973 ErrorStatus status;
974 hidl_vec<hidl_handle> modelCache, dataCache;
975 modelCacheMode[i] = AccessMode::WRITE_ONLY;
976 createCacheHandles(mModelCache, modelCacheMode, &modelCache);
977 createCacheHandles(mDataCache, dataCacheMode, &dataCache);
978 modelCacheMode[i] = AccessMode::READ_WRITE;
979 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
980 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
981 ASSERT_EQ(preparedModel, nullptr);
982 }
983
984 // Go through each handle in data cache, test with invalid access mode.
985 for (uint32_t i = 0; i < mNumDataCache; i++) {
986 sp<IPreparedModel> preparedModel = nullptr;
987 ErrorStatus status;
988 hidl_vec<hidl_handle> modelCache, dataCache;
989 dataCacheMode[i] = AccessMode::WRITE_ONLY;
990 createCacheHandles(mModelCache, modelCacheMode, &modelCache);
991 createCacheHandles(mDataCache, dataCacheMode, &dataCache);
992 dataCacheMode[i] = AccessMode::READ_WRITE;
993 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
994 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
995 ASSERT_EQ(preparedModel, nullptr);
996 }
997}
998
999// Copy file contents between file groups.
1000// The outer vector corresponds to handles and the inner vector is for fds held by each handle.
1001// The outer vector sizes must match and the inner vectors must have size = 1.
1002static void copyCacheFiles(const std::vector<std::vector<std::string>>& from,
1003 const std::vector<std::vector<std::string>>& to) {
1004 constexpr size_t kBufferSize = 1000000;
1005 uint8_t buffer[kBufferSize];
1006
1007 ASSERT_EQ(from.size(), to.size());
1008 for (uint32_t i = 0; i < from.size(); i++) {
1009 ASSERT_EQ(from[i].size(), 1u);
1010 ASSERT_EQ(to[i].size(), 1u);
1011 int fromFd = open(from[i][0].c_str(), O_RDONLY);
1012 int toFd = open(to[i][0].c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
1013 ASSERT_GE(fromFd, 0);
1014 ASSERT_GE(toFd, 0);
1015
1016 ssize_t readBytes;
1017 while ((readBytes = read(fromFd, &buffer, kBufferSize)) > 0) {
1018 ASSERT_EQ(write(toFd, &buffer, readBytes), readBytes);
1019 }
1020 ASSERT_GE(readBytes, 0);
1021
1022 close(fromFd);
1023 close(toFd);
1024 }
1025}
1026
1027// Number of operations in the large test model.
1028constexpr uint32_t kLargeModelSize = 100;
1029constexpr uint32_t kNumIterationsTOCTOU = 100;
1030
1031TEST_P(CompilationCachingTest, SaveToCache_TOCTOU) {
1032 if (!mIsCachingSupported) return;
1033
1034 // Create test models and check if fully supported by the service.
1035 const TestModel testModelMul = createLargeTestModel(OperationType::MUL, kLargeModelSize);
1036 const Model modelMul = createModel(testModelMul);
1037 if (checkEarlyTermination(modelMul)) return;
1038 const TestModel testModelAdd = createLargeTestModel(OperationType::ADD, kLargeModelSize);
1039 const Model modelAdd = createModel(testModelAdd);
1040 if (checkEarlyTermination(modelAdd)) return;
1041
1042 // Save the modelMul compilation to cache.
1043 auto modelCacheMul = mModelCache;
1044 for (auto& cache : modelCacheMul) {
1045 cache[0].append("_mul");
1046 }
1047 {
1048 hidl_vec<hidl_handle> modelCache, dataCache;
1049 createCacheHandles(modelCacheMul, AccessMode::READ_WRITE, &modelCache);
1050 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1051 saveModelToCache(modelMul, modelCache, dataCache);
1052 }
1053
1054 // Use a different token for modelAdd.
1055 mToken[0]++;
1056
1057 // This test is probabilistic, so we run it multiple times.
1058 for (uint32_t i = 0; i < kNumIterationsTOCTOU; i++) {
1059 // Save the modelAdd compilation to cache.
1060 {
1061 hidl_vec<hidl_handle> modelCache, dataCache;
1062 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1063 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1064
1065 // Spawn a thread to copy the cache content concurrently while saving to cache.
1066 std::thread thread(copyCacheFiles, std::cref(modelCacheMul), std::cref(mModelCache));
1067 saveModelToCache(modelAdd, modelCache, dataCache);
1068 thread.join();
1069 }
1070
1071 // Retrieve preparedModel from cache.
1072 {
1073 sp<IPreparedModel> preparedModel = nullptr;
1074 ErrorStatus status;
1075 hidl_vec<hidl_handle> modelCache, dataCache;
1076 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1077 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1078 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
1079
1080 // The preparation may fail or succeed, but must not crash. If the preparation succeeds,
1081 // the prepared model must be executed with the correct result and not crash.
1082 if (status != ErrorStatus::NONE) {
1083 ASSERT_EQ(preparedModel, nullptr);
1084 } else {
1085 ASSERT_NE(preparedModel, nullptr);
1086 EvaluatePreparedModel(preparedModel, testModelAdd,
1087 /*testDynamicOutputShape=*/false);
1088 }
1089 }
1090 }
1091}
1092
1093TEST_P(CompilationCachingTest, PrepareFromCache_TOCTOU) {
1094 if (!mIsCachingSupported) return;
1095
1096 // Create test models and check if fully supported by the service.
1097 const TestModel testModelMul = createLargeTestModel(OperationType::MUL, kLargeModelSize);
1098 const Model modelMul = createModel(testModelMul);
1099 if (checkEarlyTermination(modelMul)) return;
1100 const TestModel testModelAdd = createLargeTestModel(OperationType::ADD, kLargeModelSize);
1101 const Model modelAdd = createModel(testModelAdd);
1102 if (checkEarlyTermination(modelAdd)) return;
1103
1104 // Save the modelMul compilation to cache.
1105 auto modelCacheMul = mModelCache;
1106 for (auto& cache : modelCacheMul) {
1107 cache[0].append("_mul");
1108 }
1109 {
1110 hidl_vec<hidl_handle> modelCache, dataCache;
1111 createCacheHandles(modelCacheMul, AccessMode::READ_WRITE, &modelCache);
1112 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1113 saveModelToCache(modelMul, modelCache, dataCache);
1114 }
1115
1116 // Use a different token for modelAdd.
1117 mToken[0]++;
1118
1119 // This test is probabilistic, so we run it multiple times.
1120 for (uint32_t i = 0; i < kNumIterationsTOCTOU; i++) {
1121 // Save the modelAdd compilation to cache.
1122 {
1123 hidl_vec<hidl_handle> modelCache, dataCache;
1124 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1125 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1126 saveModelToCache(modelAdd, modelCache, dataCache);
1127 }
1128
1129 // Retrieve preparedModel from cache.
1130 {
1131 sp<IPreparedModel> preparedModel = nullptr;
1132 ErrorStatus status;
1133 hidl_vec<hidl_handle> modelCache, dataCache;
1134 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1135 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1136
1137 // Spawn a thread to copy the cache content concurrently while preparing from cache.
1138 std::thread thread(copyCacheFiles, std::cref(modelCacheMul), std::cref(mModelCache));
1139 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
1140 thread.join();
1141
1142 // The preparation may fail or succeed, but must not crash. If the preparation succeeds,
1143 // the prepared model must be executed with the correct result and not crash.
1144 if (status != ErrorStatus::NONE) {
1145 ASSERT_EQ(preparedModel, nullptr);
1146 } else {
1147 ASSERT_NE(preparedModel, nullptr);
1148 EvaluatePreparedModel(preparedModel, testModelAdd,
1149 /*testDynamicOutputShape=*/false);
1150 }
1151 }
1152 }
1153}
1154
1155TEST_P(CompilationCachingTest, ReplaceSecuritySensitiveCache) {
1156 if (!mIsCachingSupported) return;
1157
1158 // Create test models and check if fully supported by the service.
1159 const TestModel testModelMul = createLargeTestModel(OperationType::MUL, kLargeModelSize);
1160 const Model modelMul = createModel(testModelMul);
1161 if (checkEarlyTermination(modelMul)) return;
1162 const TestModel testModelAdd = createLargeTestModel(OperationType::ADD, kLargeModelSize);
1163 const Model modelAdd = createModel(testModelAdd);
1164 if (checkEarlyTermination(modelAdd)) return;
1165
1166 // Save the modelMul compilation to cache.
1167 auto modelCacheMul = mModelCache;
1168 for (auto& cache : modelCacheMul) {
1169 cache[0].append("_mul");
1170 }
1171 {
1172 hidl_vec<hidl_handle> modelCache, dataCache;
1173 createCacheHandles(modelCacheMul, AccessMode::READ_WRITE, &modelCache);
1174 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1175 saveModelToCache(modelMul, modelCache, dataCache);
1176 }
1177
1178 // Use a different token for modelAdd.
1179 mToken[0]++;
1180
1181 // Save the modelAdd compilation to cache.
1182 {
1183 hidl_vec<hidl_handle> modelCache, dataCache;
1184 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1185 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1186 saveModelToCache(modelAdd, modelCache, dataCache);
1187 }
1188
1189 // Replace the model cache of modelAdd with modelMul.
1190 copyCacheFiles(modelCacheMul, mModelCache);
1191
1192 // Retrieve the preparedModel from cache, expect failure.
1193 {
1194 sp<IPreparedModel> preparedModel = nullptr;
1195 ErrorStatus status;
1196 hidl_vec<hidl_handle> modelCache, dataCache;
1197 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1198 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1199 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
1200 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
1201 ASSERT_EQ(preparedModel, nullptr);
1202 }
1203}
1204
1205static const auto kNamedDeviceChoices = testing::ValuesIn(getNamedDevices());
1206static const auto kOperandTypeChoices =
1207 testing::Values(OperandType::TENSOR_FLOAT32, OperandType::TENSOR_QUANT8_ASYMM);
1208
1209std::string printCompilationCachingTest(
1210 const testing::TestParamInfo<CompilationCachingTestParam>& info) {
1211 const auto& [namedDevice, operandType] = info.param;
1212 const std::string type = (operandType == OperandType::TENSOR_FLOAT32 ? "float32" : "quant8");
1213 return gtestCompliantName(getName(namedDevice) + "_" + type);
1214}
1215
1216INSTANTIATE_TEST_CASE_P(TestCompilationCaching, CompilationCachingTest,
1217 testing::Combine(kNamedDeviceChoices, kOperandTypeChoices),
1218 printCompilationCachingTest);
1219
1220using CompilationCachingSecurityTestParam = std::tuple<NamedDevice, OperandType, uint32_t>;
1221
1222class CompilationCachingSecurityTest
1223 : public CompilationCachingTestBase,
1224 public testing::WithParamInterface<CompilationCachingSecurityTestParam> {
1225 protected:
1226 CompilationCachingSecurityTest()
1227 : CompilationCachingTestBase(getData(std::get<NamedDevice>(GetParam())),
1228 std::get<OperandType>(GetParam())) {}
1229
1230 void SetUp() {
1231 CompilationCachingTestBase::SetUp();
1232 generator.seed(kSeed);
1233 }
1234
1235 // Get a random integer within a closed range [lower, upper].
1236 template <typename T>
1237 T getRandomInt(T lower, T upper) {
1238 std::uniform_int_distribution<T> dis(lower, upper);
1239 return dis(generator);
1240 }
1241
1242 // Randomly flip one single bit of the cache entry.
1243 void flipOneBitOfCache(const std::string& filename, bool* skip) {
1244 FILE* pFile = fopen(filename.c_str(), "r+");
1245 ASSERT_EQ(fseek(pFile, 0, SEEK_END), 0);
1246 long int fileSize = ftell(pFile);
1247 if (fileSize == 0) {
1248 fclose(pFile);
1249 *skip = true;
1250 return;
1251 }
1252 ASSERT_EQ(fseek(pFile, getRandomInt(0l, fileSize - 1), SEEK_SET), 0);
1253 int readByte = fgetc(pFile);
1254 ASSERT_NE(readByte, EOF);
1255 ASSERT_EQ(fseek(pFile, -1, SEEK_CUR), 0);
1256 ASSERT_NE(fputc(static_cast<uint8_t>(readByte) ^ (1U << getRandomInt(0, 7)), pFile), EOF);
1257 fclose(pFile);
1258 *skip = false;
1259 }
1260
1261 // Randomly append bytes to the cache entry.
1262 void appendBytesToCache(const std::string& filename, bool* skip) {
1263 FILE* pFile = fopen(filename.c_str(), "a");
1264 uint32_t appendLength = getRandomInt(1, 256);
1265 for (uint32_t i = 0; i < appendLength; i++) {
1266 ASSERT_NE(fputc(getRandomInt<uint8_t>(0, 255), pFile), EOF);
1267 }
1268 fclose(pFile);
1269 *skip = false;
1270 }
1271
1272 enum class ExpectedResult { GENERAL_FAILURE, NOT_CRASH };
1273
1274 // Test if the driver behaves as expected when given corrupted cache or token.
1275 // The modifier will be invoked after save to cache but before prepare from cache.
1276 // The modifier accepts one pointer argument "skip" as the returning value, indicating
1277 // whether the test should be skipped or not.
1278 void testCorruptedCache(ExpectedResult expected, std::function<void(bool*)> modifier) {
1279 const TestModel& testModel = createTestModel();
1280 const Model model = createModel(testModel);
1281 if (checkEarlyTermination(model)) return;
1282
1283 // Save the compilation to cache.
1284 {
1285 hidl_vec<hidl_handle> modelCache, dataCache;
1286 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1287 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1288 saveModelToCache(model, modelCache, dataCache);
1289 }
1290
1291 bool skip = false;
1292 modifier(&skip);
1293 if (skip) return;
1294
1295 // Retrieve preparedModel from cache.
1296 {
1297 sp<IPreparedModel> preparedModel = nullptr;
1298 ErrorStatus status;
1299 hidl_vec<hidl_handle> modelCache, dataCache;
1300 createCacheHandles(mModelCache, AccessMode::READ_WRITE, &modelCache);
1301 createCacheHandles(mDataCache, AccessMode::READ_WRITE, &dataCache);
1302 prepareModelFromCache(modelCache, dataCache, &preparedModel, &status);
1303
1304 switch (expected) {
1305 case ExpectedResult::GENERAL_FAILURE:
1306 ASSERT_EQ(status, ErrorStatus::GENERAL_FAILURE);
1307 ASSERT_EQ(preparedModel, nullptr);
1308 break;
1309 case ExpectedResult::NOT_CRASH:
1310 ASSERT_EQ(preparedModel == nullptr, status != ErrorStatus::NONE);
1311 break;
1312 default:
1313 FAIL();
1314 }
1315 }
1316 }
1317
1318 const uint32_t kSeed = std::get<uint32_t>(GetParam());
1319 std::mt19937 generator;
1320};
1321
1322TEST_P(CompilationCachingSecurityTest, CorruptedModelCache) {
1323 if (!mIsCachingSupported) return;
1324 for (uint32_t i = 0; i < mNumModelCache; i++) {
1325 testCorruptedCache(ExpectedResult::GENERAL_FAILURE,
1326 [this, i](bool* skip) { flipOneBitOfCache(mModelCache[i][0], skip); });
1327 }
1328}
1329
1330TEST_P(CompilationCachingSecurityTest, WrongLengthModelCache) {
1331 if (!mIsCachingSupported) return;
1332 for (uint32_t i = 0; i < mNumModelCache; i++) {
1333 testCorruptedCache(ExpectedResult::GENERAL_FAILURE,
1334 [this, i](bool* skip) { appendBytesToCache(mModelCache[i][0], skip); });
1335 }
1336}
1337
1338TEST_P(CompilationCachingSecurityTest, CorruptedDataCache) {
1339 if (!mIsCachingSupported) return;
1340 for (uint32_t i = 0; i < mNumDataCache; i++) {
1341 testCorruptedCache(ExpectedResult::NOT_CRASH,
1342 [this, i](bool* skip) { flipOneBitOfCache(mDataCache[i][0], skip); });
1343 }
1344}
1345
1346TEST_P(CompilationCachingSecurityTest, WrongLengthDataCache) {
1347 if (!mIsCachingSupported) return;
1348 for (uint32_t i = 0; i < mNumDataCache; i++) {
1349 testCorruptedCache(ExpectedResult::NOT_CRASH,
1350 [this, i](bool* skip) { appendBytesToCache(mDataCache[i][0], skip); });
1351 }
1352}
1353
1354TEST_P(CompilationCachingSecurityTest, WrongToken) {
1355 if (!mIsCachingSupported) return;
1356 testCorruptedCache(ExpectedResult::GENERAL_FAILURE, [this](bool* skip) {
1357 // Randomly flip one single bit in mToken.
1358 uint32_t ind =
1359 getRandomInt(0u, static_cast<uint32_t>(Constant::BYTE_SIZE_OF_CACHE_TOKEN) - 1);
1360 mToken[ind] ^= (1U << getRandomInt(0, 7));
1361 *skip = false;
1362 });
1363}
1364
1365std::string printCompilationCachingSecurityTest(
1366 const testing::TestParamInfo<CompilationCachingSecurityTestParam>& info) {
1367 const auto& [namedDevice, operandType, seed] = info.param;
1368 const std::string type = (operandType == OperandType::TENSOR_FLOAT32 ? "float32" : "quant8");
1369 return gtestCompliantName(getName(namedDevice) + "_" + type + "_" + std::to_string(seed));
1370}
1371
1372INSTANTIATE_TEST_CASE_P(TestCompilationCaching, CompilationCachingSecurityTest,
1373 testing::Combine(kNamedDeviceChoices, kOperandTypeChoices,
1374 testing::Range(0U, 10U)),
1375 printCompilationCachingSecurityTest);
1376
Lev Proleev26d1bc82019-08-30 11:57:18 +01001377} // namespace android::hardware::neuralnetworks::V1_3::vts::functional