]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/lsan/lsan_common_mac.cc
MFV r337022:
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / lsan / lsan_common_mac.cc
1 //=-- lsan_common_mac.cc --------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of LeakSanitizer.
11 // Implementation of common leak checking functionality. Darwin-specific code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "sanitizer_common/sanitizer_platform.h"
16 #include "lsan_common.h"
17
18 #if CAN_SANITIZE_LEAKS && SANITIZER_MAC
19
20 #include "sanitizer_common/sanitizer_allocator_internal.h"
21 #include "lsan_allocator.h"
22
23 #include <pthread.h>
24
25 #include <mach/mach.h>
26
27 namespace __lsan {
28
29 typedef struct {
30   int disable_counter;
31   u32 current_thread_id;
32   AllocatorCache cache;
33 } thread_local_data_t;
34
35 static pthread_key_t key;
36 static pthread_once_t key_once = PTHREAD_ONCE_INIT;
37
38 // The main thread destructor requires the current thread id,
39 // so we can't destroy it until it's been used and reset to invalid tid
40 void restore_tid_data(void *ptr) {
41   thread_local_data_t *data = (thread_local_data_t *)ptr;
42   if (data->current_thread_id != kInvalidTid)
43     pthread_setspecific(key, data);
44 }
45
46 static void make_tls_key() {
47   CHECK_EQ(pthread_key_create(&key, restore_tid_data), 0);
48 }
49
50 static thread_local_data_t *get_tls_val(bool alloc) {
51   pthread_once(&key_once, make_tls_key);
52
53   thread_local_data_t *ptr = (thread_local_data_t *)pthread_getspecific(key);
54   if (ptr == NULL && alloc) {
55     ptr = (thread_local_data_t *)InternalAlloc(sizeof(*ptr));
56     ptr->disable_counter = 0;
57     ptr->current_thread_id = kInvalidTid;
58     ptr->cache = AllocatorCache();
59     pthread_setspecific(key, ptr);
60   }
61
62   return ptr;
63 }
64
65 bool DisabledInThisThread() {
66   thread_local_data_t *data = get_tls_val(false);
67   return data ? data->disable_counter > 0 : false;
68 }
69
70 void DisableInThisThread() { ++get_tls_val(true)->disable_counter; }
71
72 void EnableInThisThread() {
73   int *disable_counter = &get_tls_val(true)->disable_counter;
74   if (*disable_counter == 0) {
75     DisableCounterUnderflow();
76   }
77   --*disable_counter;
78 }
79
80 u32 GetCurrentThread() {
81   thread_local_data_t *data = get_tls_val(false);
82   return data ? data->current_thread_id : kInvalidTid;
83 }
84
85 void SetCurrentThread(u32 tid) { get_tls_val(true)->current_thread_id = tid; }
86
87 AllocatorCache *GetAllocatorCache() { return &get_tls_val(true)->cache; }
88
89 LoadedModule *GetLinker() { return nullptr; }
90
91 // Required on Linux for initialization of TLS behavior, but should not be
92 // required on Darwin.
93 void InitializePlatformSpecificModules() {}
94
95 // Sections which can't contain contain global pointers. This list errs on the
96 // side of caution to avoid false positives, at the expense of performance.
97 //
98 // Other potentially safe sections include:
99 // __all_image_info, __crash_info, __const, __got, __interpose, __objc_msg_break
100 //
101 // Sections which definitely cannot be included here are:
102 // __objc_data, __objc_const, __data, __bss, __common, __thread_data,
103 // __thread_bss, __thread_vars, __objc_opt_rw, __objc_opt_ptrs
104 static const char *kSkippedSecNames[] = {
105     "__cfstring",       "__la_symbol_ptr",  "__mod_init_func",
106     "__mod_term_func",  "__nl_symbol_ptr",  "__objc_classlist",
107     "__objc_classrefs", "__objc_imageinfo", "__objc_nlclslist",
108     "__objc_protolist", "__objc_selrefs",   "__objc_superrefs"};
109
110 // Scans global variables for heap pointers.
111 void ProcessGlobalRegions(Frontier *frontier) {
112   for (auto name : kSkippedSecNames) CHECK(ARRAY_SIZE(name) < kMaxSegName);
113
114   MemoryMappingLayout memory_mapping(false);
115   InternalMmapVector<LoadedModule> modules(/*initial_capacity*/ 128);
116   memory_mapping.DumpListOfModules(&modules);
117   for (uptr i = 0; i < modules.size(); ++i) {
118     // Even when global scanning is disabled, we still need to scan
119     // system libraries for stashed pointers
120     if (!flags()->use_globals && modules[i].instrumented()) continue;
121
122     for (const __sanitizer::LoadedModule::AddressRange &range :
123          modules[i].ranges()) {
124       // Sections storing global variables are writable and non-executable
125       if (range.executable || !range.writable) continue;
126
127       for (auto name : kSkippedSecNames) {
128         if (!internal_strcmp(range.name, name)) continue;
129       }
130
131       ScanGlobalRange(range.beg, range.end, frontier);
132     }
133   }
134 }
135
136 void ProcessPlatformSpecificAllocations(Frontier *frontier) {
137   mach_port_name_t port;
138   if (task_for_pid(mach_task_self(), internal_getpid(), &port)
139       != KERN_SUCCESS) {
140     return;
141   }
142
143   unsigned depth = 1;
144   vm_size_t size = 0;
145   vm_address_t address = 0;
146   kern_return_t err = KERN_SUCCESS;
147   mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
148
149   InternalMmapVector<RootRegion> const *root_regions = GetRootRegions();
150
151   while (err == KERN_SUCCESS) {
152     struct vm_region_submap_info_64 info;
153     err = vm_region_recurse_64(port, &address, &size, &depth,
154                                (vm_region_info_t)&info, &count);
155
156     uptr end_address = address + size;
157
158     // libxpc stashes some pointers in the Kernel Alloc Once page,
159     // make sure not to report those as leaks.
160     if (info.user_tag == VM_MEMORY_OS_ALLOC_ONCE) {
161       ScanRangeForPointers(address, end_address, frontier, "GLOBAL",
162                            kReachable);
163
164       // Recursing over the full memory map is very slow, break out
165       // early if we don't need the full iteration.
166       if (!flags()->use_root_regions || !root_regions->size())
167         break;
168     }
169
170     // This additional root region scan is required on Darwin in order to
171     // detect root regions contained within mmap'd memory regions, because
172     // the Darwin implementation of sanitizer_procmaps traverses images
173     // as loaded by dyld, and not the complete set of all memory regions.
174     //
175     // TODO(fjricci) - remove this once sanitizer_procmaps_mac has the same
176     // behavior as sanitizer_procmaps_linux and traverses all memory regions
177     if (flags()->use_root_regions) {
178       for (uptr i = 0; i < root_regions->size(); i++) {
179         ScanRootRegion(frontier, (*root_regions)[i], address, end_address,
180                        info.protection & kProtectionRead);
181       }
182     }
183
184     address = end_address;
185   }
186 }
187
188 // On darwin, we can intercept _exit gracefully, and return a failing exit code
189 // if required at that point. Calling Die() here is undefined behavior and
190 // causes rare race conditions.
191 void HandleLeaks() {}
192
193 void DoStopTheWorld(StopTheWorldCallback callback, void *argument) {
194   StopTheWorld(callback, argument);
195 }
196
197 } // namespace __lsan
198
199 #endif // CAN_SANITIZE_LEAKS && SANITIZER_MAC