1 //===-- hwasan.cpp --------------------------------------------------------===//
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 // This file is a part of HWAddressSanitizer.
10 //
11 // HWAddressSanitizer runtime.
12 //===----------------------------------------------------------------------===//
13 
14 #include "hwasan.h"
15 
16 #include "hwasan_checks.h"
17 #include "hwasan_dynamic_shadow.h"
18 #include "hwasan_globals.h"
19 #include "hwasan_poisoning.h"
20 #include "hwasan_report.h"
21 #include "hwasan_thread.h"
22 #include "hwasan_thread_list.h"
23 #include "sanitizer_common/sanitizer_atomic.h"
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "sanitizer_common/sanitizer_flag_parser.h"
26 #include "sanitizer_common/sanitizer_flags.h"
27 #include "sanitizer_common/sanitizer_libc.h"
28 #include "sanitizer_common/sanitizer_procmaps.h"
29 #include "sanitizer_common/sanitizer_stackdepot.h"
30 #include "sanitizer_common/sanitizer_stacktrace.h"
31 #include "sanitizer_common/sanitizer_symbolizer.h"
32 #include "ubsan/ubsan_flags.h"
33 #include "ubsan/ubsan_init.h"
34 
35 // ACHTUNG! No system header includes in this file.
36 
37 using namespace __sanitizer;
38 
39 namespace __hwasan {
40 
41 static Flags hwasan_flags;
42 
flags()43 Flags *flags() {
44   return &hwasan_flags;
45 }
46 
47 int hwasan_inited = 0;
48 int hwasan_instrumentation_inited = 0;
49 bool hwasan_init_is_running;
50 
51 int hwasan_report_count = 0;
52 
SetDefaults()53 void Flags::SetDefaults() {
54 #define HWASAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
55 #include "hwasan_flags.inc"
56 #undef HWASAN_FLAG
57 }
58 
RegisterHwasanFlags(FlagParser * parser,Flags * f)59 static void RegisterHwasanFlags(FlagParser *parser, Flags *f) {
60 #define HWASAN_FLAG(Type, Name, DefaultValue, Description) \
61   RegisterFlag(parser, #Name, Description, &f->Name);
62 #include "hwasan_flags.inc"
63 #undef HWASAN_FLAG
64 }
65 
InitializeFlags()66 static void InitializeFlags() {
67   SetCommonFlagsDefaults();
68   {
69     CommonFlags cf;
70     cf.CopyFrom(*common_flags());
71     cf.external_symbolizer_path = GetEnv("HWASAN_SYMBOLIZER_PATH");
72     cf.malloc_context_size = 20;
73     cf.handle_ioctl = true;
74     // FIXME: test and enable.
75     cf.check_printf = false;
76     cf.intercept_tls_get_addr = true;
77     cf.exitcode = 99;
78     // 8 shadow pages ~512kB, small enough to cover common stack sizes.
79     cf.clear_shadow_mmap_threshold = 4096 * (SANITIZER_ANDROID ? 2 : 8);
80     // Sigtrap is used in error reporting.
81     cf.handle_sigtrap = kHandleSignalExclusive;
82 
83 #if SANITIZER_ANDROID
84     // Let platform handle other signals. It is better at reporting them then we
85     // are.
86     cf.handle_segv = kHandleSignalNo;
87     cf.handle_sigbus = kHandleSignalNo;
88     cf.handle_abort = kHandleSignalNo;
89     cf.handle_sigill = kHandleSignalNo;
90     cf.handle_sigfpe = kHandleSignalNo;
91 #endif
92     OverrideCommonFlags(cf);
93   }
94 
95   Flags *f = flags();
96   f->SetDefaults();
97 
98   FlagParser parser;
99   RegisterHwasanFlags(&parser, f);
100   RegisterCommonFlags(&parser);
101 
102 #if HWASAN_CONTAINS_UBSAN
103   __ubsan::Flags *uf = __ubsan::flags();
104   uf->SetDefaults();
105 
106   FlagParser ubsan_parser;
107   __ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
108   RegisterCommonFlags(&ubsan_parser);
109 #endif
110 
111   // Override from user-specified string.
112   if (__hwasan_default_options)
113     parser.ParseString(__hwasan_default_options());
114 #if HWASAN_CONTAINS_UBSAN
115   const char *ubsan_default_options = __ubsan_default_options();
116   ubsan_parser.ParseString(ubsan_default_options);
117 #endif
118 
119   parser.ParseStringFromEnv("HWASAN_OPTIONS");
120 #if HWASAN_CONTAINS_UBSAN
121   ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
122 #endif
123 
124   InitializeCommonFlags();
125 
126   if (Verbosity()) ReportUnrecognizedFlags();
127 
128   if (common_flags()->help) parser.PrintFlagDescriptions();
129 }
130 
HWAsanCheckFailed(const char * file,int line,const char * cond,u64 v1,u64 v2)131 static void HWAsanCheckFailed(const char *file, int line, const char *cond,
132                               u64 v1, u64 v2) {
133   Report("HWAddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", file,
134          line, cond, (uptr)v1, (uptr)v2);
135   PRINT_CURRENT_STACK_CHECK();
136   Die();
137 }
138 
139 static constexpr uptr kMemoryUsageBufferSize = 4096;
140 
HwasanFormatMemoryUsage(InternalScopedString & s)141 static void HwasanFormatMemoryUsage(InternalScopedString &s) {
142   HwasanThreadList &thread_list = hwasanThreadList();
143   auto thread_stats = thread_list.GetThreadStats();
144   auto *sds = StackDepotGetStats();
145   AllocatorStatCounters asc;
146   GetAllocatorStats(asc);
147   s.append(
148       "HWASAN pid: %d rss: %zd threads: %zd stacks: %zd"
149       " thr_aux: %zd stack_depot: %zd uniq_stacks: %zd"
150       " heap: %zd",
151       internal_getpid(), GetRSS(), thread_stats.n_live_threads,
152       thread_stats.total_stack_size,
153       thread_stats.n_live_threads * thread_list.MemoryUsedPerThread(),
154       sds->allocated, sds->n_uniq_ids, asc[AllocatorStatMapped]);
155 }
156 
157 #if SANITIZER_ANDROID
158 static char *memory_usage_buffer = nullptr;
159 
InitMemoryUsage()160 static void InitMemoryUsage() {
161   memory_usage_buffer =
162       (char *)MmapOrDie(kMemoryUsageBufferSize, "memory usage string");
163   CHECK(memory_usage_buffer);
164   memory_usage_buffer[0] = '\0';
165   DecorateMapping((uptr)memory_usage_buffer, kMemoryUsageBufferSize,
166                   memory_usage_buffer);
167 }
168 
UpdateMemoryUsage()169 void UpdateMemoryUsage() {
170   if (!flags()->export_memory_stats)
171     return;
172   if (!memory_usage_buffer)
173     InitMemoryUsage();
174   InternalScopedString s(kMemoryUsageBufferSize);
175   HwasanFormatMemoryUsage(s);
176   internal_strncpy(memory_usage_buffer, s.data(), kMemoryUsageBufferSize - 1);
177   memory_usage_buffer[kMemoryUsageBufferSize - 1] = '\0';
178 }
179 #else
UpdateMemoryUsage()180 void UpdateMemoryUsage() {}
181 #endif
182 
183 } // namespace __hwasan
184 
185 using namespace __hwasan;
186 
UnwindImpl(uptr pc,uptr bp,void * context,bool request_fast,u32 max_depth)187 void __sanitizer::BufferedStackTrace::UnwindImpl(
188     uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
189   Thread *t = GetCurrentThread();
190   if (!t) {
191     // The thread is still being created, or has already been destroyed.
192     size = 0;
193     return;
194   }
195   Unwind(max_depth, pc, bp, context, t->stack_top(), t->stack_bottom(),
196          request_fast);
197 }
198 
InitializeSingleGlobal(const hwasan_global & global)199 static bool InitializeSingleGlobal(const hwasan_global &global) {
200   uptr full_granule_size = RoundDownTo(global.size(), 16);
201   TagMemoryAligned(global.addr(), full_granule_size, global.tag());
202   if (global.size() % 16)
203     TagMemoryAligned(global.addr() + full_granule_size, 16, global.size() % 16);
204   return false;
205 }
206 
InitLoadedGlobals()207 static void InitLoadedGlobals() {
208   dl_iterate_phdr(
209       [](dl_phdr_info *info, size_t /* size */, void * /* data */) -> int {
210         for (const hwasan_global &global : HwasanGlobalsFor(
211                  info->dlpi_addr, info->dlpi_phdr, info->dlpi_phnum))
212           InitializeSingleGlobal(global);
213         return 0;
214       },
215       nullptr);
216 }
217 
218 // Prepare to run instrumented code on the main thread.
InitInstrumentation()219 static void InitInstrumentation() {
220   if (hwasan_instrumentation_inited) return;
221 
222   InitPrctl();
223 
224   if (!InitShadow()) {
225     Printf("FATAL: HWAddressSanitizer cannot mmap the shadow memory.\n");
226     DumpProcessMap();
227     Die();
228   }
229 
230   InitThreads();
231   hwasanThreadList().CreateCurrentThread();
232 
233   hwasan_instrumentation_inited = 1;
234 }
235 
236 // Interface.
237 
238 uptr __hwasan_shadow_memory_dynamic_address;  // Global interface symbol.
239 
240 // This function was used by the old frame descriptor mechanism. We keep it
241 // around to avoid breaking ABI.
__hwasan_init_frames(uptr beg,uptr end)242 void __hwasan_init_frames(uptr beg, uptr end) {}
243 
__hwasan_init_static()244 void __hwasan_init_static() {
245   InitShadowGOT();
246   InitInstrumentation();
247 
248   // In the non-static code path we call dl_iterate_phdr here. But at this point
249   // libc might not have been initialized enough for dl_iterate_phdr to work.
250   // Fortunately, since this is a statically linked executable we can use the
251   // linker-defined symbol __ehdr_start to find the only relevant set of phdrs.
252   extern ElfW(Ehdr) __ehdr_start;
253   for (const hwasan_global &global : HwasanGlobalsFor(
254            /* base */ 0,
255            reinterpret_cast<const ElfW(Phdr) *>(
256                reinterpret_cast<const char *>(&__ehdr_start) +
257                __ehdr_start.e_phoff),
258            __ehdr_start.e_phnum))
259     InitializeSingleGlobal(global);
260 }
261 
__hwasan_init()262 void __hwasan_init() {
263   CHECK(!hwasan_init_is_running);
264   if (hwasan_inited) return;
265   hwasan_init_is_running = 1;
266   SanitizerToolName = "HWAddressSanitizer";
267 
268   InitTlsSize();
269 
270   CacheBinaryName();
271   InitializeFlags();
272 
273   // Install tool-specific callbacks in sanitizer_common.
274   SetCheckFailedCallback(HWAsanCheckFailed);
275 
276   __sanitizer_set_report_path(common_flags()->log_path);
277 
278   AndroidTestTlsSlot();
279 
280   DisableCoreDumperIfNecessary();
281 
282   InitInstrumentation();
283   InitLoadedGlobals();
284 
285   // Needs to be called here because flags()->random_tags might not have been
286   // initialized when InitInstrumentation() was called.
287   GetCurrentThread()->InitRandomState();
288 
289   SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
290   // This may call libc -> needs initialized shadow.
291   AndroidLogInit();
292 
293   InitializeInterceptors();
294   InstallDeadlySignalHandlers(HwasanOnDeadlySignal);
295   InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
296 
297   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
298 
299   HwasanTSDInit();
300   HwasanTSDThreadInit();
301 
302   HwasanAllocatorInit();
303 
304 #if HWASAN_CONTAINS_UBSAN
305   __ubsan::InitAsPlugin();
306 #endif
307 
308   VPrintf(1, "HWAddressSanitizer init done\n");
309 
310   hwasan_init_is_running = 0;
311   hwasan_inited = 1;
312 }
313 
__hwasan_library_loaded(ElfW (Addr)base,const ElfW (Phdr)* phdr,ElfW (Half)phnum)314 void __hwasan_library_loaded(ElfW(Addr) base, const ElfW(Phdr) * phdr,
315                              ElfW(Half) phnum) {
316   for (const hwasan_global &global : HwasanGlobalsFor(base, phdr, phnum))
317     InitializeSingleGlobal(global);
318 }
319 
__hwasan_library_unloaded(ElfW (Addr)base,const ElfW (Phdr)* phdr,ElfW (Half)phnum)320 void __hwasan_library_unloaded(ElfW(Addr) base, const ElfW(Phdr) * phdr,
321                                ElfW(Half) phnum) {
322   for (; phnum != 0; ++phdr, --phnum)
323     if (phdr->p_type == PT_LOAD)
324       TagMemory(base + phdr->p_vaddr, phdr->p_memsz, 0);
325 }
326 
__hwasan_print_shadow(const void * p,uptr sz)327 void __hwasan_print_shadow(const void *p, uptr sz) {
328   uptr ptr_raw = UntagAddr(reinterpret_cast<uptr>(p));
329   uptr shadow_first = MemToShadow(ptr_raw);
330   uptr shadow_last = MemToShadow(ptr_raw + sz - 1);
331   Printf("HWASan shadow map for %zx .. %zx (pointer tag %x)\n", ptr_raw,
332          ptr_raw + sz, GetTagFromPointer((uptr)p));
333   for (uptr s = shadow_first; s <= shadow_last; ++s)
334     Printf("  %zx: %x\n", ShadowToMem(s), *(tag_t *)s);
335 }
336 
__hwasan_test_shadow(const void * p,uptr sz)337 sptr __hwasan_test_shadow(const void *p, uptr sz) {
338   if (sz == 0)
339     return -1;
340   tag_t ptr_tag = GetTagFromPointer((uptr)p);
341   uptr ptr_raw = UntagAddr(reinterpret_cast<uptr>(p));
342   uptr shadow_first = MemToShadow(ptr_raw);
343   uptr shadow_last = MemToShadow(ptr_raw + sz - 1);
344   for (uptr s = shadow_first; s <= shadow_last; ++s)
345     if (*(tag_t *)s != ptr_tag) {
346       sptr offset = ShadowToMem(s) - ptr_raw;
347       return offset < 0 ? 0 : offset;
348     }
349   return -1;
350 }
351 
__sanitizer_unaligned_load16(const uu16 * p)352 u16 __sanitizer_unaligned_load16(const uu16 *p) {
353   return *p;
354 }
__sanitizer_unaligned_load32(const uu32 * p)355 u32 __sanitizer_unaligned_load32(const uu32 *p) {
356   return *p;
357 }
__sanitizer_unaligned_load64(const uu64 * p)358 u64 __sanitizer_unaligned_load64(const uu64 *p) {
359   return *p;
360 }
__sanitizer_unaligned_store16(uu16 * p,u16 x)361 void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
362   *p = x;
363 }
__sanitizer_unaligned_store32(uu32 * p,u32 x)364 void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
365   *p = x;
366 }
__sanitizer_unaligned_store64(uu64 * p,u64 x)367 void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
368   *p = x;
369 }
370 
__hwasan_loadN(uptr p,uptr sz)371 void __hwasan_loadN(uptr p, uptr sz) {
372   CheckAddressSized<ErrorAction::Abort, AccessType::Load>(p, sz);
373 }
__hwasan_load1(uptr p)374 void __hwasan_load1(uptr p) {
375   CheckAddress<ErrorAction::Abort, AccessType::Load, 0>(p);
376 }
__hwasan_load2(uptr p)377 void __hwasan_load2(uptr p) {
378   CheckAddress<ErrorAction::Abort, AccessType::Load, 1>(p);
379 }
__hwasan_load4(uptr p)380 void __hwasan_load4(uptr p) {
381   CheckAddress<ErrorAction::Abort, AccessType::Load, 2>(p);
382 }
__hwasan_load8(uptr p)383 void __hwasan_load8(uptr p) {
384   CheckAddress<ErrorAction::Abort, AccessType::Load, 3>(p);
385 }
__hwasan_load16(uptr p)386 void __hwasan_load16(uptr p) {
387   CheckAddress<ErrorAction::Abort, AccessType::Load, 4>(p);
388 }
389 
__hwasan_loadN_noabort(uptr p,uptr sz)390 void __hwasan_loadN_noabort(uptr p, uptr sz) {
391   CheckAddressSized<ErrorAction::Recover, AccessType::Load>(p, sz);
392 }
__hwasan_load1_noabort(uptr p)393 void __hwasan_load1_noabort(uptr p) {
394   CheckAddress<ErrorAction::Recover, AccessType::Load, 0>(p);
395 }
__hwasan_load2_noabort(uptr p)396 void __hwasan_load2_noabort(uptr p) {
397   CheckAddress<ErrorAction::Recover, AccessType::Load, 1>(p);
398 }
__hwasan_load4_noabort(uptr p)399 void __hwasan_load4_noabort(uptr p) {
400   CheckAddress<ErrorAction::Recover, AccessType::Load, 2>(p);
401 }
__hwasan_load8_noabort(uptr p)402 void __hwasan_load8_noabort(uptr p) {
403   CheckAddress<ErrorAction::Recover, AccessType::Load, 3>(p);
404 }
__hwasan_load16_noabort(uptr p)405 void __hwasan_load16_noabort(uptr p) {
406   CheckAddress<ErrorAction::Recover, AccessType::Load, 4>(p);
407 }
408 
__hwasan_storeN(uptr p,uptr sz)409 void __hwasan_storeN(uptr p, uptr sz) {
410   CheckAddressSized<ErrorAction::Abort, AccessType::Store>(p, sz);
411 }
__hwasan_store1(uptr p)412 void __hwasan_store1(uptr p) {
413   CheckAddress<ErrorAction::Abort, AccessType::Store, 0>(p);
414 }
__hwasan_store2(uptr p)415 void __hwasan_store2(uptr p) {
416   CheckAddress<ErrorAction::Abort, AccessType::Store, 1>(p);
417 }
__hwasan_store4(uptr p)418 void __hwasan_store4(uptr p) {
419   CheckAddress<ErrorAction::Abort, AccessType::Store, 2>(p);
420 }
__hwasan_store8(uptr p)421 void __hwasan_store8(uptr p) {
422   CheckAddress<ErrorAction::Abort, AccessType::Store, 3>(p);
423 }
__hwasan_store16(uptr p)424 void __hwasan_store16(uptr p) {
425   CheckAddress<ErrorAction::Abort, AccessType::Store, 4>(p);
426 }
427 
__hwasan_storeN_noabort(uptr p,uptr sz)428 void __hwasan_storeN_noabort(uptr p, uptr sz) {
429   CheckAddressSized<ErrorAction::Recover, AccessType::Store>(p, sz);
430 }
__hwasan_store1_noabort(uptr p)431 void __hwasan_store1_noabort(uptr p) {
432   CheckAddress<ErrorAction::Recover, AccessType::Store, 0>(p);
433 }
__hwasan_store2_noabort(uptr p)434 void __hwasan_store2_noabort(uptr p) {
435   CheckAddress<ErrorAction::Recover, AccessType::Store, 1>(p);
436 }
__hwasan_store4_noabort(uptr p)437 void __hwasan_store4_noabort(uptr p) {
438   CheckAddress<ErrorAction::Recover, AccessType::Store, 2>(p);
439 }
__hwasan_store8_noabort(uptr p)440 void __hwasan_store8_noabort(uptr p) {
441   CheckAddress<ErrorAction::Recover, AccessType::Store, 3>(p);
442 }
__hwasan_store16_noabort(uptr p)443 void __hwasan_store16_noabort(uptr p) {
444   CheckAddress<ErrorAction::Recover, AccessType::Store, 4>(p);
445 }
446 
__hwasan_tag_memory(uptr p,u8 tag,uptr sz)447 void __hwasan_tag_memory(uptr p, u8 tag, uptr sz) {
448   TagMemoryAligned(p, sz, tag);
449 }
450 
__hwasan_tag_pointer(uptr p,u8 tag)451 uptr __hwasan_tag_pointer(uptr p, u8 tag) {
452   return AddTagToPointer(p, tag);
453 }
454 
__hwasan_handle_longjmp(const void * sp_dst)455 void __hwasan_handle_longjmp(const void *sp_dst) {
456   uptr dst = (uptr)sp_dst;
457   // HWASan does not support tagged SP.
458   CHECK(GetTagFromPointer(dst) == 0);
459 
460   uptr sp = (uptr)__builtin_frame_address(0);
461   static const uptr kMaxExpectedCleanupSize = 64 << 20;  // 64M
462   if (dst < sp || dst - sp > kMaxExpectedCleanupSize) {
463     Report(
464         "WARNING: HWASan is ignoring requested __hwasan_handle_longjmp: "
465         "stack top: %p; target %p; distance: %p (%zd)\n"
466         "False positive error reports may follow\n",
467         (void *)sp, (void *)dst, dst - sp);
468     return;
469   }
470   TagMemory(sp, dst - sp, 0);
471 }
472 
__hwasan_handle_vfork(const void * sp_dst)473 void __hwasan_handle_vfork(const void *sp_dst) {
474   uptr sp = (uptr)sp_dst;
475   Thread *t = GetCurrentThread();
476   CHECK(t);
477   uptr top = t->stack_top();
478   uptr bottom = t->stack_bottom();
479   if (top == 0 || bottom == 0 || sp < bottom || sp >= top) {
480     Report(
481         "WARNING: HWASan is ignoring requested __hwasan_handle_vfork: "
482         "stack top: %zx; current %zx; bottom: %zx \n"
483         "False positive error reports may follow\n",
484         top, sp, bottom);
485     return;
486   }
487   TagMemory(bottom, sp - bottom, 0);
488 }
489 
__hwasan_extra_spill_area()490 extern "C" void *__hwasan_extra_spill_area() {
491   Thread *t = GetCurrentThread();
492   return &t->vfork_spill();
493 }
494 
__hwasan_print_memory_usage()495 void __hwasan_print_memory_usage() {
496   InternalScopedString s(kMemoryUsageBufferSize);
497   HwasanFormatMemoryUsage(s);
498   Printf("%s\n", s.data());
499 }
500 
501 static const u8 kFallbackTag = 0xBB;
502 
__hwasan_generate_tag()503 u8 __hwasan_generate_tag() {
504   Thread *t = GetCurrentThread();
505   if (!t) return kFallbackTag;
506   return t->GenerateRandomTag();
507 }
508 
509 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
510 extern "C" {
511 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
__hwasan_default_options()512 const char* __hwasan_default_options() { return ""; }
513 }  // extern "C"
514 #endif
515 
516 extern "C" {
517 SANITIZER_INTERFACE_ATTRIBUTE
__sanitizer_print_stack_trace()518 void __sanitizer_print_stack_trace() {
519   GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
520   stack.Print();
521 }
522 } // extern "C"
523