tsan_mman.cpp 14 KB

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