xref: /freebsd-src/contrib/llvm-project/compiler-rt/lib/lsan/lsan_common_mac.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
168d75effSDimitry Andric //=-- lsan_common_mac.cpp -------------------------------------------------===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric //
968d75effSDimitry Andric // This file is a part of LeakSanitizer.
1068d75effSDimitry Andric // Implementation of common leak checking functionality. Darwin-specific code.
1168d75effSDimitry Andric //
1268d75effSDimitry Andric //===----------------------------------------------------------------------===//
1368d75effSDimitry Andric 
1468d75effSDimitry Andric #include "sanitizer_common/sanitizer_platform.h"
1568d75effSDimitry Andric #include "sanitizer_common/sanitizer_libc.h"
1668d75effSDimitry Andric #include "lsan_common.h"
1768d75effSDimitry Andric 
1868d75effSDimitry Andric #if CAN_SANITIZE_LEAKS && SANITIZER_MAC
1968d75effSDimitry Andric 
2068d75effSDimitry Andric #include "sanitizer_common/sanitizer_allocator_internal.h"
2168d75effSDimitry Andric #include "lsan_allocator.h"
2268d75effSDimitry Andric 
2368d75effSDimitry Andric #include <pthread.h>
2468d75effSDimitry Andric 
2568d75effSDimitry Andric #include <mach/mach.h>
2668d75effSDimitry Andric 
2768d75effSDimitry Andric // Only introduced in Mac OS X 10.9.
2868d75effSDimitry Andric #ifdef VM_MEMORY_OS_ALLOC_ONCE
2968d75effSDimitry Andric static const int kSanitizerVmMemoryOsAllocOnce = VM_MEMORY_OS_ALLOC_ONCE;
3068d75effSDimitry Andric #else
3168d75effSDimitry Andric static const int kSanitizerVmMemoryOsAllocOnce = 73;
3268d75effSDimitry Andric #endif
3368d75effSDimitry Andric 
3468d75effSDimitry Andric namespace __lsan {
3568d75effSDimitry Andric 
3668d75effSDimitry Andric typedef struct {
3768d75effSDimitry Andric   int disable_counter;
3868d75effSDimitry Andric   u32 current_thread_id;
3968d75effSDimitry Andric   AllocatorCache cache;
4068d75effSDimitry Andric } thread_local_data_t;
4168d75effSDimitry Andric 
4268d75effSDimitry Andric static pthread_key_t key;
4368d75effSDimitry Andric static pthread_once_t key_once = PTHREAD_ONCE_INIT;
4468d75effSDimitry Andric 
4568d75effSDimitry Andric // The main thread destructor requires the current thread id,
4668d75effSDimitry Andric // so we can't destroy it until it's been used and reset to invalid tid
4768d75effSDimitry Andric void restore_tid_data(void *ptr) {
4868d75effSDimitry Andric   thread_local_data_t *data = (thread_local_data_t *)ptr;
4968d75effSDimitry Andric   if (data->current_thread_id != kInvalidTid)
5068d75effSDimitry Andric     pthread_setspecific(key, data);
5168d75effSDimitry Andric }
5268d75effSDimitry Andric 
5368d75effSDimitry Andric static void make_tls_key() {
5468d75effSDimitry Andric   CHECK_EQ(pthread_key_create(&key, restore_tid_data), 0);
5568d75effSDimitry Andric }
5668d75effSDimitry Andric 
5768d75effSDimitry Andric static thread_local_data_t *get_tls_val(bool alloc) {
5868d75effSDimitry Andric   pthread_once(&key_once, make_tls_key);
5968d75effSDimitry Andric 
6068d75effSDimitry Andric   thread_local_data_t *ptr = (thread_local_data_t *)pthread_getspecific(key);
6168d75effSDimitry Andric   if (ptr == NULL && alloc) {
6268d75effSDimitry Andric     ptr = (thread_local_data_t *)InternalAlloc(sizeof(*ptr));
6368d75effSDimitry Andric     ptr->disable_counter = 0;
6468d75effSDimitry Andric     ptr->current_thread_id = kInvalidTid;
6568d75effSDimitry Andric     ptr->cache = AllocatorCache();
6668d75effSDimitry Andric     pthread_setspecific(key, ptr);
6768d75effSDimitry Andric   }
6868d75effSDimitry Andric 
6968d75effSDimitry Andric   return ptr;
7068d75effSDimitry Andric }
7168d75effSDimitry Andric 
7268d75effSDimitry Andric bool DisabledInThisThread() {
7368d75effSDimitry Andric   thread_local_data_t *data = get_tls_val(false);
7468d75effSDimitry Andric   return data ? data->disable_counter > 0 : false;
7568d75effSDimitry Andric }
7668d75effSDimitry Andric 
7768d75effSDimitry Andric void DisableInThisThread() { ++get_tls_val(true)->disable_counter; }
7868d75effSDimitry Andric 
7968d75effSDimitry Andric void EnableInThisThread() {
8068d75effSDimitry Andric   int *disable_counter = &get_tls_val(true)->disable_counter;
8168d75effSDimitry Andric   if (*disable_counter == 0) {
8268d75effSDimitry Andric     DisableCounterUnderflow();
8368d75effSDimitry Andric   }
8468d75effSDimitry Andric   --*disable_counter;
8568d75effSDimitry Andric }
8668d75effSDimitry Andric 
8768d75effSDimitry Andric u32 GetCurrentThread() {
8868d75effSDimitry Andric   thread_local_data_t *data = get_tls_val(false);
8968d75effSDimitry Andric   return data ? data->current_thread_id : kInvalidTid;
9068d75effSDimitry Andric }
9168d75effSDimitry Andric 
9268d75effSDimitry Andric void SetCurrentThread(u32 tid) { get_tls_val(true)->current_thread_id = tid; }
9368d75effSDimitry Andric 
9468d75effSDimitry Andric AllocatorCache *GetAllocatorCache() { return &get_tls_val(true)->cache; }
9568d75effSDimitry Andric 
9668d75effSDimitry Andric LoadedModule *GetLinker() { return nullptr; }
9768d75effSDimitry Andric 
9868d75effSDimitry Andric // Required on Linux for initialization of TLS behavior, but should not be
9968d75effSDimitry Andric // required on Darwin.
10068d75effSDimitry Andric void InitializePlatformSpecificModules() {}
10168d75effSDimitry Andric 
10268d75effSDimitry Andric // Sections which can't contain contain global pointers. This list errs on the
10368d75effSDimitry Andric // side of caution to avoid false positives, at the expense of performance.
10468d75effSDimitry Andric //
10568d75effSDimitry Andric // Other potentially safe sections include:
10668d75effSDimitry Andric // __all_image_info, __crash_info, __const, __got, __interpose, __objc_msg_break
10768d75effSDimitry Andric //
10868d75effSDimitry Andric // Sections which definitely cannot be included here are:
10968d75effSDimitry Andric // __objc_data, __objc_const, __data, __bss, __common, __thread_data,
11068d75effSDimitry Andric // __thread_bss, __thread_vars, __objc_opt_rw, __objc_opt_ptrs
11168d75effSDimitry Andric static const char *kSkippedSecNames[] = {
11268d75effSDimitry Andric     "__cfstring",       "__la_symbol_ptr",  "__mod_init_func",
11368d75effSDimitry Andric     "__mod_term_func",  "__nl_symbol_ptr",  "__objc_classlist",
11468d75effSDimitry Andric     "__objc_classrefs", "__objc_imageinfo", "__objc_nlclslist",
11568d75effSDimitry Andric     "__objc_protolist", "__objc_selrefs",   "__objc_superrefs"};
11668d75effSDimitry Andric 
11768d75effSDimitry Andric // Scans global variables for heap pointers.
11868d75effSDimitry Andric void ProcessGlobalRegions(Frontier *frontier) {
11968d75effSDimitry Andric   for (auto name : kSkippedSecNames)
12068d75effSDimitry Andric     CHECK(internal_strnlen(name, kMaxSegName + 1) <= kMaxSegName);
12168d75effSDimitry Andric 
12268d75effSDimitry Andric   MemoryMappingLayout memory_mapping(false);
12368d75effSDimitry Andric   InternalMmapVector<LoadedModule> modules;
12468d75effSDimitry Andric   modules.reserve(128);
12568d75effSDimitry Andric   memory_mapping.DumpListOfModules(&modules);
12668d75effSDimitry Andric   for (uptr i = 0; i < modules.size(); ++i) {
12768d75effSDimitry Andric     // Even when global scanning is disabled, we still need to scan
12868d75effSDimitry Andric     // system libraries for stashed pointers
12968d75effSDimitry Andric     if (!flags()->use_globals && modules[i].instrumented()) continue;
13068d75effSDimitry Andric 
13168d75effSDimitry Andric     for (const __sanitizer::LoadedModule::AddressRange &range :
13268d75effSDimitry Andric          modules[i].ranges()) {
13368d75effSDimitry Andric       // Sections storing global variables are writable and non-executable
13468d75effSDimitry Andric       if (range.executable || !range.writable) continue;
13568d75effSDimitry Andric 
13668d75effSDimitry Andric       for (auto name : kSkippedSecNames) {
13768d75effSDimitry Andric         if (!internal_strcmp(range.name, name)) continue;
13868d75effSDimitry Andric       }
13968d75effSDimitry Andric 
14068d75effSDimitry Andric       ScanGlobalRange(range.beg, range.end, frontier);
14168d75effSDimitry Andric     }
14268d75effSDimitry Andric   }
14368d75effSDimitry Andric }
14468d75effSDimitry Andric 
14568d75effSDimitry Andric void ProcessPlatformSpecificAllocations(Frontier *frontier) {
14668d75effSDimitry Andric   unsigned depth = 1;
14768d75effSDimitry Andric   vm_size_t size = 0;
14868d75effSDimitry Andric   vm_address_t address = 0;
14968d75effSDimitry Andric   kern_return_t err = KERN_SUCCESS;
15068d75effSDimitry Andric   mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
15168d75effSDimitry Andric 
15268d75effSDimitry Andric   InternalMmapVector<RootRegion> const *root_regions = GetRootRegions();
15368d75effSDimitry Andric 
15468d75effSDimitry Andric   while (err == KERN_SUCCESS) {
15568d75effSDimitry Andric     struct vm_region_submap_info_64 info;
15668d75effSDimitry Andric     err = vm_region_recurse_64(mach_task_self(), &address, &size, &depth,
15768d75effSDimitry Andric                                (vm_region_info_t)&info, &count);
15868d75effSDimitry Andric 
15968d75effSDimitry Andric     uptr end_address = address + size;
16068d75effSDimitry Andric 
16168d75effSDimitry Andric     // libxpc stashes some pointers in the Kernel Alloc Once page,
16268d75effSDimitry Andric     // make sure not to report those as leaks.
16368d75effSDimitry Andric     if (info.user_tag == kSanitizerVmMemoryOsAllocOnce) {
16468d75effSDimitry Andric       ScanRangeForPointers(address, end_address, frontier, "GLOBAL",
16568d75effSDimitry Andric                            kReachable);
16668d75effSDimitry Andric 
16768d75effSDimitry Andric       // Recursing over the full memory map is very slow, break out
16868d75effSDimitry Andric       // early if we don't need the full iteration.
16968d75effSDimitry Andric       if (!flags()->use_root_regions || !root_regions->size())
17068d75effSDimitry Andric         break;
17168d75effSDimitry Andric     }
17268d75effSDimitry Andric 
17368d75effSDimitry Andric     // This additional root region scan is required on Darwin in order to
17468d75effSDimitry Andric     // detect root regions contained within mmap'd memory regions, because
17568d75effSDimitry Andric     // the Darwin implementation of sanitizer_procmaps traverses images
17668d75effSDimitry Andric     // as loaded by dyld, and not the complete set of all memory regions.
17768d75effSDimitry Andric     //
17868d75effSDimitry Andric     // TODO(fjricci) - remove this once sanitizer_procmaps_mac has the same
17968d75effSDimitry Andric     // behavior as sanitizer_procmaps_linux and traverses all memory regions
18068d75effSDimitry Andric     if (flags()->use_root_regions) {
18168d75effSDimitry Andric       for (uptr i = 0; i < root_regions->size(); i++) {
18268d75effSDimitry Andric         ScanRootRegion(frontier, (*root_regions)[i], address, end_address,
18368d75effSDimitry Andric                        info.protection & kProtectionRead);
18468d75effSDimitry Andric       }
18568d75effSDimitry Andric     }
18668d75effSDimitry Andric 
18768d75effSDimitry Andric     address = end_address;
18868d75effSDimitry Andric   }
18968d75effSDimitry Andric }
19068d75effSDimitry Andric 
19168d75effSDimitry Andric // On darwin, we can intercept _exit gracefully, and return a failing exit code
19268d75effSDimitry Andric // if required at that point. Calling Die() here is undefined behavior and
19368d75effSDimitry Andric // causes rare race conditions.
19468d75effSDimitry Andric void HandleLeaks() {}
19568d75effSDimitry Andric 
196*5ffd83dbSDimitry Andric void LockStuffAndStopTheWorld(StopTheWorldCallback callback,
197*5ffd83dbSDimitry Andric                               CheckForLeaksParam *argument) {
19868d75effSDimitry Andric   LockThreadRegistry();
19968d75effSDimitry Andric   LockAllocator();
20068d75effSDimitry Andric   StopTheWorld(callback, argument);
20168d75effSDimitry Andric   UnlockAllocator();
20268d75effSDimitry Andric   UnlockThreadRegistry();
20368d75effSDimitry Andric }
20468d75effSDimitry Andric 
20568d75effSDimitry Andric } // namespace __lsan
20668d75effSDimitry Andric 
20768d75effSDimitry Andric #endif // CAN_SANITIZE_LEAKS && SANITIZER_MAC
208