1 //===-- hwasan.cpp --------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file is a part of HWAddressSanitizer.
11 // HWAddressSanitizer runtime.
12 //===----------------------------------------------------------------------===//
16 #include "hwasan_checks.h"
17 #include "hwasan_dynamic_shadow.h"
18 #include "hwasan_globals.h"
19 #include "hwasan_mapping.h"
20 #include "hwasan_poisoning.h"
21 #include "hwasan_report.h"
22 #include "hwasan_thread.h"
23 #include "hwasan_thread_list.h"
24 #include "sanitizer_common/sanitizer_atomic.h"
25 #include "sanitizer_common/sanitizer_common.h"
26 #include "sanitizer_common/sanitizer_flag_parser.h"
27 #include "sanitizer_common/sanitizer_flags.h"
28 #include "sanitizer_common/sanitizer_interface_internal.h"
29 #include "sanitizer_common/sanitizer_libc.h"
30 #include "sanitizer_common/sanitizer_procmaps.h"
31 #include "sanitizer_common/sanitizer_stackdepot.h"
32 #include "sanitizer_common/sanitizer_stacktrace.h"
33 #include "sanitizer_common/sanitizer_symbolizer.h"
34 #include "ubsan/ubsan_flags.h"
35 #include "ubsan/ubsan_init.h"
37 // ACHTUNG! No system header includes in this file.
39 using namespace __sanitizer
;
43 static Flags hwasan_flags
;
49 int hwasan_inited
= 0;
50 int hwasan_instrumentation_inited
= 0;
51 bool hwasan_init_is_running
;
53 int hwasan_report_count
= 0;
57 uptr kHighShadowStart
;
60 void Flags::SetDefaults() {
61 #define HWASAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
62 #include "hwasan_flags.inc"
66 static void RegisterHwasanFlags(FlagParser
*parser
, Flags
*f
) {
67 #define HWASAN_FLAG(Type, Name, DefaultValue, Description) \
68 RegisterFlag(parser, #Name, Description, &f->Name);
69 #include "hwasan_flags.inc"
73 static void InitializeFlags() {
74 SetCommonFlagsDefaults();
77 cf
.CopyFrom(*common_flags());
78 cf
.external_symbolizer_path
= GetEnv("HWASAN_SYMBOLIZER_PATH");
79 cf
.malloc_context_size
= 20;
80 cf
.handle_ioctl
= true;
81 // FIXME: test and enable.
82 cf
.check_printf
= false;
83 cf
.intercept_tls_get_addr
= true;
85 // 8 shadow pages ~512kB, small enough to cover common stack sizes.
86 cf
.clear_shadow_mmap_threshold
= 4096 * (SANITIZER_ANDROID
? 2 : 8);
87 // Sigtrap is used in error reporting.
88 cf
.handle_sigtrap
= kHandleSignalExclusive
;
89 // FIXME: enable once all false positives have been fixed.
90 cf
.detect_leaks
= false;
93 // Let platform handle other signals. It is better at reporting them then we
95 cf
.handle_segv
= kHandleSignalNo
;
96 cf
.handle_sigbus
= kHandleSignalNo
;
97 cf
.handle_abort
= kHandleSignalNo
;
98 cf
.handle_sigill
= kHandleSignalNo
;
99 cf
.handle_sigfpe
= kHandleSignalNo
;
101 OverrideCommonFlags(cf
);
108 RegisterHwasanFlags(&parser
, f
);
109 RegisterCommonFlags(&parser
);
111 #if CAN_SANITIZE_LEAKS
112 __lsan::Flags
*lf
= __lsan::flags();
115 FlagParser lsan_parser
;
116 __lsan::RegisterLsanFlags(&lsan_parser
, lf
);
117 RegisterCommonFlags(&lsan_parser
);
120 #if HWASAN_CONTAINS_UBSAN
121 __ubsan::Flags
*uf
= __ubsan::flags();
124 FlagParser ubsan_parser
;
125 __ubsan::RegisterUbsanFlags(&ubsan_parser
, uf
);
126 RegisterCommonFlags(&ubsan_parser
);
129 // Override from user-specified string.
130 if (__hwasan_default_options
)
131 parser
.ParseString(__hwasan_default_options());
132 #if CAN_SANITIZE_LEAKS
133 lsan_parser
.ParseString(__lsan_default_options());
135 #if HWASAN_CONTAINS_UBSAN
136 const char *ubsan_default_options
= __ubsan_default_options();
137 ubsan_parser
.ParseString(ubsan_default_options
);
140 parser
.ParseStringFromEnv("HWASAN_OPTIONS");
141 #if CAN_SANITIZE_LEAKS
142 lsan_parser
.ParseStringFromEnv("LSAN_OPTIONS");
144 #if HWASAN_CONTAINS_UBSAN
145 ubsan_parser
.ParseStringFromEnv("UBSAN_OPTIONS");
148 InitializeCommonFlags();
150 if (Verbosity()) ReportUnrecognizedFlags();
152 if (common_flags()->help
) parser
.PrintFlagDescriptions();
154 if (!CAN_SANITIZE_LEAKS
&& common_flags()->detect_leaks
) {
155 Report("%s: detect_leaks is not supported on this platform.\n",
161 static void CheckUnwind() {
162 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
166 static void HwasanFormatMemoryUsage(InternalScopedString
&s
) {
167 HwasanThreadList
&thread_list
= hwasanThreadList();
168 auto thread_stats
= thread_list
.GetThreadStats();
169 auto sds
= StackDepotGetStats();
170 AllocatorStatCounters asc
;
171 GetAllocatorStats(asc
);
173 "HWASAN pid: %d rss: %zd threads: %zd stacks: %zd"
174 " thr_aux: %zd stack_depot: %zd uniq_stacks: %zd"
176 internal_getpid(), GetRSS(), thread_stats
.n_live_threads
,
177 thread_stats
.total_stack_size
,
178 thread_stats
.n_live_threads
* thread_list
.MemoryUsedPerThread(),
179 sds
.allocated
, sds
.n_uniq_ids
, asc
[AllocatorStatMapped
]);
182 #if SANITIZER_ANDROID
183 static constexpr uptr kMemoryUsageBufferSize
= 4096;
185 static char *memory_usage_buffer
= nullptr;
187 static void InitMemoryUsage() {
188 memory_usage_buffer
=
189 (char *)MmapOrDie(kMemoryUsageBufferSize
, "memory usage string");
190 CHECK(memory_usage_buffer
);
191 memory_usage_buffer
[0] = '\0';
192 DecorateMapping((uptr
)memory_usage_buffer
, kMemoryUsageBufferSize
,
193 memory_usage_buffer
);
196 void UpdateMemoryUsage() {
197 if (!flags()->export_memory_stats
)
199 if (!memory_usage_buffer
)
201 InternalScopedString s
;
202 HwasanFormatMemoryUsage(s
);
203 internal_strncpy(memory_usage_buffer
, s
.data(), kMemoryUsageBufferSize
- 1);
204 memory_usage_buffer
[kMemoryUsageBufferSize
- 1] = '\0';
207 void UpdateMemoryUsage() {}
210 void HwasanAtExit() {
211 if (common_flags()->print_module_map
)
213 if (flags()->print_stats
&& (flags()->atexit
|| hwasan_report_count
> 0))
215 if (hwasan_report_count
> 0) {
216 // ReportAtExitStatistics();
217 if (common_flags()->exitcode
)
218 internal__exit(common_flags()->exitcode
);
222 void HandleTagMismatch(AccessInfo ai
, uptr pc
, uptr frame
, void *uc
,
223 uptr
*registers_frame
) {
224 InternalMmapVector
<BufferedStackTrace
> stack_buffer(1);
225 BufferedStackTrace
*stack
= stack_buffer
.data();
227 stack
->Unwind(pc
, frame
, uc
, common_flags()->fast_unwind_on_fatal
);
229 // The second stack frame contains the failure __hwasan_check function, as
230 // we have a stack frame for the registers saved in __hwasan_tag_mismatch that
231 // we wish to ignore. This (currently) only occurs on AArch64, as x64
232 // implementations use SIGTRAP to implement the failure, and thus do not go
233 // through the stack saver.
234 if (registers_frame
&& stack
->trace
&& stack
->size
> 0) {
239 bool fatal
= flags()->halt_on_error
|| !ai
.recover
;
240 ReportTagMismatch(stack
, ai
.addr
, ai
.size
, ai
.is_store
, fatal
,
244 void HwasanTagMismatch(uptr addr
, uptr pc
, uptr frame
, uptr access_info
,
245 uptr
*registers_frame
, size_t outsize
) {
246 __hwasan::AccessInfo ai
;
247 ai
.is_store
= access_info
& 0x10;
248 ai
.is_load
= !ai
.is_store
;
249 ai
.recover
= access_info
& 0x20;
251 if ((access_info
& 0xf) == 0xf)
254 ai
.size
= 1 << (access_info
& 0xf);
256 HandleTagMismatch(ai
, pc
, frame
, nullptr, registers_frame
);
259 Thread
*GetCurrentThread() {
260 uptr
*ThreadLongPtr
= GetCurrentThreadLongPtr();
261 if (UNLIKELY(*ThreadLongPtr
== 0))
263 auto *R
= (StackAllocationsRingBuffer
*)ThreadLongPtr
;
264 return hwasanThreadList().GetThreadByBufferAddress((uptr
)R
->Next());
267 } // namespace __hwasan
269 using namespace __hwasan
;
271 void __sanitizer::BufferedStackTrace::UnwindImpl(
272 uptr pc
, uptr bp
, void *context
, bool request_fast
, u32 max_depth
) {
273 Thread
*t
= GetCurrentThread();
275 // The thread is still being created, or has already been destroyed.
279 Unwind(max_depth
, pc
, bp
, context
, t
->stack_top(), t
->stack_bottom(),
283 static bool InitializeSingleGlobal(const hwasan_global
&global
) {
284 uptr full_granule_size
= RoundDownTo(global
.size(), 16);
285 TagMemoryAligned(global
.addr(), full_granule_size
, global
.tag());
286 if (global
.size() % 16)
287 TagMemoryAligned(global
.addr() + full_granule_size
, 16, global
.size() % 16);
291 static void InitLoadedGlobals() {
293 [](dl_phdr_info
*info
, size_t /* size */, void * /* data */) -> int {
294 for (const hwasan_global
&global
: HwasanGlobalsFor(
295 info
->dlpi_addr
, info
->dlpi_phdr
, info
->dlpi_phnum
))
296 InitializeSingleGlobal(global
);
302 // Prepare to run instrumented code on the main thread.
303 static void InitInstrumentation() {
304 if (hwasan_instrumentation_inited
) return;
306 InitializeOsSupport();
309 Printf("FATAL: HWAddressSanitizer cannot mmap the shadow memory.\n");
316 hwasan_instrumentation_inited
= 1;
321 uptr __hwasan_shadow_memory_dynamic_address
; // Global interface symbol.
323 // This function was used by the old frame descriptor mechanism. We keep it
324 // around to avoid breaking ABI.
325 void __hwasan_init_frames(uptr beg
, uptr end
) {}
327 void __hwasan_init_static() {
329 InitInstrumentation();
331 // In the non-static code path we call dl_iterate_phdr here. But at this point
332 // libc might not have been initialized enough for dl_iterate_phdr to work.
333 // Fortunately, since this is a statically linked executable we can use the
334 // linker-defined symbol __ehdr_start to find the only relevant set of phdrs.
335 extern ElfW(Ehdr
) __ehdr_start
;
336 for (const hwasan_global
&global
: HwasanGlobalsFor(
338 reinterpret_cast<const ElfW(Phdr
) *>(
339 reinterpret_cast<const char *>(&__ehdr_start
) +
340 __ehdr_start
.e_phoff
),
341 __ehdr_start
.e_phnum
))
342 InitializeSingleGlobal(global
);
345 __attribute__((constructor(0))) void __hwasan_init() {
346 CHECK(!hwasan_init_is_running
);
347 if (hwasan_inited
) return;
348 hwasan_init_is_running
= 1;
349 SanitizerToolName
= "HWAddressSanitizer";
356 // Install tool-specific callbacks in sanitizer_common.
357 SetCheckUnwindCallback(CheckUnwind
);
359 __sanitizer_set_report_path(common_flags()->log_path
);
361 AndroidTestTlsSlot();
363 DisableCoreDumperIfNecessary();
365 InitInstrumentation();
366 if constexpr (!SANITIZER_FUCHSIA
) {
367 // Fuchsia's libc provides a hook (__sanitizer_module_loaded) that runs on
368 // the startup path which calls into __hwasan_library_loaded on all
369 // initially loaded modules, so explicitly registering the globals here
374 // Needs to be called here because flags()->random_tags might not have been
375 // initialized when InitInstrumentation() was called.
376 GetCurrentThread()->EnsureRandomStateInited();
378 SetPrintfAndReportCallback(AppendToErrorMessageBuffer
);
379 // This may call libc -> needs initialized shadow.
382 InitializeInterceptors();
383 InstallDeadlySignalHandlers(HwasanOnDeadlySignal
);
384 InstallAtExitHandler(); // Needs __cxa_atexit interceptor.
386 InitializeCoverage(common_flags()->coverage
, common_flags()->coverage_dir
);
389 HwasanTSDThreadInit();
391 HwasanAllocatorInit();
392 HwasanInstallAtForkHandler();
394 if (CAN_SANITIZE_LEAKS
) {
395 __lsan::InitCommonLsan();
396 InstallAtExitCheckLeaks();
399 #if HWASAN_CONTAINS_UBSAN
400 __ubsan::InitAsPlugin();
403 if (CAN_SANITIZE_LEAKS
) {
404 __lsan::ScopedInterceptorDisabler disabler
;
405 Symbolizer::LateInitialize();
407 Symbolizer::LateInitialize();
410 VPrintf(1, "HWAddressSanitizer init done\n");
412 hwasan_init_is_running
= 0;
416 void __hwasan_library_loaded(ElfW(Addr
) base
, const ElfW(Phdr
) * phdr
,
418 for (const hwasan_global
&global
: HwasanGlobalsFor(base
, phdr
, phnum
))
419 InitializeSingleGlobal(global
);
422 void __hwasan_library_unloaded(ElfW(Addr
) base
, const ElfW(Phdr
) * phdr
,
424 for (; phnum
!= 0; ++phdr
, --phnum
)
425 if (phdr
->p_type
== PT_LOAD
)
426 TagMemory(base
+ phdr
->p_vaddr
, phdr
->p_memsz
, 0);
429 void __hwasan_print_shadow(const void *p
, uptr sz
) {
430 uptr ptr_raw
= UntagAddr(reinterpret_cast<uptr
>(p
));
431 uptr shadow_first
= MemToShadow(ptr_raw
);
432 uptr shadow_last
= MemToShadow(ptr_raw
+ sz
- 1);
433 Printf("HWASan shadow map for %zx .. %zx (pointer tag %x)\n", ptr_raw
,
434 ptr_raw
+ sz
, GetTagFromPointer((uptr
)p
));
435 for (uptr s
= shadow_first
; s
<= shadow_last
; ++s
) {
436 tag_t mem_tag
= *reinterpret_cast<tag_t
*>(s
);
437 uptr granule_addr
= ShadowToMem(s
);
438 if (mem_tag
&& mem_tag
< kShadowAlignment
)
439 Printf(" %zx: %02x(%02x)\n", granule_addr
, mem_tag
,
440 *reinterpret_cast<tag_t
*>(granule_addr
+ kShadowAlignment
- 1));
442 Printf(" %zx: %02x\n", granule_addr
, mem_tag
);
446 sptr
__hwasan_test_shadow(const void *p
, uptr sz
) {
449 tag_t ptr_tag
= GetTagFromPointer((uptr
)p
);
450 uptr ptr_raw
= UntagAddr(reinterpret_cast<uptr
>(p
));
451 uptr shadow_first
= MemToShadow(ptr_raw
);
452 uptr shadow_last
= MemToShadow(ptr_raw
+ sz
- 1);
453 for (uptr s
= shadow_first
; s
<= shadow_last
; ++s
)
454 if (*(tag_t
*)s
!= ptr_tag
) {
455 sptr offset
= ShadowToMem(s
) - ptr_raw
;
456 return offset
< 0 ? 0 : offset
;
461 u16
__sanitizer_unaligned_load16(const uu16
*p
) {
464 u32
__sanitizer_unaligned_load32(const uu32
*p
) {
467 u64
__sanitizer_unaligned_load64(const uu64
*p
) {
470 void __sanitizer_unaligned_store16(uu16
*p
, u16 x
) {
473 void __sanitizer_unaligned_store32(uu32
*p
, u32 x
) {
476 void __sanitizer_unaligned_store64(uu64
*p
, u64 x
) {
480 void __hwasan_loadN(uptr p
, uptr sz
) {
481 CheckAddressSized
<ErrorAction::Abort
, AccessType::Load
>(p
, sz
);
483 void __hwasan_load1(uptr p
) {
484 CheckAddress
<ErrorAction::Abort
, AccessType::Load
, 0>(p
);
486 void __hwasan_load2(uptr p
) {
487 CheckAddress
<ErrorAction::Abort
, AccessType::Load
, 1>(p
);
489 void __hwasan_load4(uptr p
) {
490 CheckAddress
<ErrorAction::Abort
, AccessType::Load
, 2>(p
);
492 void __hwasan_load8(uptr p
) {
493 CheckAddress
<ErrorAction::Abort
, AccessType::Load
, 3>(p
);
495 void __hwasan_load16(uptr p
) {
496 CheckAddress
<ErrorAction::Abort
, AccessType::Load
, 4>(p
);
499 void __hwasan_loadN_noabort(uptr p
, uptr sz
) {
500 CheckAddressSized
<ErrorAction::Recover
, AccessType::Load
>(p
, sz
);
502 void __hwasan_load1_noabort(uptr p
) {
503 CheckAddress
<ErrorAction::Recover
, AccessType::Load
, 0>(p
);
505 void __hwasan_load2_noabort(uptr p
) {
506 CheckAddress
<ErrorAction::Recover
, AccessType::Load
, 1>(p
);
508 void __hwasan_load4_noabort(uptr p
) {
509 CheckAddress
<ErrorAction::Recover
, AccessType::Load
, 2>(p
);
511 void __hwasan_load8_noabort(uptr p
) {
512 CheckAddress
<ErrorAction::Recover
, AccessType::Load
, 3>(p
);
514 void __hwasan_load16_noabort(uptr p
) {
515 CheckAddress
<ErrorAction::Recover
, AccessType::Load
, 4>(p
);
518 void __hwasan_storeN(uptr p
, uptr sz
) {
519 CheckAddressSized
<ErrorAction::Abort
, AccessType::Store
>(p
, sz
);
521 void __hwasan_store1(uptr p
) {
522 CheckAddress
<ErrorAction::Abort
, AccessType::Store
, 0>(p
);
524 void __hwasan_store2(uptr p
) {
525 CheckAddress
<ErrorAction::Abort
, AccessType::Store
, 1>(p
);
527 void __hwasan_store4(uptr p
) {
528 CheckAddress
<ErrorAction::Abort
, AccessType::Store
, 2>(p
);
530 void __hwasan_store8(uptr p
) {
531 CheckAddress
<ErrorAction::Abort
, AccessType::Store
, 3>(p
);
533 void __hwasan_store16(uptr p
) {
534 CheckAddress
<ErrorAction::Abort
, AccessType::Store
, 4>(p
);
537 void __hwasan_storeN_noabort(uptr p
, uptr sz
) {
538 CheckAddressSized
<ErrorAction::Recover
, AccessType::Store
>(p
, sz
);
540 void __hwasan_store1_noabort(uptr p
) {
541 CheckAddress
<ErrorAction::Recover
, AccessType::Store
, 0>(p
);
543 void __hwasan_store2_noabort(uptr p
) {
544 CheckAddress
<ErrorAction::Recover
, AccessType::Store
, 1>(p
);
546 void __hwasan_store4_noabort(uptr p
) {
547 CheckAddress
<ErrorAction::Recover
, AccessType::Store
, 2>(p
);
549 void __hwasan_store8_noabort(uptr p
) {
550 CheckAddress
<ErrorAction::Recover
, AccessType::Store
, 3>(p
);
552 void __hwasan_store16_noabort(uptr p
) {
553 CheckAddress
<ErrorAction::Recover
, AccessType::Store
, 4>(p
);
556 void __hwasan_tag_memory(uptr p
, u8 tag
, uptr sz
) {
557 TagMemoryAligned(p
, sz
, tag
);
560 uptr
__hwasan_tag_pointer(uptr p
, u8 tag
) {
561 return AddTagToPointer(p
, tag
);
564 void __hwasan_handle_longjmp(const void *sp_dst
) {
565 uptr dst
= (uptr
)sp_dst
;
566 // HWASan does not support tagged SP.
567 CHECK(GetTagFromPointer(dst
) == 0);
569 uptr sp
= (uptr
)__builtin_frame_address(0);
570 static const uptr kMaxExpectedCleanupSize
= 64 << 20; // 64M
571 if (dst
< sp
|| dst
- sp
> kMaxExpectedCleanupSize
) {
573 "WARNING: HWASan is ignoring requested __hwasan_handle_longjmp: "
574 "stack top: %p; target %p; distance: %p (%zd)\n"
575 "False positive error reports may follow\n",
576 (void *)sp
, (void *)dst
, dst
- sp
);
579 TagMemory(sp
, dst
- sp
, 0);
582 void __hwasan_handle_vfork(const void *sp_dst
) {
583 uptr sp
= (uptr
)sp_dst
;
584 Thread
*t
= GetCurrentThread();
586 uptr top
= t
->stack_top();
587 uptr bottom
= t
->stack_bottom();
588 if (top
== 0 || bottom
== 0 || sp
< bottom
|| sp
>= top
) {
590 "WARNING: HWASan is ignoring requested __hwasan_handle_vfork: "
591 "stack top: %zx; current %zx; bottom: %zx \n"
592 "False positive error reports may follow\n",
596 TagMemory(bottom
, sp
- bottom
, 0);
599 extern "C" void *__hwasan_extra_spill_area() {
600 Thread
*t
= GetCurrentThread();
601 return &t
->vfork_spill();
604 void __hwasan_print_memory_usage() {
605 InternalScopedString s
;
606 HwasanFormatMemoryUsage(s
);
607 Printf("%s\n", s
.data());
610 static const u8 kFallbackTag
= 0xBB & kTagMask
;
612 u8
__hwasan_generate_tag() {
613 Thread
*t
= GetCurrentThread();
614 if (!t
) return kFallbackTag
;
615 return t
->GenerateRandomTag();
618 void __hwasan_add_frame_record(u64 frame_record_info
) {
619 Thread
*t
= GetCurrentThread();
621 t
->stack_allocations()->push(frame_record_info
);
624 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
626 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
627 const char* __hwasan_default_options() { return ""; }
632 SANITIZER_INTERFACE_ATTRIBUTE
633 void __sanitizer_print_stack_trace() {
634 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
638 // Entry point for interoperability between __hwasan_tag_mismatch (ASM) and the
639 // rest of the mismatch handling code (C++).
640 void __hwasan_tag_mismatch4(uptr addr
, uptr access_info
, uptr
*registers_frame
,
642 __hwasan::HwasanTagMismatch(addr
, (uptr
)__builtin_return_address(0),
643 (uptr
)__builtin_frame_address(0), access_info
,
644 registers_frame
, outsize
);