lsan_common_mac.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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_APPLE
  17. # include <mach/mach.h>
  18. # include <mach/vm_statistics.h>
  19. # include <pthread.h>
  20. # include "lsan_allocator.h"
  21. # include "sanitizer_common/sanitizer_allocator_internal.h"
  22. namespace __lsan {
  23. class ThreadContextLsanBase;
  24. enum class SeenRegion {
  25. None = 0,
  26. AllocOnce = 1 << 0,
  27. LibDispatch = 1 << 1,
  28. Foundation = 1 << 2,
  29. All = AllocOnce | LibDispatch | Foundation
  30. };
  31. inline SeenRegion operator|(SeenRegion left, SeenRegion right) {
  32. return static_cast<SeenRegion>(static_cast<int>(left) |
  33. static_cast<int>(right));
  34. }
  35. inline SeenRegion &operator|=(SeenRegion &left, const SeenRegion &right) {
  36. left = left | right;
  37. return left;
  38. }
  39. struct RegionScanState {
  40. SeenRegion seen_regions = SeenRegion::None;
  41. bool in_libdispatch = false;
  42. };
  43. typedef struct {
  44. int disable_counter;
  45. ThreadContextLsanBase *current_thread;
  46. AllocatorCache cache;
  47. } thread_local_data_t;
  48. static pthread_key_t key;
  49. static pthread_once_t key_once = PTHREAD_ONCE_INIT;
  50. // The main thread destructor requires the current thread,
  51. // so we can't destroy it until it's been used and reset.
  52. void restore_tid_data(void *ptr) {
  53. thread_local_data_t *data = (thread_local_data_t *)ptr;
  54. if (data->current_thread)
  55. pthread_setspecific(key, data);
  56. }
  57. static void make_tls_key() {
  58. CHECK_EQ(pthread_key_create(&key, restore_tid_data), 0);
  59. }
  60. static thread_local_data_t *get_tls_val(bool alloc) {
  61. pthread_once(&key_once, make_tls_key);
  62. thread_local_data_t *ptr = (thread_local_data_t *)pthread_getspecific(key);
  63. if (ptr == NULL && alloc) {
  64. ptr = (thread_local_data_t *)InternalAlloc(sizeof(*ptr));
  65. ptr->disable_counter = 0;
  66. ptr->current_thread = nullptr;
  67. ptr->cache = AllocatorCache();
  68. pthread_setspecific(key, ptr);
  69. }
  70. return ptr;
  71. }
  72. bool DisabledInThisThread() {
  73. thread_local_data_t *data = get_tls_val(false);
  74. return data ? data->disable_counter > 0 : false;
  75. }
  76. void DisableInThisThread() { ++get_tls_val(true)->disable_counter; }
  77. void EnableInThisThread() {
  78. int *disable_counter = &get_tls_val(true)->disable_counter;
  79. if (*disable_counter == 0) {
  80. DisableCounterUnderflow();
  81. }
  82. --*disable_counter;
  83. }
  84. ThreadContextLsanBase *GetCurrentThread() {
  85. thread_local_data_t *data = get_tls_val(false);
  86. return data ? data->current_thread : nullptr;
  87. }
  88. void SetCurrentThread(ThreadContextLsanBase *tctx) {
  89. get_tls_val(true)->current_thread = tctx;
  90. }
  91. AllocatorCache *GetAllocatorCache() { return &get_tls_val(true)->cache; }
  92. LoadedModule *GetLinker() { return nullptr; }
  93. // Required on Linux for initialization of TLS behavior, but should not be
  94. // required on Darwin.
  95. void InitializePlatformSpecificModules() {}
  96. // Sections which can't contain contain global pointers. This list errs on the
  97. // side of caution to avoid false positives, at the expense of performance.
  98. //
  99. // Other potentially safe sections include:
  100. // __all_image_info, __crash_info, __const, __got, __interpose, __objc_msg_break
  101. //
  102. // Sections which definitely cannot be included here are:
  103. // __objc_data, __objc_const, __data, __bss, __common, __thread_data,
  104. // __thread_bss, __thread_vars, __objc_opt_rw, __objc_opt_ptrs
  105. static const char *kSkippedSecNames[] = {
  106. "__cfstring", "__la_symbol_ptr", "__mod_init_func",
  107. "__mod_term_func", "__nl_symbol_ptr", "__objc_classlist",
  108. "__objc_classrefs", "__objc_imageinfo", "__objc_nlclslist",
  109. "__objc_protolist", "__objc_selrefs", "__objc_superrefs"};
  110. // Scans global variables for heap pointers.
  111. void ProcessGlobalRegions(Frontier *frontier) {
  112. for (auto name : kSkippedSecNames)
  113. CHECK(internal_strnlen(name, kMaxSegName + 1) <= kMaxSegName);
  114. MemoryMappingLayout memory_mapping(false);
  115. InternalMmapVector<LoadedModule> modules;
  116. modules.reserve(128);
  117. memory_mapping.DumpListOfModules(&modules);
  118. for (uptr i = 0; i < modules.size(); ++i) {
  119. // Even when global scanning is disabled, we still need to scan
  120. // system libraries for stashed pointers
  121. if (!flags()->use_globals && modules[i].instrumented()) continue;
  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. for (auto name : kSkippedSecNames) {
  127. if (!internal_strcmp(range.name, name)) continue;
  128. }
  129. ScanGlobalRange(range.beg, range.end, frontier);
  130. }
  131. }
  132. }
  133. void ProcessPlatformSpecificAllocations(Frontier *frontier) {
  134. vm_address_t address = 0;
  135. kern_return_t err = KERN_SUCCESS;
  136. InternalMmapVector<Region> mapped_regions;
  137. bool use_root_regions = flags()->use_root_regions && HasRootRegions();
  138. RegionScanState scan_state;
  139. while (err == KERN_SUCCESS) {
  140. vm_size_t size = 0;
  141. unsigned depth = 1;
  142. struct vm_region_submap_info_64 info;
  143. mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
  144. err = vm_region_recurse_64(mach_task_self(), &address, &size, &depth,
  145. (vm_region_info_t)&info, &count);
  146. uptr end_address = address + size;
  147. if (info.user_tag == VM_MEMORY_OS_ALLOC_ONCE) {
  148. // libxpc stashes some pointers in the Kernel Alloc Once page,
  149. // make sure not to report those as leaks.
  150. scan_state.seen_regions |= SeenRegion::AllocOnce;
  151. ScanRangeForPointers(address, end_address, frontier, "GLOBAL",
  152. kReachable);
  153. } else if (info.user_tag == VM_MEMORY_FOUNDATION) {
  154. // Objective-C block trampolines use the Foundation region.
  155. scan_state.seen_regions |= SeenRegion::Foundation;
  156. ScanRangeForPointers(address, end_address, frontier, "GLOBAL",
  157. kReachable);
  158. } else if (info.user_tag == VM_MEMORY_LIBDISPATCH) {
  159. // Dispatch continuations use the libdispatch region. Empirically, there
  160. // can be more than one region with this tag, so we'll optimistically
  161. // assume that they're continguous. Otherwise, we would need to scan every
  162. // region to ensure we find them all.
  163. scan_state.in_libdispatch = true;
  164. ScanRangeForPointers(address, end_address, frontier, "GLOBAL",
  165. kReachable);
  166. } else if (scan_state.in_libdispatch) {
  167. scan_state.seen_regions |= SeenRegion::LibDispatch;
  168. scan_state.in_libdispatch = false;
  169. }
  170. // Recursing over the full memory map is very slow, break out
  171. // early if we don't need the full iteration.
  172. if (scan_state.seen_regions == SeenRegion::All && !use_root_regions) {
  173. break;
  174. }
  175. // This additional root region scan is required on Darwin in order to
  176. // detect root regions contained within mmap'd memory regions, because
  177. // the Darwin implementation of sanitizer_procmaps traverses images
  178. // as loaded by dyld, and not the complete set of all memory regions.
  179. //
  180. // TODO(fjricci) - remove this once sanitizer_procmaps_mac has the same
  181. // behavior as sanitizer_procmaps_linux and traverses all memory regions
  182. if (use_root_regions && (info.protection & kProtectionRead))
  183. mapped_regions.push_back({address, end_address});
  184. address = end_address;
  185. }
  186. ScanRootRegions(frontier, mapped_regions);
  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. void LockStuffAndStopTheWorld(StopTheWorldCallback callback,
  193. CheckForLeaksParam *argument) {
  194. ScopedStopTheWorldLock lock;
  195. StopTheWorld(callback, argument);
  196. }
  197. } // namespace __lsan
  198. #endif // CAN_SANITIZE_LEAKS && SANITIZER_APPLE