1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include "heap_tagging.h"
30 #include "malloc_common.h"
31 #include "malloc_tagged_pointers.h"
32
33 #include <bionic/pthread_internal.h>
34 #include <platform/bionic/malloc.h>
35 #include <sanitizer/hwasan_interface.h>
36 #include <sys/auxv.h>
37 #include <sys/prctl.h>
38
39 extern "C" void scudo_malloc_disable_memory_tagging();
40 extern "C" void scudo_malloc_set_track_allocation_stacks(int);
41
42 extern "C" const char* __scudo_get_stack_depot_addr();
43 extern "C" const char* __scudo_get_ring_buffer_addr();
44 extern "C" size_t __scudo_get_ring_buffer_size();
45 extern "C" size_t __scudo_get_stack_depot_size();
46
47 // Protected by `g_heap_tagging_lock`.
48 static HeapTaggingLevel heap_tagging_level = M_HEAP_TAGGING_LEVEL_NONE;
49
SetDefaultHeapTaggingLevel()50 void SetDefaultHeapTaggingLevel() {
51 #if defined(__aarch64__)
52 #if !__has_feature(hwaddress_sanitizer)
53 heap_tagging_level = __libc_shared_globals()->initial_heap_tagging_level;
54 #endif
55
56 __libc_globals.mutate([](libc_globals* globals) {
57 switch (heap_tagging_level) {
58 case M_HEAP_TAGGING_LEVEL_TBI:
59 // Arrange for us to set pointer tags to POINTER_TAG, check tags on
60 // deallocation and untag when passing pointers to the allocator.
61 globals->heap_pointer_tag = (reinterpret_cast<uintptr_t>(POINTER_TAG) << TAG_SHIFT) |
62 (0xffull << CHECK_SHIFT) | (0xffull << UNTAG_SHIFT);
63 break;
64 case M_HEAP_TAGGING_LEVEL_SYNC:
65 case M_HEAP_TAGGING_LEVEL_ASYNC:
66 atomic_store(&globals->memtag, true);
67 atomic_store(&__libc_memtag_stack, __libc_shared_globals()->initial_memtag_stack);
68 break;
69 default:
70 break;
71 };
72 });
73
74 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
75 switch (heap_tagging_level) {
76 case M_HEAP_TAGGING_LEVEL_TBI:
77 case M_HEAP_TAGGING_LEVEL_NONE:
78 scudo_malloc_disable_memory_tagging();
79 break;
80 case M_HEAP_TAGGING_LEVEL_SYNC:
81 scudo_malloc_set_track_allocation_stacks(1);
82 break;
83 default:
84 break;
85 }
86 #endif // USE_SCUDO
87 #endif // aarch64
88 }
89
set_tcf_on_all_threads(int tcf)90 static bool set_tcf_on_all_threads(int tcf) {
91 return android_run_on_all_threads(
92 [](void* arg) {
93 int tcf = *reinterpret_cast<int*>(arg);
94 int tagged_addr_ctrl = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
95 if (tagged_addr_ctrl < 0) {
96 return false;
97 }
98
99 tagged_addr_ctrl = (tagged_addr_ctrl & ~PR_MTE_TCF_MASK) | tcf;
100 return prctl(PR_SET_TAGGED_ADDR_CTRL, tagged_addr_ctrl, 0, 0, 0) >= 0;
101 },
102 &tcf);
103 }
104
105 pthread_mutex_t g_heap_tagging_lock = PTHREAD_MUTEX_INITIALIZER;
106
107 // Requires `g_heap_tagging_lock` to be held.
SetHeapTaggingLevel(HeapTaggingLevel tag_level)108 bool SetHeapTaggingLevel(HeapTaggingLevel tag_level) {
109 if (tag_level == heap_tagging_level) {
110 return true;
111 }
112
113 switch (tag_level) {
114 case M_HEAP_TAGGING_LEVEL_NONE:
115 __libc_globals.mutate([](libc_globals* globals) {
116 if (heap_tagging_level == M_HEAP_TAGGING_LEVEL_TBI) {
117 // Preserve the untag mask (we still want to untag pointers when passing them to the
118 // allocator), but clear the fixed tag and the check mask, so that pointers are no longer
119 // tagged and checks no longer happen.
120 globals->heap_pointer_tag = static_cast<uintptr_t>(0xffull << UNTAG_SHIFT);
121 }
122 atomic_store(&__libc_memtag_stack, false);
123 atomic_store(&globals->memtag, false);
124 });
125
126 if (heap_tagging_level != M_HEAP_TAGGING_LEVEL_TBI) {
127 if (!set_tcf_on_all_threads(PR_MTE_TCF_NONE)) {
128 error_log("SetHeapTaggingLevel: set_tcf_on_all_threads failed");
129 return false;
130 }
131 }
132 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
133 scudo_malloc_disable_memory_tagging();
134 #endif
135 break;
136 case M_HEAP_TAGGING_LEVEL_TBI:
137 case M_HEAP_TAGGING_LEVEL_ASYNC:
138 case M_HEAP_TAGGING_LEVEL_SYNC:
139 if (heap_tagging_level == M_HEAP_TAGGING_LEVEL_NONE) {
140 #if !__has_feature(hwaddress_sanitizer)
141 // Suppress the error message in HWASan builds. Apps can try to enable TBI (or even MTE
142 // modes) being unaware of HWASan, fail them silently.
143 error_log(
144 "SetHeapTaggingLevel: re-enabling tagging after it was disabled is not supported");
145 #endif
146 return false;
147 } else if (tag_level == M_HEAP_TAGGING_LEVEL_TBI ||
148 heap_tagging_level == M_HEAP_TAGGING_LEVEL_TBI) {
149 error_log("SetHeapTaggingLevel: switching between TBI and ASYNC/SYNC is not supported");
150 return false;
151 }
152
153 if (tag_level == M_HEAP_TAGGING_LEVEL_ASYNC) {
154 // When entering ASYNC mode, specify that we want to allow upgrading to SYNC by OR'ing in
155 // the SYNC flag. But if the kernel doesn't support specifying multiple TCF modes, fall back
156 // to specifying a single mode.
157 if (!set_tcf_on_all_threads(PR_MTE_TCF_ASYNC | PR_MTE_TCF_SYNC)) {
158 set_tcf_on_all_threads(PR_MTE_TCF_ASYNC);
159 }
160 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
161 scudo_malloc_set_track_allocation_stacks(0);
162 #endif
163 } else if (tag_level == M_HEAP_TAGGING_LEVEL_SYNC) {
164 set_tcf_on_all_threads(PR_MTE_TCF_SYNC);
165 #if defined(USE_SCUDO) && !__has_feature(hwaddress_sanitizer)
166 scudo_malloc_set_track_allocation_stacks(1);
167 __libc_shared_globals()->scudo_ring_buffer = __scudo_get_ring_buffer_addr();
168 __libc_shared_globals()->scudo_ring_buffer_size = __scudo_get_ring_buffer_size();
169 __libc_shared_globals()->scudo_stack_depot = __scudo_get_stack_depot_addr();
170 __libc_shared_globals()->scudo_stack_depot_size = __scudo_get_stack_depot_size();
171 #endif
172 }
173 break;
174 default:
175 error_log("SetHeapTaggingLevel: unknown tagging level");
176 return false;
177 }
178
179 heap_tagging_level = tag_level;
180 info_log("SetHeapTaggingLevel: tag level set to %d", tag_level);
181
182 return true;
183 }
184
185 #ifdef __aarch64__
untag_memory(void * from,void * to)186 static inline __attribute__((no_sanitize("memtag"))) void untag_memory(void* from, void* to) {
187 if (from == to) {
188 return;
189 }
190 __asm__ __volatile__(
191 ".arch_extension mte\n"
192 "1:\n"
193 "stg %[Ptr], [%[Ptr]], #16\n"
194 "cmp %[Ptr], %[End]\n"
195 "b.lt 1b\n"
196 : [Ptr] "+&r"(from)
197 : [End] "r"(to)
198 : "memory");
199 }
200 #endif
201
202 #ifdef __aarch64__
203 // 128Mb of stack should be enough for anybody.
204 static constexpr size_t kUntagLimit = 128 * 1024 * 1024;
205 #endif // __aarch64__
206
memtag_handle_longjmp(void * sp_dst __unused,void * sp_src __unused)207 extern "C" __LIBC_HIDDEN__ __attribute__((no_sanitize("memtag"))) void memtag_handle_longjmp(
208 void* sp_dst __unused, void* sp_src __unused) {
209 // A usual longjmp looks like this, where sp_dst was the LR in the call to setlongjmp (i.e.
210 // the SP of the frame calling setlongjmp).
211 // ┌─────────────────────┐ │
212 // │ │ │
213 // ├─────────────────────┤◄──────── sp_dst │ stack
214 // │ ... │ │ grows
215 // ├─────────────────────┤ │ to lower
216 // │ ... │ │ addresses
217 // ├─────────────────────┤◄──────── sp_src │
218 // │siglongjmp │ │
219 // ├─────────────────────┤ │
220 // │memtag_handle_longjmp│ │
221 // └─────────────────────┘ ▼
222 #ifdef __aarch64__
223 if (atomic_load(&__libc_memtag_stack)) {
224 size_t distance = reinterpret_cast<uintptr_t>(sp_dst) - reinterpret_cast<uintptr_t>(sp_src);
225 if (distance > kUntagLimit) {
226 async_safe_fatal(
227 "memtag_handle_longjmp: stack adjustment too large! %p -> %p, distance %zx > %zx\n",
228 sp_src, sp_dst, distance, kUntagLimit);
229 } else {
230 untag_memory(sp_src, sp_dst);
231 }
232 }
233 #endif // __aarch64__
234
235 // We can use __has_feature here rather than __hwasan_handle_longjmp as a
236 // weak symbol because this is part of libc which is always sanitized for a
237 // hwasan enabled process.
238 #if __has_feature(hwaddress_sanitizer)
239 __hwasan_handle_longjmp(sp_dst);
240 #endif // __has_feature(hwaddress_sanitizer)
241 }
242