1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "mem/code_allocator.h"
17 #include "mem/pool_manager.h"
18 #include "mem/base_mem_stats.h"
19
20 #include "gtest/gtest.h"
21
22 namespace ark {
23
24 // NOLINTBEGIN(readability-magic-numbers)
25
26 class BaseMemStatsTest : public testing::Test {
27 protected:
SetUp()28 void SetUp() override
29 {
30 ark::mem::MemConfig::Initialize(128_MB, 64_MB, 64_MB, 32_MB, 0U, 0U);
31 PoolManager::Initialize();
32 }
33
TearDown()34 void TearDown() override
35 {
36 PoolManager::Finalize();
37 ark::mem::MemConfig::Finalize();
38 }
39 };
40
TEST_F(BaseMemStatsTest,CodeStatistic)41 TEST_F(BaseMemStatsTest, CodeStatistic)
42 {
43 static constexpr size_t N = 100;
44 BaseMemStats stats;
45 size_t sum = 0;
46 for (size_t i = 1; i < N; i++) {
47 sum += i;
48 stats.RecordAllocateRaw(i, SpaceType::SPACE_TYPE_CODE);
49 }
50 stats.RecordFreeRaw(N, SpaceType::SPACE_TYPE_CODE);
51 ASSERT_EQ(sum, stats.GetAllocated(SpaceType::SPACE_TYPE_CODE));
52 ASSERT_EQ(N, stats.GetFreed(SpaceType::SPACE_TYPE_CODE));
53 ASSERT_EQ(sum - N, stats.GetFootprint(SpaceType::SPACE_TYPE_CODE));
54 }
55
TEST_F(BaseMemStatsTest,AllocationsOverAllocator)56 TEST_F(BaseMemStatsTest, AllocationsOverAllocator)
57 {
58 BaseMemStats stats;
59 void *tmp;
60 CodeAllocator ca(&stats);
61
62 // NOLINTBEGIN(modernize-avoid-c-arrays)
63 uint8_t buff1[] = {0xCCU};
64 uint8_t buff2[] = {0xCCU, 0xCCU, 0xCCU};
65 // NOLINTEND(modernize-avoid-c-arrays)
66 size_t size1 = sizeof(buff1);
67 size_t size2 = sizeof(buff2);
68
69 // NOLINTBEGIN(clang-analyzer-deadcode.DeadStores)
70 tmp = ca.AllocateCode(size1, static_cast<void *>(&buff1[0U]));
71 tmp = ca.AllocateCode(sizeof(buff2), static_cast<void *>(&buff2[0U]));
72 // NOLINTEND(clang-analyzer-deadcode.DeadStores)
73
74 ASSERT_EQ(size1 + size2, stats.GetAllocated(SpaceType::SPACE_TYPE_CODE));
75 ASSERT_EQ(0U, stats.GetFreed(SpaceType::SPACE_TYPE_CODE));
76 ASSERT_EQ(size1 + size2, stats.GetFootprint(SpaceType::SPACE_TYPE_CODE));
77
78 stats.RecordFreeRaw(size2, SpaceType::SPACE_TYPE_CODE);
79
80 ASSERT_EQ(sizeof(buff1) + sizeof(buff2), stats.GetAllocated(SpaceType::SPACE_TYPE_CODE));
81 ASSERT_EQ(sizeof(buff2), stats.GetFreed(SpaceType::SPACE_TYPE_CODE));
82 ASSERT_EQ(sizeof(buff1), stats.GetFootprint(SpaceType::SPACE_TYPE_CODE));
83 }
84
85 // NOLINTEND(readability-magic-numbers)
86
87 } // namespace ark
88