1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #if defined(ANDROID_EXPERIMENTAL_MTE)
18 
19 #include <sys/mman.h>
20 #include <sys/types.h>
21 
22 #include <gtest/gtest.h>
23 
24 #include <bionic/mte.h>
25 
26 #include "MemoryLocal.h"
27 #include "MemoryRemote.h"
28 #include "TestUtils.h"
29 
30 namespace unwindstack {
31 
CreateTagMapping()32 static uintptr_t CreateTagMapping() {
33   uintptr_t mapping =
34       reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
35                                        MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
36   if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
37     return 0;
38   }
39 #if defined(__aarch64__)
40   __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
41                        :
42                        : "r"(mapping + (1ULL << 56))
43                        : "memory");
44 #endif
45   return mapping;
46 }
47 
TEST(MemoryMteTest,remote_read_tag)48 TEST(MemoryMteTest, remote_read_tag) {
49 #if !defined(__aarch64__)
50   GTEST_SKIP() << "Requires aarch64";
51 #else
52   if (!mte_supported()) {
53     GTEST_SKIP() << "Requires MTE";
54   }
55 #endif
56 
57   uintptr_t mapping = CreateTagMapping();
58   ASSERT_NE(0U, mapping);
59 
60   pid_t pid;
61   if ((pid = fork()) == 0) {
62     while (true)
63       ;
64     exit(1);
65   }
66   ASSERT_LT(0, pid);
67   TestScopedPidReaper reap(pid);
68 
69   ASSERT_TRUE(TestAttach(pid));
70 
71   MemoryRemote remote(pid);
72 
73   EXPECT_EQ(1, remote.ReadTag(mapping));
74   EXPECT_EQ(0, remote.ReadTag(mapping + 16));
75 
76   ASSERT_TRUE(TestDetach(pid));
77 }
78 
TEST(MemoryMteTest,local_read_tag)79 TEST(MemoryMteTest, local_read_tag) {
80 #if !defined(__aarch64__)
81   GTEST_SKIP() << "Requires aarch64";
82 #else
83   if (!mte_supported()) {
84     GTEST_SKIP() << "Requires MTE";
85   }
86 #endif
87 
88   uintptr_t mapping = CreateTagMapping();
89   ASSERT_NE(0U, mapping);
90 
91   MemoryLocal local;
92 
93   EXPECT_EQ(1, local.ReadTag(mapping));
94   EXPECT_EQ(0, local.ReadTag(mapping + 16));
95 }
96 
97 }  // namespace unwindstack
98 
99 #endif
100