tsan_mman.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. GlobalProc() : mtx(MutexTypeGlobalProc), proc(ProcCreate()) {}
  67. };
  68. static char global_proc_placeholder[sizeof(GlobalProc)] ALIGNED(64);
  69. GlobalProc *global_proc() {
  70. return reinterpret_cast<GlobalProc*>(&global_proc_placeholder);
  71. }
  72. ScopedGlobalProcessor::ScopedGlobalProcessor() {
  73. GlobalProc *gp = global_proc();
  74. ThreadState *thr = cur_thread();
  75. if (thr->proc())
  76. return;
  77. // If we don't have a proc, use the global one.
  78. // There are currently only two known case where this path is triggered:
  79. // __interceptor_free
  80. // __nptl_deallocate_tsd
  81. // start_thread
  82. // clone
  83. // and:
  84. // ResetRange
  85. // __interceptor_munmap
  86. // __deallocate_stack
  87. // start_thread
  88. // clone
  89. // Ideally, we destroy thread state (and unwire proc) when a thread actually
  90. // exits (i.e. when we join/wait it). Then we would not need the global proc
  91. gp->mtx.Lock();
  92. ProcWire(gp->proc, thr);
  93. }
  94. ScopedGlobalProcessor::~ScopedGlobalProcessor() {
  95. GlobalProc *gp = global_proc();
  96. ThreadState *thr = cur_thread();
  97. if (thr->proc() != gp->proc)
  98. return;
  99. ProcUnwire(gp->proc, thr);
  100. gp->mtx.Unlock();
  101. }
  102. static constexpr uptr kMaxAllowedMallocSize = 1ull << 40;
  103. static uptr max_user_defined_malloc_size;
  104. void InitializeAllocator() {
  105. SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
  106. allocator()->Init(common_flags()->allocator_release_to_os_interval_ms);
  107. max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
  108. ? common_flags()->max_allocation_size_mb
  109. << 20
  110. : kMaxAllowedMallocSize;
  111. }
  112. void InitializeAllocatorLate() {
  113. new(global_proc()) GlobalProc();
  114. }
  115. void AllocatorProcStart(Processor *proc) {
  116. allocator()->InitCache(&proc->alloc_cache);
  117. internal_allocator()->InitCache(&proc->internal_alloc_cache);
  118. }
  119. void AllocatorProcFinish(Processor *proc) {
  120. allocator()->DestroyCache(&proc->alloc_cache);
  121. internal_allocator()->DestroyCache(&proc->internal_alloc_cache);
  122. }
  123. void AllocatorPrintStats() {
  124. allocator()->PrintStats();
  125. }
  126. static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
  127. if (atomic_load_relaxed(&thr->in_signal_handler) == 0 ||
  128. !ShouldReport(thr, ReportTypeSignalUnsafe))
  129. return;
  130. VarSizeStackTrace stack;
  131. ObtainCurrentStack(thr, pc, &stack);
  132. if (IsFiredSuppression(ctx, ReportTypeSignalUnsafe, stack))
  133. return;
  134. ThreadRegistryLock l(&ctx->thread_registry);
  135. ScopedReport rep(ReportTypeSignalUnsafe);
  136. rep.AddStack(stack, true);
  137. OutputReport(thr, rep);
  138. }
  139. void *user_alloc_internal(ThreadState *thr, uptr pc, uptr sz, uptr align,
  140. bool signal) {
  141. if (sz >= kMaxAllowedMallocSize || align >= kMaxAllowedMallocSize ||
  142. sz > max_user_defined_malloc_size) {
  143. if (AllocatorMayReturnNull())
  144. return nullptr;
  145. uptr malloc_limit =
  146. Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
  147. GET_STACK_TRACE_FATAL(thr, pc);
  148. ReportAllocationSizeTooBig(sz, malloc_limit, &stack);
  149. }
  150. void *p = allocator()->Allocate(&thr->proc()->alloc_cache, sz, align);
  151. if (UNLIKELY(!p)) {
  152. SetAllocatorOutOfMemory();
  153. if (AllocatorMayReturnNull())
  154. return nullptr;
  155. GET_STACK_TRACE_FATAL(thr, pc);
  156. ReportOutOfMemory(sz, &stack);
  157. }
  158. if (ctx && ctx->initialized)
  159. OnUserAlloc(thr, pc, (uptr)p, sz, true);
  160. if (signal)
  161. SignalUnsafeCall(thr, pc);
  162. return p;
  163. }
  164. void user_free(ThreadState *thr, uptr pc, void *p, bool signal) {
  165. ScopedGlobalProcessor sgp;
  166. if (ctx && ctx->initialized)
  167. OnUserFree(thr, pc, (uptr)p, true);
  168. allocator()->Deallocate(&thr->proc()->alloc_cache, p);
  169. if (signal)
  170. SignalUnsafeCall(thr, pc);
  171. }
  172. void *user_alloc(ThreadState *thr, uptr pc, uptr sz) {
  173. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, kDefaultAlignment));
  174. }
  175. void *user_calloc(ThreadState *thr, uptr pc, uptr size, uptr n) {
  176. if (UNLIKELY(CheckForCallocOverflow(size, n))) {
  177. if (AllocatorMayReturnNull())
  178. return SetErrnoOnNull(nullptr);
  179. GET_STACK_TRACE_FATAL(thr, pc);
  180. ReportCallocOverflow(n, size, &stack);
  181. }
  182. void *p = user_alloc_internal(thr, pc, n * size);
  183. if (p)
  184. internal_memset(p, 0, n * size);
  185. return SetErrnoOnNull(p);
  186. }
  187. void *user_reallocarray(ThreadState *thr, uptr pc, void *p, uptr size, uptr n) {
  188. if (UNLIKELY(CheckForCallocOverflow(size, n))) {
  189. if (AllocatorMayReturnNull())
  190. return SetErrnoOnNull(nullptr);
  191. GET_STACK_TRACE_FATAL(thr, pc);
  192. ReportReallocArrayOverflow(size, n, &stack);
  193. }
  194. return user_realloc(thr, pc, p, size * n);
  195. }
  196. void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write) {
  197. DPrintf("#%d: alloc(%zu) = 0x%zx\n", thr->tid, sz, p);
  198. ctx->metamap.AllocBlock(thr, pc, p, sz);
  199. if (write && thr->ignore_reads_and_writes == 0)
  200. MemoryRangeImitateWrite(thr, pc, (uptr)p, sz);
  201. else
  202. MemoryResetRange(thr, pc, (uptr)p, sz);
  203. }
  204. void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write) {
  205. CHECK_NE(p, (void*)0);
  206. uptr sz = ctx->metamap.FreeBlock(thr->proc(), p);
  207. DPrintf("#%d: free(0x%zx, %zu)\n", thr->tid, p, sz);
  208. if (write && thr->ignore_reads_and_writes == 0)
  209. MemoryRangeFreed(thr, pc, (uptr)p, sz);
  210. }
  211. void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) {
  212. // FIXME: Handle "shrinking" more efficiently,
  213. // it seems that some software actually does this.
  214. if (!p)
  215. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz));
  216. if (!sz) {
  217. user_free(thr, pc, p);
  218. return nullptr;
  219. }
  220. void *new_p = user_alloc_internal(thr, pc, sz);
  221. if (new_p) {
  222. uptr old_sz = user_alloc_usable_size(p);
  223. internal_memcpy(new_p, p, min(old_sz, sz));
  224. user_free(thr, pc, p);
  225. }
  226. return SetErrnoOnNull(new_p);
  227. }
  228. void *user_memalign(ThreadState *thr, uptr pc, uptr align, uptr sz) {
  229. if (UNLIKELY(!IsPowerOfTwo(align))) {
  230. errno = errno_EINVAL;
  231. if (AllocatorMayReturnNull())
  232. return nullptr;
  233. GET_STACK_TRACE_FATAL(thr, pc);
  234. ReportInvalidAllocationAlignment(align, &stack);
  235. }
  236. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, align));
  237. }
  238. int user_posix_memalign(ThreadState *thr, uptr pc, void **memptr, uptr align,
  239. uptr sz) {
  240. if (UNLIKELY(!CheckPosixMemalignAlignment(align))) {
  241. if (AllocatorMayReturnNull())
  242. return errno_EINVAL;
  243. GET_STACK_TRACE_FATAL(thr, pc);
  244. ReportInvalidPosixMemalignAlignment(align, &stack);
  245. }
  246. void *ptr = user_alloc_internal(thr, pc, sz, align);
  247. if (UNLIKELY(!ptr))
  248. // OOM error is already taken care of by user_alloc_internal.
  249. return errno_ENOMEM;
  250. CHECK(IsAligned((uptr)ptr, align));
  251. *memptr = ptr;
  252. return 0;
  253. }
  254. void *user_aligned_alloc(ThreadState *thr, uptr pc, uptr align, uptr sz) {
  255. if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(align, sz))) {
  256. errno = errno_EINVAL;
  257. if (AllocatorMayReturnNull())
  258. return nullptr;
  259. GET_STACK_TRACE_FATAL(thr, pc);
  260. ReportInvalidAlignedAllocAlignment(sz, align, &stack);
  261. }
  262. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, align));
  263. }
  264. void *user_valloc(ThreadState *thr, uptr pc, uptr sz) {
  265. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, GetPageSizeCached()));
  266. }
  267. void *user_pvalloc(ThreadState *thr, uptr pc, uptr sz) {
  268. uptr PageSize = GetPageSizeCached();
  269. if (UNLIKELY(CheckForPvallocOverflow(sz, PageSize))) {
  270. errno = errno_ENOMEM;
  271. if (AllocatorMayReturnNull())
  272. return nullptr;
  273. GET_STACK_TRACE_FATAL(thr, pc);
  274. ReportPvallocOverflow(sz, &stack);
  275. }
  276. // pvalloc(0) should allocate one page.
  277. sz = sz ? RoundUpTo(sz, PageSize) : PageSize;
  278. return SetErrnoOnNull(user_alloc_internal(thr, pc, sz, PageSize));
  279. }
  280. uptr user_alloc_usable_size(const void *p) {
  281. if (p == 0)
  282. return 0;
  283. MBlock *b = ctx->metamap.GetBlock((uptr)p);
  284. if (!b)
  285. return 0; // Not a valid pointer.
  286. if (b->siz == 0)
  287. return 1; // Zero-sized allocations are actually 1 byte.
  288. return b->siz;
  289. }
  290. void invoke_malloc_hook(void *ptr, uptr size) {
  291. ThreadState *thr = cur_thread();
  292. if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
  293. return;
  294. __sanitizer_malloc_hook(ptr, size);
  295. RunMallocHooks(ptr, size);
  296. }
  297. void invoke_free_hook(void *ptr) {
  298. ThreadState *thr = cur_thread();
  299. if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
  300. return;
  301. __sanitizer_free_hook(ptr);
  302. RunFreeHooks(ptr);
  303. }
  304. void *Alloc(uptr sz) {
  305. ThreadState *thr = cur_thread();
  306. if (thr->nomalloc) {
  307. thr->nomalloc = 0; // CHECK calls internal_malloc().
  308. CHECK(0);
  309. }
  310. return InternalAlloc(sz, &thr->proc()->internal_alloc_cache);
  311. }
  312. void FreeImpl(void *p) {
  313. ThreadState *thr = cur_thread();
  314. if (thr->nomalloc) {
  315. thr->nomalloc = 0; // CHECK calls internal_malloc().
  316. CHECK(0);
  317. }
  318. InternalFree(p, &thr->proc()->internal_alloc_cache);
  319. }
  320. } // namespace __tsan
  321. using namespace __tsan;
  322. extern "C" {
  323. uptr __sanitizer_get_current_allocated_bytes() {
  324. uptr stats[AllocatorStatCount];
  325. allocator()->GetStats(stats);
  326. return stats[AllocatorStatAllocated];
  327. }
  328. uptr __sanitizer_get_heap_size() {
  329. uptr stats[AllocatorStatCount];
  330. allocator()->GetStats(stats);
  331. return stats[AllocatorStatMapped];
  332. }
  333. uptr __sanitizer_get_free_bytes() {
  334. return 1;
  335. }
  336. uptr __sanitizer_get_unmapped_bytes() {
  337. return 1;
  338. }
  339. uptr __sanitizer_get_estimated_allocated_size(uptr size) {
  340. return size;
  341. }
  342. int __sanitizer_get_ownership(const void *p) {
  343. return allocator()->GetBlockBegin(p) != 0;
  344. }
  345. uptr __sanitizer_get_allocated_size(const void *p) {
  346. return user_alloc_usable_size(p);
  347. }
  348. void __tsan_on_thread_idle() {
  349. ThreadState *thr = cur_thread();
  350. thr->clock.ResetCached(&thr->proc()->clock_cache);
  351. thr->last_sleep_clock.ResetCached(&thr->proc()->clock_cache);
  352. allocator()->SwallowCache(&thr->proc()->alloc_cache);
  353. internal_allocator()->SwallowCache(&thr->proc()->internal_alloc_cache);
  354. ctx->metamap.OnProcIdle(thr->proc());
  355. }
  356. } // extern "C"