Software APIs
hardened_memory_unittest.cc
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
6 
7 #include <vector>
8 
9 #include "gmock/gmock.h"
10 #include "gtest/gtest.h"
11 
12 // NOTE: This test does not verify hardening measures; it only checks that the
13 // "normal" contract of the functions is upheld.
14 
15 namespace hardened_memory_unittest {
16 namespace {
17 
18 using ::testing::Each;
19 using ::testing::ElementsAre;
20 
21 TEST(HardenedMemory, Memcpy) {
22  std::vector<uint32_t> xs = {1, 2, 3, 4, 5, 6, 7, 8};
23  std::vector<uint32_t> ys(8);
24 
25  hardened_memcpy(ys.data(), xs.data(), 0);
26  EXPECT_THAT(ys, Each(0));
27 
28  hardened_memcpy(ys.data() + 1, xs.data(), 7);
29  EXPECT_THAT(ys, ElementsAre(0, 1, 2, 3, 4, 5, 6, 7));
30 }
31 
32 constexpr uint32_t kRandomWord = 0xdeadbeef;
33 
34 // Override whatever the default randomness source is so we can verify it
35 // actually gets used.
36 extern "C" size_t hardened_memshred_random_word() { return kRandomWord; }
37 
38 TEST(HardenedMemory, MemShred) {
39  std::vector<uint32_t> xs = {1, 2, 3, 4, 5, 6, 7, 8};
40  hardened_memshred(xs.data(), xs.size());
41 
42  EXPECT_THAT(xs, Each(kRandomWord));
43 }
44 
45 TEST(HardenedMemory, MemEq) {
46  std::vector<uint32_t> xs = {1, 2, 3, 4, 5, 6, 7, 8};
47  std::vector<uint32_t> ys = xs;
48 
49  EXPECT_EQ(hardened_memeq(ys.data(), xs.data(), xs.size()), kHardenedBoolTrue);
50 
51  ++ys[5];
52  EXPECT_EQ(hardened_memeq(ys.data(), xs.data(), xs.size()),
54 }
55 
56 } // namespace
57 } // namespace hardened_memory_unittest