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