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 when aliases aren't used.
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(HWASAN_ALIASING_MODE)
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 #  if defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE)
150     // Try the new prctl API for Intel LAM.  The API is based on a currently
151     // unsubmitted patch to the Linux kernel (as of May 2021) and is thus
152     // subject to change.  Patch is here:
153     // https://lore.kernel.org/linux-mm/[email protected]/
154     int tag_bits = kTagBits;
155     int tag_shift = kAddressTagShift;
156     if (!internal_iserror(
157             internal_prctl(PR_SET_TAGGED_ADDR_CTRL, PR_TAGGED_ADDR_ENABLE,
158                            reinterpret_cast<unsigned long>(&tag_bits),
159                            reinterpret_cast<unsigned long>(&tag_shift), 0))) {
160       CHECK_EQ(tag_bits, kTagBits);
161       CHECK_EQ(tag_shift, kAddressTagShift);
162       return;
163     }
164 #  endif  // defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE)
165     if (flags()->fail_without_syscall_abi) {
166       Printf(
167           "FATAL: HWAddressSanitizer failed to enable tagged address syscall "
168           "ABI.\nSuggest check `sysctl abi.tagged_addr_disabled` "
169           "configuration.\n");
170       Die();
171     }
172   }
173 #undef PR_SET_TAGGED_ADDR_CTRL
174 #undef PR_GET_TAGGED_ADDR_CTRL
175 #undef PR_TAGGED_ADDR_ENABLE
176 }
177 
178 bool InitShadow() {
179   // Define the entire memory range.
180   kHighMemEnd = GetHighMemEnd();
181 
182   // Determine shadow memory base offset.
183   InitializeShadowBaseAddress(MemToShadowSize(kHighMemEnd));
184 
185   // Place the low memory first.
186   kLowMemEnd = __hwasan_shadow_memory_dynamic_address - 1;
187   kLowMemStart = 0;
188 
189   // Define the low shadow based on the already placed low memory.
190   kLowShadowEnd = MemToShadow(kLowMemEnd);
191   kLowShadowStart = __hwasan_shadow_memory_dynamic_address;
192 
193   // High shadow takes whatever memory is left up there (making sure it is not
194   // interfering with low memory in the fixed case).
195   kHighShadowEnd = MemToShadow(kHighMemEnd);
196   kHighShadowStart = Max(kLowMemEnd, MemToShadow(kHighShadowEnd)) + 1;
197 
198   // High memory starts where allocated shadow allows.
199   kHighMemStart = ShadowToMem(kHighShadowStart);
200 
201 #  if defined(HWASAN_ALIASING_MODE)
202   constexpr uptr kAliasRegionOffset = 1ULL << (kTaggableRegionCheckShift - 1);
203   kAliasRegionStart =
204       __hwasan_shadow_memory_dynamic_address + kAliasRegionOffset;
205 
206   CHECK_EQ(kAliasRegionStart >> kTaggableRegionCheckShift,
207            __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
208   CHECK_EQ(
209       (kAliasRegionStart + kAliasRegionOffset - 1) >> kTaggableRegionCheckShift,
210       __hwasan_shadow_memory_dynamic_address >> kTaggableRegionCheckShift);
211 #  endif
212 
213   // Check the sanity of the defined memory ranges (there might be gaps).
214   CHECK_EQ(kHighMemStart % GetMmapGranularity(), 0);
215   CHECK_GT(kHighMemStart, kHighShadowEnd);
216   CHECK_GT(kHighShadowEnd, kHighShadowStart);
217   CHECK_GT(kHighShadowStart, kLowMemEnd);
218   CHECK_GT(kLowMemEnd, kLowMemStart);
219   CHECK_GT(kLowShadowEnd, kLowShadowStart);
220   CHECK_GT(kLowShadowStart, kLowMemEnd);
221 
222   if (Verbosity())
223     PrintAddressSpaceLayout();
224 
225   // Reserve shadow memory.
226   ReserveShadowMemoryRange(kLowShadowStart, kLowShadowEnd, "low shadow");
227   ReserveShadowMemoryRange(kHighShadowStart, kHighShadowEnd, "high shadow");
228 
229   // Protect all the gaps.
230   ProtectGap(0, Min(kLowMemStart, kLowShadowStart));
231   if (kLowMemEnd + 1 < kLowShadowStart)
232     ProtectGap(kLowMemEnd + 1, kLowShadowStart - kLowMemEnd - 1);
233   if (kLowShadowEnd + 1 < kHighShadowStart)
234     ProtectGap(kLowShadowEnd + 1, kHighShadowStart - kLowShadowEnd - 1);
235   if (kHighShadowEnd + 1 < kHighMemStart)
236     ProtectGap(kHighShadowEnd + 1, kHighMemStart - kHighShadowEnd - 1);
237 
238   return true;
239 }
240 
241 void InitThreads() {
242   CHECK(__hwasan_shadow_memory_dynamic_address);
243   uptr guard_page_size = GetMmapGranularity();
244   uptr thread_space_start =
245       __hwasan_shadow_memory_dynamic_address - (1ULL << kShadowBaseAlignment);
246   uptr thread_space_end =
247       __hwasan_shadow_memory_dynamic_address - guard_page_size;
248   ReserveShadowMemoryRange(thread_space_start, thread_space_end - 1,
249                            "hwasan threads", /*madvise_shadow*/ false);
250   ProtectGap(thread_space_end,
251              __hwasan_shadow_memory_dynamic_address - thread_space_end);
252   InitThreadList(thread_space_start, thread_space_end - thread_space_start);
253 }
254 
255 bool MemIsApp(uptr p) {
256 // Memory outside the alias range has non-zero tags.
257 #  if !defined(HWASAN_ALIASING_MODE)
258   CHECK(GetTagFromPointer(p) == 0);
259 #  endif
260 
261   return p >= kHighMemStart || (p >= kLowMemStart && p <= kLowMemEnd);
262 }
263 
264 static void HwasanAtExit(void) {
265   if (common_flags()->print_module_map)
266     DumpProcessMap();
267   if (flags()->print_stats && (flags()->atexit || hwasan_report_count > 0))
268     ReportStats();
269   if (hwasan_report_count > 0) {
270     // ReportAtExitStatistics();
271     if (common_flags()->exitcode)
272       internal__exit(common_flags()->exitcode);
273   }
274 }
275 
276 void InstallAtExitHandler() {
277   atexit(HwasanAtExit);
278 }
279 
280 // ---------------------- TSD ---------------- {{{1
281 
282 extern "C" void __hwasan_thread_enter() {
283   hwasanThreadList().CreateCurrentThread()->InitRandomState();
284 }
285 
286 extern "C" void __hwasan_thread_exit() {
287   Thread *t = GetCurrentThread();
288   // Make sure that signal handler can not see a stale current thread pointer.
289   atomic_signal_fence(memory_order_seq_cst);
290   if (t)
291     hwasanThreadList().ReleaseThread(t);
292 }
293 
294 #if HWASAN_WITH_INTERCEPTORS
295 static pthread_key_t tsd_key;
296 static bool tsd_key_inited = false;
297 
298 void HwasanTSDThreadInit() {
299   if (tsd_key_inited)
300     CHECK_EQ(0, pthread_setspecific(tsd_key,
301                                     (void *)GetPthreadDestructorIterations()));
302 }
303 
304 void HwasanTSDDtor(void *tsd) {
305   uptr iterations = (uptr)tsd;
306   if (iterations > 1) {
307     CHECK_EQ(0, pthread_setspecific(tsd_key, (void *)(iterations - 1)));
308     return;
309   }
310   __hwasan_thread_exit();
311 }
312 
313 void HwasanTSDInit() {
314   CHECK(!tsd_key_inited);
315   tsd_key_inited = true;
316   CHECK_EQ(0, pthread_key_create(&tsd_key, HwasanTSDDtor));
317 }
318 #else
319 void HwasanTSDInit() {}
320 void HwasanTSDThreadInit() {}
321 #endif
322 
323 #if SANITIZER_ANDROID
324 uptr *GetCurrentThreadLongPtr() {
325   return (uptr *)get_android_tls_ptr();
326 }
327 #else
328 uptr *GetCurrentThreadLongPtr() {
329   return &__hwasan_tls;
330 }
331 #endif
332 
333 #if SANITIZER_ANDROID
334 void AndroidTestTlsSlot() {
335   uptr kMagicValue = 0x010203040A0B0C0D;
336   uptr *tls_ptr = GetCurrentThreadLongPtr();
337   uptr old_value = *tls_ptr;
338   *tls_ptr = kMagicValue;
339   dlerror();
340   if (*(uptr *)get_android_tls_ptr() != kMagicValue) {
341     Printf(
342         "ERROR: Incompatible version of Android: TLS_SLOT_SANITIZER(6) is used "
343         "for dlerror().\n");
344     Die();
345   }
346   *tls_ptr = old_value;
347 }
348 #else
349 void AndroidTestTlsSlot() {}
350 #endif
351 
352 Thread *GetCurrentThread() {
353   uptr *ThreadLongPtr = GetCurrentThreadLongPtr();
354   if (UNLIKELY(*ThreadLongPtr == 0))
355     return nullptr;
356   auto *R = (StackAllocationsRingBuffer *)ThreadLongPtr;
357   return hwasanThreadList().GetThreadByBufferAddress((uptr)R->Next());
358 }
359 
360 struct AccessInfo {
361   uptr addr;
362   uptr size;
363   bool is_store;
364   bool is_load;
365   bool recover;
366 };
367 
368 static AccessInfo GetAccessInfo(siginfo_t *info, ucontext_t *uc) {
369   // Access type is passed in a platform dependent way (see below) and encoded
370   // as 0xXY, where X&1 is 1 for store, 0 for load, and X&2 is 1 if the error is
371   // recoverable. Valid values of Y are 0 to 4, which are interpreted as
372   // log2(access_size), and 0xF, which means that access size is passed via
373   // platform dependent register (see below).
374 #if defined(__aarch64__)
375   // Access type is encoded in BRK immediate as 0x900 + 0xXY. For Y == 0xF,
376   // access size is stored in X1 register. Access address is always in X0
377   // register.
378   uptr pc = (uptr)info->si_addr;
379   const unsigned code = ((*(u32 *)pc) >> 5) & 0xffff;
380   if ((code & 0xff00) != 0x900)
381     return AccessInfo{}; // Not ours.
382 
383   const bool is_store = code & 0x10;
384   const bool recover = code & 0x20;
385   const uptr addr = uc->uc_mcontext.regs[0];
386   const unsigned size_log = code & 0xf;
387   if (size_log > 4 && size_log != 0xf)
388     return AccessInfo{}; // Not ours.
389   const uptr size = size_log == 0xf ? uc->uc_mcontext.regs[1] : 1U << size_log;
390 
391 #elif defined(__x86_64__)
392   // Access type is encoded in the instruction following INT3 as
393   // NOP DWORD ptr [EAX + 0x40 + 0xXY]. For Y == 0xF, access size is stored in
394   // RSI register. Access address is always in RDI register.
395   uptr pc = (uptr)uc->uc_mcontext.gregs[REG_RIP];
396   uint8_t *nop = (uint8_t*)pc;
397   if (*nop != 0x0f || *(nop + 1) != 0x1f || *(nop + 2) != 0x40  ||
398       *(nop + 3) < 0x40)
399     return AccessInfo{}; // Not ours.
400   const unsigned code = *(nop + 3);
401 
402   const bool is_store = code & 0x10;
403   const bool recover = code & 0x20;
404   const uptr addr = uc->uc_mcontext.gregs[REG_RDI];
405   const unsigned size_log = code & 0xf;
406   if (size_log > 4 && size_log != 0xf)
407     return AccessInfo{}; // Not ours.
408   const uptr size =
409       size_log == 0xf ? uc->uc_mcontext.gregs[REG_RSI] : 1U << size_log;
410 
411 #else
412 # error Unsupported architecture
413 #endif
414 
415   return AccessInfo{addr, size, is_store, !is_store, recover};
416 }
417 
418 static void HandleTagMismatch(AccessInfo ai, uptr pc, uptr frame,
419                               ucontext_t *uc, uptr *registers_frame = nullptr) {
420   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
421   BufferedStackTrace *stack = stack_buffer.data();
422   stack->Reset();
423   stack->Unwind(pc, frame, uc, common_flags()->fast_unwind_on_fatal);
424 
425   // The second stack frame contains the failure __hwasan_check function, as
426   // we have a stack frame for the registers saved in __hwasan_tag_mismatch that
427   // we wish to ignore. This (currently) only occurs on AArch64, as x64
428   // implementations use SIGTRAP to implement the failure, and thus do not go
429   // through the stack saver.
430   if (registers_frame && stack->trace && stack->size > 0) {
431     stack->trace++;
432     stack->size--;
433   }
434 
435   bool fatal = flags()->halt_on_error || !ai.recover;
436   ReportTagMismatch(stack, ai.addr, ai.size, ai.is_store, fatal,
437                     registers_frame);
438 }
439 
440 static bool HwasanOnSIGTRAP(int signo, siginfo_t *info, ucontext_t *uc) {
441   AccessInfo ai = GetAccessInfo(info, uc);
442   if (!ai.is_store && !ai.is_load)
443     return false;
444 
445   SignalContext sig{info, uc};
446   HandleTagMismatch(ai, StackTrace::GetNextInstructionPc(sig.pc), sig.bp, uc);
447 
448 #if defined(__aarch64__)
449   uc->uc_mcontext.pc += 4;
450 #elif defined(__x86_64__)
451 #else
452 # error Unsupported architecture
453 #endif
454   return true;
455 }
456 
457 static void OnStackUnwind(const SignalContext &sig, const void *,
458                           BufferedStackTrace *stack) {
459   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
460                 common_flags()->fast_unwind_on_fatal);
461 }
462 
463 void HwasanOnDeadlySignal(int signo, void *info, void *context) {
464   // Probably a tag mismatch.
465   if (signo == SIGTRAP)
466     if (HwasanOnSIGTRAP(signo, (siginfo_t *)info, (ucontext_t*)context))
467       return;
468 
469   HandleDeadlySignal(info, context, GetTid(), &OnStackUnwind, nullptr);
470 }
471 
472 
473 } // namespace __hwasan
474 
475 // Entry point for interoperability between __hwasan_tag_mismatch (ASM) and the
476 // rest of the mismatch handling code (C++).
477 void __hwasan_tag_mismatch4(uptr addr, uptr access_info, uptr *registers_frame,
478                             size_t outsize) {
479   __hwasan::AccessInfo ai;
480   ai.is_store = access_info & 0x10;
481   ai.is_load = !ai.is_store;
482   ai.recover = access_info & 0x20;
483   ai.addr = addr;
484   if ((access_info & 0xf) == 0xf)
485     ai.size = outsize;
486   else
487     ai.size = 1 << (access_info & 0xf);
488 
489   __hwasan::HandleTagMismatch(ai, (uptr)__builtin_return_address(0),
490                               (uptr)__builtin_frame_address(0), nullptr,
491                               registers_frame);
492   __builtin_unreachable();
493 }
494 
495 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
496