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