1 //===-- hwasan_linux.cpp ----------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file is a part of HWAddressSanitizer and contains Linux-, NetBSD- and
11 /// FreeBSD-specific code.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "sanitizer_common/sanitizer_platform.h"
16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
17 
18 #include "hwasan.h"
19 #include "hwasan_dynamic_shadow.h"
20 #include "hwasan_interface_internal.h"
21 #include "hwasan_mapping.h"
22 #include "hwasan_report.h"
23 #include "hwasan_thread.h"
24 #include "hwasan_thread_list.h"
25 
26 #include <dlfcn.h>
27 #include <elf.h>
28 #include <link.h>
29 #include <pthread.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <sys/resource.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36 #include <unwind.h>
37 #include <sys/prctl.h>
38 #include <errno.h>
39 
40 #include "sanitizer_common/sanitizer_common.h"
41 #include "sanitizer_common/sanitizer_procmaps.h"
42 
43 // Configurations of HWASAN_WITH_INTERCEPTORS and SANITIZER_ANDROID.
44 //
45 // HWASAN_WITH_INTERCEPTORS=OFF, SANITIZER_ANDROID=OFF
46 //   Not currently tested.
47 // HWASAN_WITH_INTERCEPTORS=OFF, SANITIZER_ANDROID=ON
48 //   Integration tests downstream exist.
49 // HWASAN_WITH_INTERCEPTORS=ON, SANITIZER_ANDROID=OFF
50 //    Tested with check-hwasan on x86_64-linux.
51 // HWASAN_WITH_INTERCEPTORS=ON, SANITIZER_ANDROID=ON
52 //    Tested with check-hwasan on aarch64-linux-android.
53 #if !SANITIZER_ANDROID
54 SANITIZER_INTERFACE_ATTRIBUTE
55 THREADLOCAL uptr __hwasan_tls;
56 #endif
57 
58 namespace __hwasan {
59 
60 // With the zero shadow base we can not actually map pages starting from 0.
61 // This constant is somewhat arbitrary.
62 constexpr uptr kZeroBaseShadowStart = 0;
63 constexpr uptr kZeroBaseMaxShadowStart = 1 << 18;
64 
65 static void ProtectGap(uptr addr, uptr size) {
66   __sanitizer::ProtectGap(addr, size, kZeroBaseShadowStart,
67                           kZeroBaseMaxShadowStart);
68 }
69 
70 uptr kLowMemStart;
71 uptr kLowMemEnd;
72 uptr kLowShadowEnd;
73 uptr kLowShadowStart;
74 uptr kHighShadowStart;
75 uptr kHighShadowEnd;
76 uptr kHighMemStart;
77 uptr kHighMemEnd;
78 
79 uptr kAliasRegionStart;  // Always 0 on non-x86.
80 
81 static void PrintRange(uptr start, uptr end, const char *name) {
82   Printf("|| [%p, %p] || %.*s ||\n", (void *)start, (void *)end, 10, name);
83 }
84 
85 static void PrintAddressSpaceLayout() {
86   PrintRange(kHighMemStart, kHighMemEnd, "HighMem");
87   if (kHighShadowEnd + 1 < kHighMemStart)
88     PrintRange(kHighShadowEnd + 1, kHighMemStart - 1, "ShadowGap");
89   else
90     CHECK_EQ(kHighShadowEnd + 1, kHighMemStart);
91   PrintRange(kHighShadowStart, kHighShadowEnd, "HighShadow");
92   if (kLowShadowEnd + 1 < kHighShadowStart)
93     PrintRange(kLowShadowEnd + 1, kHighShadowStart - 1, "ShadowGap");
94   else
95     CHECK_EQ(kLowMemEnd + 1, kHighShadowStart);
96   PrintRange(kLowShadowStart, kLowShadowEnd, "LowShadow");
97   if (kLowMemEnd + 1 < kLowShadowStart)
98     PrintRange(kLowMemEnd + 1, kLowShadowStart - 1, "ShadowGap");
99   else
100     CHECK_EQ(kLowMemEnd + 1, kLowShadowStart);
101   PrintRange(kLowMemStart, kLowMemEnd, "LowMem");
102   CHECK_EQ(0, kLowMemStart);
103 }
104 
105 static uptr GetHighMemEnd() {
106   // HighMem covers the upper part of the address space.
107   uptr max_address = GetMaxUserVirtualAddress();
108   // Adjust max address to make sure that kHighMemEnd and kHighMemStart are
109   // properly aligned:
110   max_address |= (GetMmapGranularity() << kShadowScale) - 1;
111   return max_address;
112 }
113 
114 static void InitializeShadowBaseAddress(uptr shadow_size_bytes) {
115   __hwasan_shadow_memory_dynamic_address =
116       FindDynamicShadowStart(shadow_size_bytes);
117 }
118 
119 void InitPrctl() {
120 #define PR_SET_TAGGED_ADDR_CTRL 55
121 #define PR_GET_TAGGED_ADDR_CTRL 56
122 #define PR_TAGGED_ADDR_ENABLE (1UL << 0)
123   // Check we're running on a kernel that can use the tagged address ABI.
124   int local_errno = 0;
125   if (internal_iserror(internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0),
126                        &local_errno) &&
127       local_errno == EINVAL) {
128 #if SANITIZER_ANDROID || defined(__x86_64__)
129     // Some older Android kernels have the tagged pointer ABI on
130     // unconditionally, and hence don't have the tagged-addr prctl while still
131     // allow the ABI.
132     // If targeting Android and the prctl is not around we assume this is the
133     // case.
134     return;
135 #else
136     if (flags()->fail_without_syscall_abi) {
137       Printf(
138           "FATAL: "
139           "HWAddressSanitizer requires a kernel with tagged address ABI.\n");
140       Die();
141     }
142 #endif
143   }
144 
145   // Turn on the tagged address ABI.
146   if ((internal_iserror(internal_prctl(PR_SET_TAGGED_ADDR_CTRL,
147                                        PR_TAGGED_ADDR_ENABLE, 0, 0, 0)) ||
148        !internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0)) &&
149       flags()->fail_without_syscall_abi) {
150     Printf(
151         "FATAL: HWAddressSanitizer failed to enable tagged address syscall "
152         "ABI.\nSuggest check `sysctl abi.tagged_addr_disabled` "
153         "configuration.\n");
154     Die();
155   }
156 #undef PR_SET_TAGGED_ADDR_CTRL
157 #undef PR_GET_TAGGED_ADDR_CTRL
158 #undef PR_TAGGED_ADDR_ENABLE
159 }
160 
161 bool InitShadow() {
162   // Define the entire memory range.
163   kHighMemEnd = GetHighMemEnd();
164 
165   // Determine shadow memory base offset.
166   InitializeShadowBaseAddress(MemToShadowSize(kHighMemEnd));
167 
168   // Place the low memory first.
169   kLowMemEnd = __hwasan_shadow_memory_dynamic_address - 1;
170   kLowMemStart = 0;
171 
172   // Define the low shadow based on the already placed low memory.
173   kLowShadowEnd = MemToShadow(kLowMemEnd);
174   kLowShadowStart = __hwasan_shadow_memory_dynamic_address;
175 
176   // High shadow takes whatever memory is left up there (making sure it is not
177   // interfering with low memory in the fixed case).
178   kHighShadowEnd = MemToShadow(kHighMemEnd);
179   kHighShadowStart = Max(kLowMemEnd, MemToShadow(kHighShadowEnd)) + 1;
180 
181   // High memory starts where allocated shadow allows.
182   kHighMemStart = ShadowToMem(kHighShadowStart);
183 
184 #if defined(__x86_64__)
185   constexpr uptr kAliasRegionOffset = 1ULL << (kTaggableRegionCheckShift - 1);
186   kAliasRegionStart =
187       __hwasan_shadow_memory_dynamic_address + kAliasRegionOffset;
188 
189   CHECK_EQ(kAliasRegionStart >> kTaggableRegionCheckShift,
190            __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
191   CHECK_EQ(
192       (kAliasRegionStart + kAliasRegionOffset - 1) >> kTaggableRegionCheckShift,
193       __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
194 #endif
195 
196   // Check the sanity of the defined memory ranges (there might be gaps).
197   CHECK_EQ(kHighMemStart % GetMmapGranularity(), 0);
198   CHECK_GT(kHighMemStart, kHighShadowEnd);
199   CHECK_GT(kHighShadowEnd, kHighShadowStart);
200   CHECK_GT(kHighShadowStart, kLowMemEnd);
201   CHECK_GT(kLowMemEnd, kLowMemStart);
202   CHECK_GT(kLowShadowEnd, kLowShadowStart);
203   CHECK_GT(kLowShadowStart, kLowMemEnd);
204 
205   if (Verbosity())
206     PrintAddressSpaceLayout();
207 
208   // Reserve shadow memory.
209   ReserveShadowMemoryRange(kLowShadowStart, kLowShadowEnd, "low shadow");
210   ReserveShadowMemoryRange(kHighShadowStart, kHighShadowEnd, "high shadow");
211 
212   // Protect all the gaps.
213   ProtectGap(0, Min(kLowMemStart, kLowShadowStart));
214   if (kLowMemEnd + 1 < kLowShadowStart)
215     ProtectGap(kLowMemEnd + 1, kLowShadowStart - kLowMemEnd - 1);
216   if (kLowShadowEnd + 1 < kHighShadowStart)
217     ProtectGap(kLowShadowEnd + 1, kHighShadowStart - kLowShadowEnd - 1);
218   if (kHighShadowEnd + 1 < kHighMemStart)
219     ProtectGap(kHighShadowEnd + 1, kHighMemStart - kHighShadowEnd - 1);
220 
221   return true;
222 }
223 
224 void InitThreads() {
225   CHECK(__hwasan_shadow_memory_dynamic_address);
226   uptr guard_page_size = GetMmapGranularity();
227   uptr thread_space_start =
228       __hwasan_shadow_memory_dynamic_address - (1ULL << kShadowBaseAlignment);
229   uptr thread_space_end =
230       __hwasan_shadow_memory_dynamic_address - guard_page_size;
231   ReserveShadowMemoryRange(thread_space_start, thread_space_end - 1,
232                            "hwasan threads", /*madvise_shadow*/ false);
233   ProtectGap(thread_space_end,
234              __hwasan_shadow_memory_dynamic_address - thread_space_end);
235   InitThreadList(thread_space_start, thread_space_end - thread_space_start);
236 }
237 
238 bool MemIsApp(uptr p) {
239 #if !defined(__x86_64__)  // Memory outside the alias range has non-zero tags.
240   CHECK(GetTagFromPointer(p) == 0);
241 #endif
242   return p >= kHighMemStart || (p >= kLowMemStart && p <= kLowMemEnd);
243 }
244 
245 static void HwasanAtExit(void) {
246   if (common_flags()->print_module_map)
247     DumpProcessMap();
248   if (flags()->print_stats && (flags()->atexit || hwasan_report_count > 0))
249     ReportStats();
250   if (hwasan_report_count > 0) {
251     // ReportAtExitStatistics();
252     if (common_flags()->exitcode)
253       internal__exit(common_flags()->exitcode);
254   }
255 }
256 
257 void InstallAtExitHandler() {
258   atexit(HwasanAtExit);
259 }
260 
261 // ---------------------- TSD ---------------- {{{1
262 
263 extern "C" void __hwasan_thread_enter() {
264   hwasanThreadList().CreateCurrentThread()->InitRandomState();
265 }
266 
267 extern "C" void __hwasan_thread_exit() {
268   Thread *t = GetCurrentThread();
269   // Make sure that signal handler can not see a stale current thread pointer.
270   atomic_signal_fence(memory_order_seq_cst);
271   if (t)
272     hwasanThreadList().ReleaseThread(t);
273 }
274 
275 #if HWASAN_WITH_INTERCEPTORS
276 static pthread_key_t tsd_key;
277 static bool tsd_key_inited = false;
278 
279 void HwasanTSDThreadInit() {
280   if (tsd_key_inited)
281     CHECK_EQ(0, pthread_setspecific(tsd_key,
282                                     (void *)GetPthreadDestructorIterations()));
283 }
284 
285 void HwasanTSDDtor(void *tsd) {
286   uptr iterations = (uptr)tsd;
287   if (iterations > 1) {
288     CHECK_EQ(0, pthread_setspecific(tsd_key, (void *)(iterations - 1)));
289     return;
290   }
291   __hwasan_thread_exit();
292 }
293 
294 void HwasanTSDInit() {
295   CHECK(!tsd_key_inited);
296   tsd_key_inited = true;
297   CHECK_EQ(0, pthread_key_create(&tsd_key, HwasanTSDDtor));
298 }
299 #else
300 void HwasanTSDInit() {}
301 void HwasanTSDThreadInit() {}
302 #endif
303 
304 #if SANITIZER_ANDROID
305 uptr *GetCurrentThreadLongPtr() {
306   return (uptr *)get_android_tls_ptr();
307 }
308 #else
309 uptr *GetCurrentThreadLongPtr() {
310   return &__hwasan_tls;
311 }
312 #endif
313 
314 #if SANITIZER_ANDROID
315 void AndroidTestTlsSlot() {
316   uptr kMagicValue = 0x010203040A0B0C0D;
317   uptr *tls_ptr = GetCurrentThreadLongPtr();
318   uptr old_value = *tls_ptr;
319   *tls_ptr = kMagicValue;
320   dlerror();
321   if (*(uptr *)get_android_tls_ptr() != kMagicValue) {
322     Printf(
323         "ERROR: Incompatible version of Android: TLS_SLOT_SANITIZER(6) is used "
324         "for dlerror().\n");
325     Die();
326   }
327   *tls_ptr = old_value;
328 }
329 #else
330 void AndroidTestTlsSlot() {}
331 #endif
332 
333 Thread *GetCurrentThread() {
334   uptr *ThreadLongPtr = GetCurrentThreadLongPtr();
335   if (UNLIKELY(*ThreadLongPtr == 0))
336     return nullptr;
337   auto *R = (StackAllocationsRingBuffer *)ThreadLongPtr;
338   return hwasanThreadList().GetThreadByBufferAddress((uptr)R->Next());
339 }
340 
341 struct AccessInfo {
342   uptr addr;
343   uptr size;
344   bool is_store;
345   bool is_load;
346   bool recover;
347 };
348 
349 static AccessInfo GetAccessInfo(siginfo_t *info, ucontext_t *uc) {
350   // Access type is passed in a platform dependent way (see below) and encoded
351   // as 0xXY, where X&1 is 1 for store, 0 for load, and X&2 is 1 if the error is
352   // recoverable. Valid values of Y are 0 to 4, which are interpreted as
353   // log2(access_size), and 0xF, which means that access size is passed via
354   // platform dependent register (see below).
355 #if defined(__aarch64__)
356   // Access type is encoded in BRK immediate as 0x900 + 0xXY. For Y == 0xF,
357   // access size is stored in X1 register. Access address is always in X0
358   // register.
359   uptr pc = (uptr)info->si_addr;
360   const unsigned code = ((*(u32 *)pc) >> 5) & 0xffff;
361   if ((code & 0xff00) != 0x900)
362     return AccessInfo{}; // Not ours.
363 
364   const bool is_store = code & 0x10;
365   const bool recover = code & 0x20;
366   const uptr addr = uc->uc_mcontext.regs[0];
367   const unsigned size_log = code & 0xf;
368   if (size_log > 4 && size_log != 0xf)
369     return AccessInfo{}; // Not ours.
370   const uptr size = size_log == 0xf ? uc->uc_mcontext.regs[1] : 1U << size_log;
371 
372 #elif defined(__x86_64__)
373   // Access type is encoded in the instruction following INT3 as
374   // NOP DWORD ptr [EAX + 0x40 + 0xXY]. For Y == 0xF, access size is stored in
375   // RSI register. Access address is always in RDI register.
376   uptr pc = (uptr)uc->uc_mcontext.gregs[REG_RIP];
377   uint8_t *nop = (uint8_t*)pc;
378   if (*nop != 0x0f || *(nop + 1) != 0x1f || *(nop + 2) != 0x40  ||
379       *(nop + 3) < 0x40)
380     return AccessInfo{}; // Not ours.
381   const unsigned code = *(nop + 3);
382 
383   const bool is_store = code & 0x10;
384   const bool recover = code & 0x20;
385   const uptr addr = uc->uc_mcontext.gregs[REG_RDI];
386   const unsigned size_log = code & 0xf;
387   if (size_log > 4 && size_log != 0xf)
388     return AccessInfo{}; // Not ours.
389   const uptr size =
390       size_log == 0xf ? uc->uc_mcontext.gregs[REG_RSI] : 1U << size_log;
391 
392 #else
393 # error Unsupported architecture
394 #endif
395 
396   return AccessInfo{addr, size, is_store, !is_store, recover};
397 }
398 
399 static void HandleTagMismatch(AccessInfo ai, uptr pc, uptr frame,
400                               ucontext_t *uc, uptr *registers_frame = nullptr) {
401   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
402   BufferedStackTrace *stack = stack_buffer.data();
403   stack->Reset();
404   stack->Unwind(pc, frame, uc, common_flags()->fast_unwind_on_fatal);
405 
406   // The second stack frame contains the failure __hwasan_check function, as
407   // we have a stack frame for the registers saved in __hwasan_tag_mismatch that
408   // we wish to ignore. This (currently) only occurs on AArch64, as x64
409   // implementations use SIGTRAP to implement the failure, and thus do not go
410   // through the stack saver.
411   if (registers_frame && stack->trace && stack->size > 0) {
412     stack->trace++;
413     stack->size--;
414   }
415 
416   bool fatal = flags()->halt_on_error || !ai.recover;
417   ReportTagMismatch(stack, ai.addr, ai.size, ai.is_store, fatal,
418                     registers_frame);
419 }
420 
421 static bool HwasanOnSIGTRAP(int signo, siginfo_t *info, ucontext_t *uc) {
422   AccessInfo ai = GetAccessInfo(info, uc);
423   if (!ai.is_store && !ai.is_load)
424     return false;
425 
426   SignalContext sig{info, uc};
427   HandleTagMismatch(ai, StackTrace::GetNextInstructionPc(sig.pc), sig.bp, uc);
428 
429 #if defined(__aarch64__)
430   uc->uc_mcontext.pc += 4;
431 #elif defined(__x86_64__)
432 #else
433 # error Unsupported architecture
434 #endif
435   return true;
436 }
437 
438 static void OnStackUnwind(const SignalContext &sig, const void *,
439                           BufferedStackTrace *stack) {
440   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
441                 common_flags()->fast_unwind_on_fatal);
442 }
443 
444 void HwasanOnDeadlySignal(int signo, void *info, void *context) {
445   // Probably a tag mismatch.
446   if (signo == SIGTRAP)
447     if (HwasanOnSIGTRAP(signo, (siginfo_t *)info, (ucontext_t*)context))
448       return;
449 
450   HandleDeadlySignal(info, context, GetTid(), &OnStackUnwind, nullptr);
451 }
452 
453 
454 } // namespace __hwasan
455 
456 // Entry point for interoperability between __hwasan_tag_mismatch (ASM) and the
457 // rest of the mismatch handling code (C++).
458 void __hwasan_tag_mismatch4(uptr addr, uptr access_info, uptr *registers_frame,
459                             size_t outsize) {
460   __hwasan::AccessInfo ai;
461   ai.is_store = access_info & 0x10;
462   ai.is_load = !ai.is_store;
463   ai.recover = access_info & 0x20;
464   ai.addr = addr;
465   if ((access_info & 0xf) == 0xf)
466     ai.size = outsize;
467   else
468     ai.size = 1 << (access_info & 0xf);
469 
470   __hwasan::HandleTagMismatch(ai, (uptr)__builtin_return_address(0),
471                               (uptr)__builtin_frame_address(0), nullptr,
472                               registers_frame);
473   __builtin_unreachable();
474 }
475 
476 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
477