1 /* 2 * Copyright (c) 2021-2022 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 #include "utils/logger.h" 22 23 namespace panda { 24 25 class CodeAllocatorTest : public testing::Test { 26 public: CodeAllocatorTest()27 CodeAllocatorTest() {} 28 ~CodeAllocatorTest()29 ~CodeAllocatorTest() 30 { 31 Logger::Destroy(); 32 } 33 34 protected: 35 static constexpr size_t k1K = 1024; 36 static constexpr size_t testHeapSize = k1K * k1K; 37 IsAligned(const void * ptr,size_t alignment)38 static bool IsAligned(const void *ptr, size_t alignment) 39 { 40 return reinterpret_cast<uintptr_t>(ptr) % alignment == 0; 41 } 42 SetUp()43 void SetUp() override 44 { 45 panda::mem::MemConfig::Initialize(0, 32_MB, 0, 32_MB); 46 PoolManager::Initialize(); 47 } 48 TearDown()49 void TearDown() override 50 { 51 PoolManager::Finalize(); 52 panda::mem::MemConfig::Finalize(); 53 } 54 }; 55 56 HWTEST_F(CodeAllocatorTest, AllocateBuffTest, testing::ext::TestSize.Level0) 57 { 58 BaseMemStats stats; 59 CodeAllocator ca(&stats); 60 uint8_t buff[] = {0xCC, 0xCC}; 61 void *code_buff = ca.AllocateCode(sizeof(buff), static_cast<void *>(&buff[0])); 62 for (size_t i = 0; i < sizeof(buff); i++) { 63 ASSERT_EQ(static_cast<uint8_t *>(code_buff)[i], 0xCC); 64 } 65 ASSERT_TRUE(IsAligned(code_buff, 4 * SIZE_1K)); 66 67 std::byte byte{0x00}; 68 os::mem::MapRange<std::byte> map_range = ca.AllocateCodeUnprotected(8U); 69 ASSERT_EQ(map_range.GetSize(), 8U); 70 ASSERT_EQ(*(map_range.GetData()), byte); 71 } 72 73 } // namespace panda 74