tsan_mman.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. //===-- tsan_mman.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 ThreadSanitizer (TSan), a race detector.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "sanitizer_common/sanitizer_allocator_checks.h"
  13. #include "sanitizer_common/sanitizer_allocator_interface.h"
  14. #include "sanitizer_common/sanitizer_allocator_report.h"
  15. #include "sanitizer_common/sanitizer_common.h"
  16. #include "sanitizer_common/sanitizer_errno.h"
  17. #include "sanitizer_common/sanitizer_placement_new.h"
  18. #include "tsan_mman.h"
  19. #include "tsan_rtl.h"
  20. #include "tsan_report.h"
  21. #include "tsan_flags.h"
  22. // May be overriden by front-end.
  23. SANITIZER_WEAK_DEFAULT_IMPL
  24. void __sanitizer_malloc_hook(void *ptr, uptr size) {
  25. (void)ptr;
  26. (void)size;
  27. }
  28. SANITIZER_WEAK_DEFAULT_IMPL
  29. void __sanitizer_free_hook(void *ptr) {
  30. (void)ptr;
  31. }
  32. namespace __tsan {
  33. struct MapUnmapCallback {
  34. void OnMap(uptr p, uptr size) const { }
  35. void OnUnmap(uptr p, uptr size) const {
  36. // We are about to unmap a chunk of user memory.
  37. // Mark the corresponding shadow memory as not needed.
  38. DontNeedShadowFor(p, size);
  39. // Mark the corresponding meta shadow memory as not needed.
  40. // Note the block does not contain any meta info at this point
  41. // (this happens after free).
  42. const uptr kMetaRatio = kMetaShadowCell / kMetaShadowSize;
  43. const uptr kPageSize = GetPageSizeCached() * kMetaRatio;
  44. // Block came from LargeMmapAllocator, so must be large.
  45. // We rely on this in the calculations below.
  46. CHECK_GE(size, 2 * kPageSize);
  47. uptr diff = RoundUp(p, kPageSize) - p;
  48. if (diff != 0) {
  49. p += diff;
  50. size -= diff;
  51. }
  52. diff = p + size - RoundDown(p + size, kPageSize);
  53. if (diff != 0)
  54. size -= diff;
  55. uptr p_meta = (uptr)MemToMeta(p);
  56. ReleaseMemoryPagesToOS(p_meta, p_meta + size / kMetaRatio);
  57. }
  58. };
  59. static char allocator_placeholder[sizeof(Allocator)] ALIGNED(64);
  60. Allocator *allocator() {
  61. return reinterpret_cast<Allocator*>(&allocator_placeholder);
  62. }
  63. struct GlobalProc {
  64. Mutex mtx;
  65. Processor *proc;
  66. // This mutex represents the internal allocator combined for
  67. // the purposes of deadlock detection. The internal allocator
  68. // uses multiple mutexes, moreover they are locked only occasionally
  69. // and they are spin mutexes which don't support deadlock detection.
  70. // So we use this fake mutex to serve as a substitute for these mutexes.
  71. CheckedMutex internal_alloc_mtx;
  72. GlobalProc()
  73. : mtx(MutexTypeGlobalProc),
  74. proc(ProcCreate()),
  75. internal_alloc_mtx(MutexTypeInternalAlloc) {}
  76. };
  77. static char global_proc_placeholder[sizeof(GlobalProc)] ALIGNED(64);
  78. GlobalProc *global_proc() {
  79. return reinterpret_cast<GlobalProc*>(&global_proc_placeholder);
  80. }
  81. static void InternalAllocAccess() {
  82. global_proc()->internal_alloc_mtx.Lock();
  83. global_proc()->internal_alloc_mtx.Unlock();
  84. }
  85. ScopedGlobalProcessor::ScopedGlobalProcessor() {
  86. GlobalProc *gp = global_proc();
  87. ThreadState *thr = cur_thread();
  88. if (thr->proc())
  89. return;
  90. // If we don't have a proc, use the global one.
  91. // There are currently only two known case where this path is triggered:
  92. // __interceptor_free
  93. // __nptl_deallocate_tsd
  94. // start_thread
  95. // clone
  96. // and:
  97. // ResetRange
  98. // __interceptor_munmap
  99. // __deallocate_stack
  100. // start_thread
  101. // clone
  102. // Ideally, we destroy thread state (and unwire proc) when a thread actually
  103. // exits (i.e. when we join/wait it). Then we would not need the global proc
  104. gp->mtx.Lock();
  105. ProcWire(gp->proc, thr);
  106. }
  107. ScopedGlobalProcessor::~ScopedGlobalProcessor() {
  108. GlobalProc *gp = global_proc();
  109. ThreadState *thr = cur_thread();
  110. if (thr->proc() != gp->proc)
  111. return;
  112. ProcUnwire(gp->proc, thr);
  113. gp->mtx.Unlock();
  114. }
  115. void AllocatorLock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  116. global_proc()->internal_alloc_mtx.Lock();
  117. InternalAllocatorLock();
  118. }
  119. void AllocatorUnlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  120. InternalAllocatorUnlock();
  121. global_proc()->internal_alloc_mtx.Unlock();
  122. }
  123. void GlobalProcessorLock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  124. global_proc()->mtx.Lock();
  125. }
  126. void GlobalProcessorUnlock() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  127. global_proc()->mtx.Unlock();
  128. }
  129. static constexpr uptr kMaxAllowedMallocSize = 1ull << 40;
  130. static uptr max_user_defined_malloc_size;
  131. void InitializeAllocator() {
  132. SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
  133. allocator()->Init(common_flags()->allocator_release_to_os_interval_ms);
  134. max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
  135. ? common_flags()->max_allocation_size_mb
  136. << 20
  137. : kMaxAllowedMallocSize;
  138. }
  139. void InitializeAllocatorLate() {
  140. new(global_proc()) GlobalProc();
  141. }
  142. void AllocatorProcStart(Processor *proc) {
  143. allocator()->InitCache(&proc->alloc_cache);
  144. internal_allocator()->InitCache(&proc->internal_alloc_cache);
  145. }
  146. void AllocatorProcFinish(Processor *proc) {
  147. allocator()->DestroyCache(&proc->alloc_cache);
  148. internal_allocator()->DestroyCache(&proc->internal_alloc_cache);
  149. }
  150. void AllocatorPrintStats() {
  151. allocator()->PrintStats();
  152. }
  153. static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
  154. if (atomic_load_relaxed(&thr->in_signal_handler) == 0 ||
  155. !ShouldReport(thr, ReportTypeSignalUnsafe))
  156. return;
  157. VarSizeStackTrace stack;
  158. ObtainCurrentStack(thr, pc, &stack);
  159. if (IsFiredSuppression(ctx, ReportTypeSignalUnsafe, stack))
  160. return;
  161. ThreadRegistryLock l(&ctx->thread_registry);
  162. ScopedReport rep(ReportTypeSignalUnsafe);
  163. rep.AddStack(stack, true);
  164. OutputReport(thr, rep);
  165. }
  166. void *user_alloc_internal(ThreadState *thr, uptr pc, uptr sz, uptr align,
  167. bool signal) {
  168. if (sz >= kMaxAllowedMallocSize || align >= kMaxAllowedMallocSize ||
  169. sz > max_user_defined_malloc_size) {
  170. if (AllocatorMayReturnNull())
  171. return nullptr;
  172. uptr malloc_limit =
  173. Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
  174. GET_STACK_TRACE_FATAL(thr, pc);
  175. ReportAllocationSizeTooBig(sz, malloc_limit, &stack);
  176. }
  177. if (UNLIKELY(IsRssLimitExceeded())) {
  178. if (AllocatorMayReturnNull())
  179. return nullptr;
  180. GET_STACK_TRACE_FATAL(thr, pc);
  181. ReportRssLimitExceeded(&stack);
  182. }
  183. void *p = allocator()->Allocate(&thr->proc()->alloc_cache, sz, align);
  184. if (UNLIKELY(!p)) {
  185. SetAllocatorOutOfMemory();
  186. if (AllocatorMayReturnNull())
  187. return nullptr;
  188. GET_STACK_TRACE_FATAL(thr, pc);
  189. ReportOutOfMemory(sz, &stack);
  190. }
  191. if (ctx && ctx->initialized)
  192. OnUserAlloc(thr, pc, (uptr)p, sz, true);
  193. if (signal)
  194. SignalUnsafeCall(thr, pc);
  195. return p;
  196. }
  197. void user_free(ThreadState *thr, uptr pc, void *p, bool signal) {
  198. ScopedGlobalProcessor sgp;
  199. if (ctx && ctx->initialized)
  200. OnUserFree(thr, pc, (uptr)p, true);
  201. allocator()->Deallocate(&thr->proc()->alloc_cache, p);
  202. if (signal)
  203. SignalUnsafeCall(thr, pc);
  204. }
  205. void *user_alloc(ThreadState *thr, uptr pc, uptr sz) {
  206. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, kDefaultAlignment));
  207. }
  208. void *user_calloc(ThreadState *thr, uptr pc, uptr size, uptr n) {
  209. if (UNLIKELY(CheckForCallocOverflow(size, n))) {
  210. if (AllocatorMayReturnNull())
  211. return SetErrnoOnNull(nullptr);
  212. GET_STACK_TRACE_FATAL(thr, pc);
  213. ReportCallocOverflow(n, size, &stack);
  214. }
  215. void *p = user_alloc_internal(thr, pc, n * size);
  216. if (p)
  217. internal_memset(p, 0, n * size);
  218. return SetErrnoOnNull(p);
  219. }
  220. void *user_reallocarray(ThreadState *thr, uptr pc, void *p, uptr size, uptr n) {
  221. if (UNLIKELY(CheckForCallocOverflow(size, n))) {
  222. if (AllocatorMayReturnNull())
  223. return SetErrnoOnNull(nullptr);
  224. GET_STACK_TRACE_FATAL(thr, pc);
  225. ReportReallocArrayOverflow(size, n, &stack);
  226. }
  227. return user_realloc(thr, pc, p, size * n);
  228. }
  229. void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write) {
  230. DPrintf("#%d: alloc(%zu) = 0x%zx\n", thr->tid, sz, p);
  231. // Note: this can run before thread initialization/after finalization.
  232. // As a result this is not necessarily synchronized with DoReset,
  233. // which iterates over and resets all sync objects,
  234. // but it is fine to create new MBlocks in this context.
  235. ctx->metamap.AllocBlock(thr, pc, p, sz);
  236. // If this runs before thread initialization/after finalization
  237. // and we don't have trace initialized, we can't imitate writes.
  238. // In such case just reset the shadow range, it is fine since
  239. // it affects only a small fraction of special objects.
  240. if (write && thr->ignore_reads_and_writes == 0 &&
  241. atomic_load_relaxed(&thr->trace_pos))
  242. MemoryRangeImitateWrite(thr, pc, (uptr)p, sz);
  243. else
  244. MemoryResetRange(thr, pc, (uptr)p, sz);
  245. }
  246. void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write) {
  247. CHECK_NE(p, (void*)0);
  248. if (!thr->slot) {
  249. // Very early/late in thread lifetime, or during fork.
  250. UNUSED uptr sz = ctx->metamap.FreeBlock(thr->proc(), p, false);
  251. DPrintf("#%d: free(0x%zx, %zu) (no slot)\n", thr->tid, p, sz);
  252. return;
  253. }
  254. SlotLocker locker(thr);
  255. uptr sz = ctx->metamap.FreeBlock(thr->proc(), p, true);
  256. DPrintf("#%d: free(0x%zx, %zu)\n", thr->tid, p, sz);
  257. if (write && thr->ignore_reads_and_writes == 0)
  258. MemoryRangeFreed(thr, pc, (uptr)p, sz);
  259. }
  260. void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) {
  261. // FIXME: Handle "shrinking" more efficiently,
  262. // it seems that some software actually does this.
  263. if (!p)
  264. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz));
  265. if (!sz) {
  266. user_free(thr, pc, p);
  267. return nullptr;
  268. }
  269. void *new_p = user_alloc_internal(thr, pc, sz);
  270. if (new_p) {
  271. uptr old_sz = user_alloc_usable_size(p);
  272. internal_memcpy(new_p, p, min(old_sz, sz));
  273. user_free(thr, pc, p);
  274. }
  275. return SetErrnoOnNull(new_p);
  276. }
  277. void *user_memalign(ThreadState *thr, uptr pc, uptr align, uptr sz) {
  278. if (UNLIKELY(!IsPowerOfTwo(align))) {
  279. errno = errno_EINVAL;
  280. if (AllocatorMayReturnNull())
  281. return nullptr;
  282. GET_STACK_TRACE_FATAL(thr, pc);
  283. ReportInvalidAllocationAlignment(align, &stack);
  284. }
  285. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, align));
  286. }
  287. int user_posix_memalign(ThreadState *thr, uptr pc, void **memptr, uptr align,
  288. uptr sz) {
  289. if (UNLIKELY(!CheckPosixMemalignAlignment(align))) {
  290. if (AllocatorMayReturnNull())
  291. return errno_EINVAL;
  292. GET_STACK_TRACE_FATAL(thr, pc);
  293. ReportInvalidPosixMemalignAlignment(align, &stack);
  294. }
  295. void *ptr = user_alloc_internal(thr, pc, sz, align);
  296. if (UNLIKELY(!ptr))
  297. // OOM error is already taken care of by user_alloc_internal.
  298. return errno_ENOMEM;
  299. CHECK(IsAligned((uptr)ptr, align));
  300. *memptr = ptr;
  301. return 0;
  302. }
  303. void *user_aligned_alloc(ThreadState *thr, uptr pc, uptr align, uptr sz) {
  304. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(align, sz))) {
  305. errno = errno_EINVAL;
  306. if (AllocatorMayReturnNull())
  307. return nullptr;
  308. GET_STACK_TRACE_FATAL(thr, pc);
  309. ReportInvalidAlignedAllocAlignment(sz, align, &stack);
  310. }
  311. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, align));
  312. }
  313. void *user_valloc(ThreadState *thr, uptr pc, uptr sz) {
  314. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, GetPageSizeCached()));
  315. }
  316. void *user_pvalloc(ThreadState *thr, uptr pc, uptr sz) {
  317. uptr PageSize = GetPageSizeCached();
  318. if (UNLIKELY(CheckForPvallocOverflow(sz, PageSize))) {
  319. errno = errno_ENOMEM;
  320. if (AllocatorMayReturnNull())
  321. return nullptr;
  322. GET_STACK_TRACE_FATAL(thr, pc);
  323. ReportPvallocOverflow(sz, &stack);
  324. }
  325. // pvalloc(0) should allocate one page.
  326. sz = sz ? RoundUpTo(sz, PageSize) : PageSize;
  327. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, PageSize));
  328. }
  329. uptr user_alloc_usable_size(const void *p) {
  330. if (p == 0 || !IsAppMem((uptr)p))
  331. return 0;
  332. MBlock *b = ctx->metamap.GetBlock((uptr)p);
  333. if (!b)
  334. return 0; // Not a valid pointer.
  335. if (b->siz == 0)
  336. return 1; // Zero-sized allocations are actually 1 byte.
  337. return b->siz;
  338. }
  339. void invoke_malloc_hook(void *ptr, uptr size) {
  340. ThreadState *thr = cur_thread();
  341. if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
  342. return;
  343. __sanitizer_malloc_hook(ptr, size);
  344. RunMallocHooks(ptr, size);
  345. }
  346. void invoke_free_hook(void *ptr) {
  347. ThreadState *thr = cur_thread();
  348. if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
  349. return;
  350. __sanitizer_free_hook(ptr);
  351. RunFreeHooks(ptr);
  352. }
  353. void *Alloc(uptr sz) {
  354. ThreadState *thr = cur_thread();
  355. if (thr->nomalloc) {
  356. thr->nomalloc = 0; // CHECK calls internal_malloc().
  357. CHECK(0);
  358. }
  359. InternalAllocAccess();
  360. return InternalAlloc(sz, &thr->proc()->internal_alloc_cache);
  361. }
  362. void FreeImpl(void *p) {
  363. ThreadState *thr = cur_thread();
  364. if (thr->nomalloc) {
  365. thr->nomalloc = 0; // CHECK calls internal_malloc().
  366. CHECK(0);
  367. }
  368. InternalAllocAccess();
  369. InternalFree(p, &thr->proc()->internal_alloc_cache);
  370. }
  371. } // namespace __tsan
  372. using namespace __tsan;
  373. extern "C" {
  374. uptr __sanitizer_get_current_allocated_bytes() {
  375. uptr stats[AllocatorStatCount];
  376. allocator()->GetStats(stats);
  377. return stats[AllocatorStatAllocated];
  378. }
  379. uptr __sanitizer_get_heap_size() {
  380. uptr stats[AllocatorStatCount];
  381. allocator()->GetStats(stats);
  382. return stats[AllocatorStatMapped];
  383. }
  384. uptr __sanitizer_get_free_bytes() {
  385. return 1;
  386. }
  387. uptr __sanitizer_get_unmapped_bytes() {
  388. return 1;
  389. }
  390. uptr __sanitizer_get_estimated_allocated_size(uptr size) {
  391. return size;
  392. }
  393. int __sanitizer_get_ownership(const void *p) {
  394. return allocator()->GetBlockBegin(p) != 0;
  395. }
  396. uptr __sanitizer_get_allocated_size(const void *p) {
  397. return user_alloc_usable_size(p);
  398. }
  399. void __tsan_on_thread_idle() {
  400. ThreadState *thr = cur_thread();
  401. allocator()->SwallowCache(&thr->proc()->alloc_cache);
  402. internal_allocator()->SwallowCache(&thr->proc()->internal_alloc_cache);
  403. ctx->metamap.OnProcIdle(thr->proc());
  404. }
  405. } // extern "C"