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