tsan_mman.cpp 15 KB

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