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