1 //===-- ubsan_init.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 // Initialization of UBSan runtime.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ubsan_platform.h"
14 #if CAN_SANITIZE_UB
15 #include "sanitizer_common/sanitizer_common.h"
16 #include "sanitizer_common/sanitizer_interface_internal.h"
17 #include "sanitizer_common/sanitizer_libc.h"
18 #include "sanitizer_common/sanitizer_mutex.h"
19 #include "sanitizer_common/sanitizer_symbolizer.h"
20 #include "ubsan_diag.h"
21 #include "ubsan_flags.h"
22 #include "ubsan_init.h"
23 
24 using namespace __ubsan;
25 
26 const char *__ubsan::GetSanititizerToolName() {
27   return "UndefinedBehaviorSanitizer";
28 }
29 
30 static bool ubsan_initialized;
31 static StaticSpinMutex ubsan_init_mu;
32 
33 static void CommonInit() {
34   InitializeSuppressions();
35 }
36 
37 static void UbsanDie() {
38   if (common_flags()->print_module_map >= 1)
39     DumpProcessMap();
40 }
41 
42 static void CommonStandaloneInit() {
43   SanitizerToolName = GetSanititizerToolName();
44   CacheBinaryName();
45   InitializeFlags();
46   __sanitizer::InitializePlatformEarly();
47   __sanitizer_set_report_path(common_flags()->log_path);
48   AndroidLogInit();
49   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
50   CommonInit();
51 
52   // Only add die callback when running in standalone mode to avoid printing
53   // the same information from multiple sanitizers' output
54   AddDieCallback(UbsanDie);
55   Symbolizer::LateInitialize();
56 }
57 
58 void __ubsan::InitAsStandalone() {
59   SpinMutexLock l(&ubsan_init_mu);
60   if (!ubsan_initialized) {
61     CommonStandaloneInit();
62     ubsan_initialized = true;
63   }
64 }
65 
66 void __ubsan::InitAsStandaloneIfNecessary() { return InitAsStandalone(); }
67 
68 void __ubsan::InitAsPlugin() {
69   SpinMutexLock l(&ubsan_init_mu);
70   if (!ubsan_initialized) {
71     CommonInit();
72     ubsan_initialized = true;
73   }
74 }
75 
76 #endif  // CAN_SANITIZE_UB
77