• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "os/mem.h"
16 #include "mem/mem.h"
17 #include "utils/asan_interface.h"
18 
19 #include "gtest/gtest.h"
20 
21 namespace panda::os::mem {
22 
23 class MMapFixedTest : public testing::Test {
24 protected:
25     static constexpr uint64_t MAGIC_VALUE = 0xDEADBEAF;
DeathWrite64(uintptr_t addr)26     void DeathWrite64(uintptr_t addr)
27     {
28         auto pointer = static_cast<uint64_t *>(ToVoidPtr(addr));
29         *pointer = MAGIC_VALUE;
30     }
31 };
32 
TEST_F(MMapFixedTest,MMapAsanTest)33 TEST_F(MMapFixedTest, MMapAsanTest)
34 {
35     static constexpr size_t OFFSET = 4_KB;
36     static constexpr size_t MMAP_ALLOC_SIZE = OFFSET * 2;
37     size_t page_size = panda::os::mem::GetPageSize();
38     static_assert(OFFSET < panda::os::mem::MMAP_FIXED_MAGIC_ADDR_FOR_ASAN);
39     static_assert(MMAP_ALLOC_SIZE > OFFSET);
40     ASSERT_TRUE((MMAP_ALLOC_SIZE % page_size) == 0);
41     uintptr_t cur_addr = panda::os::mem::MMAP_FIXED_MAGIC_ADDR_FOR_ASAN - OFFSET;
42     cur_addr = AlignUp(cur_addr, page_size);
43     ASSERT_TRUE((cur_addr % page_size) == 0);
44     uintptr_t end_addr = panda::os::mem::MMAP_FIXED_MAGIC_ADDR_FOR_ASAN;
45     end_addr = AlignUp(end_addr, sizeof(uint64_t));
46     void *result =  // NOLINTNEXTLINE(hicpp-signed-bitwise)
47         mmap(ToVoidPtr(cur_addr), MMAP_ALLOC_SIZE, MMAP_PROT_READ | MMAP_PROT_WRITE,
48              MMAP_FLAG_PRIVATE | MMAP_FLAG_ANONYMOUS | MMAP_FLAG_FIXED, -1, 0);
49     ASSERT_TRUE(result != nullptr);
50     ASSERT_TRUE(ToUintPtr(result) == cur_addr);
51     while (cur_addr < end_addr) {
52         DeathWrite64(cur_addr);
53         cur_addr += sizeof(uint64_t);
54     }
55 #if defined(PANDA_ASAN_ON)
56     // Check Death:
57     EXPECT_DEATH(DeathWrite64(end_addr), "");
58 #else
59     // Writing must be finished successfully
60     DeathWrite64(end_addr);
61 #endif
62     munmap(result, MMAP_ALLOC_SIZE);
63 }
64 
65 }  // namespace panda::os::mem
66