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/ptrace.h>
20 #include <sys/uio.h>
21 
22 #include <bionic/mte.h>
23 #include <bionic/mte_kernel.h>
24 
25 #include "MemoryLocal.h"
26 #include "MemoryRemote.h"
27 
28 namespace unwindstack {
29 
ReadTag(uint64_t addr)30 long MemoryRemote::ReadTag(uint64_t addr) {
31 #if defined(__aarch64__)
32   char tag;
33   iovec iov = {&tag, 1};
34   if (ptrace(PTRACE_PEEKMTETAGS, pid_, reinterpret_cast<void*>(addr), &iov) != 0 ||
35       iov.iov_len != 1) {
36     return -1;
37   }
38   return tag;
39 #else
40   (void)addr;
41   return -1;
42 #endif
43 }
44 
ReadTag(uint64_t addr)45 long MemoryLocal::ReadTag(uint64_t addr) {
46 #if defined(__aarch64__)
47   // Check that the memory is readable first. This is racy with the ldg but there's not much
48   // we can do about it.
49   char data;
50   if (!mte_supported() || !Read(addr, &data, 1)) {
51     return -1;
52   }
53 
54   __asm__ __volatile__(".arch_extension mte; ldg %0, [%0]" : "+r"(addr) : : "memory");
55   return (addr >> 56) & 0xf;
56 #else
57   (void)addr;
58   return -1;
59 #endif
60 }
61 
62 }  // namespace unwindstack
63 
64 #endif
65