lsan_common_mac.cpp 6.9 KB

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