1 //===-- tsan_mman.cc ------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
12 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common/sanitizer_allocator_interface.h"
14 #include "sanitizer_common/sanitizer_common.h"
15 #include "sanitizer_common/sanitizer_placement_new.h"
16 #include "tsan_mman.h"
18 #include "tsan_report.h"
19 #include "tsan_flags.h"
21 // May be overriden by front-end.
22 SANITIZER_WEAK_DEFAULT_IMPL
23 void __sanitizer_malloc_hook(void *ptr, uptr size) {
28 SANITIZER_WEAK_DEFAULT_IMPL
29 void __sanitizer_free_hook(void *ptr) {
35 struct MapUnmapCallback {
36 void OnMap(uptr p, uptr size) const { }
37 void OnUnmap(uptr p, uptr size) const {
38 // We are about to unmap a chunk of user memory.
39 // Mark the corresponding shadow memory as not needed.
40 DontNeedShadowFor(p, size);
41 // Mark the corresponding meta shadow memory as not needed.
42 // Note the block does not contain any meta info at this point
43 // (this happens after free).
44 const uptr kMetaRatio = kMetaShadowCell / kMetaShadowSize;
45 const uptr kPageSize = GetPageSizeCached() * kMetaRatio;
46 // Block came from LargeMmapAllocator, so must be large.
47 // We rely on this in the calculations below.
48 CHECK_GE(size, 2 * kPageSize);
49 uptr diff = RoundUp(p, kPageSize) - p;
54 diff = p + size - RoundDown(p + size, kPageSize);
57 uptr p_meta = (uptr)MemToMeta(p);
58 ReleaseMemoryPagesToOS(p_meta, p_meta + size / kMetaRatio);
62 static char allocator_placeholder[sizeof(Allocator)] ALIGNED(64);
63 Allocator *allocator() {
64 return reinterpret_cast<Allocator*>(&allocator_placeholder);
72 : mtx(MutexTypeGlobalProc, StatMtxGlobalProc)
73 , proc(ProcCreate()) {
77 static char global_proc_placeholder[sizeof(GlobalProc)] ALIGNED(64);
78 GlobalProc *global_proc() {
79 return reinterpret_cast<GlobalProc*>(&global_proc_placeholder);
82 ScopedGlobalProcessor::ScopedGlobalProcessor() {
83 GlobalProc *gp = global_proc();
84 ThreadState *thr = cur_thread();
87 // If we don't have a proc, use the global one.
88 // There are currently only two known case where this path is triggered:
90 // __nptl_deallocate_tsd
95 // __interceptor_munmap
99 // Ideally, we destroy thread state (and unwire proc) when a thread actually
100 // exits (i.e. when we join/wait it). Then we would not need the global proc
102 ProcWire(gp->proc, thr);
105 ScopedGlobalProcessor::~ScopedGlobalProcessor() {
106 GlobalProc *gp = global_proc();
107 ThreadState *thr = cur_thread();
108 if (thr->proc() != gp->proc)
110 ProcUnwire(gp->proc, thr);
114 void InitializeAllocator() {
115 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
116 allocator()->Init(common_flags()->allocator_release_to_os_interval_ms);
119 void InitializeAllocatorLate() {
120 new(global_proc()) GlobalProc();
123 void AllocatorProcStart(Processor *proc) {
124 allocator()->InitCache(&proc->alloc_cache);
125 internal_allocator()->InitCache(&proc->internal_alloc_cache);
128 void AllocatorProcFinish(Processor *proc) {
129 allocator()->DestroyCache(&proc->alloc_cache);
130 internal_allocator()->DestroyCache(&proc->internal_alloc_cache);
133 void AllocatorPrintStats() {
134 allocator()->PrintStats();
137 static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
138 if (atomic_load_relaxed(&thr->in_signal_handler) == 0 ||
139 !flags()->report_signal_unsafe)
141 VarSizeStackTrace stack;
142 ObtainCurrentStack(thr, pc, &stack);
143 if (IsFiredSuppression(ctx, ReportTypeSignalUnsafe, stack))
145 ThreadRegistryLock l(ctx->thread_registry);
146 ScopedReport rep(ReportTypeSignalUnsafe);
147 rep.AddStack(stack, true);
148 OutputReport(thr, rep);
151 void *user_alloc(ThreadState *thr, uptr pc, uptr sz, uptr align, bool signal) {
152 if ((sz >= (1ull << 40)) || (align >= (1ull << 40)))
153 return Allocator::FailureHandler::OnBadRequest();
154 void *p = allocator()->Allocate(&thr->proc()->alloc_cache, sz, align);
157 if (ctx && ctx->initialized)
158 OnUserAlloc(thr, pc, (uptr)p, sz, true);
160 SignalUnsafeCall(thr, pc);
164 void *user_calloc(ThreadState *thr, uptr pc, uptr size, uptr n) {
165 if (CallocShouldReturnNullDueToOverflow(size, n))
166 return Allocator::FailureHandler::OnBadRequest();
167 void *p = user_alloc(thr, pc, n * size);
169 internal_memset(p, 0, n * size);
173 void user_free(ThreadState *thr, uptr pc, void *p, bool signal) {
174 ScopedGlobalProcessor sgp;
175 if (ctx && ctx->initialized)
176 OnUserFree(thr, pc, (uptr)p, true);
177 allocator()->Deallocate(&thr->proc()->alloc_cache, p);
179 SignalUnsafeCall(thr, pc);
182 void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write) {
183 DPrintf("#%d: alloc(%zu) = %p\n", thr->tid, sz, p);
184 ctx->metamap.AllocBlock(thr, pc, p, sz);
185 if (write && thr->ignore_reads_and_writes == 0)
186 MemoryRangeImitateWrite(thr, pc, (uptr)p, sz);
188 MemoryResetRange(thr, pc, (uptr)p, sz);
191 void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write) {
192 CHECK_NE(p, (void*)0);
193 uptr sz = ctx->metamap.FreeBlock(thr->proc(), p);
194 DPrintf("#%d: free(%p, %zu)\n", thr->tid, p, sz);
195 if (write && thr->ignore_reads_and_writes == 0)
196 MemoryRangeFreed(thr, pc, (uptr)p, sz);
199 void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) {
200 // FIXME: Handle "shrinking" more efficiently,
201 // it seems that some software actually does this.
202 void *p2 = user_alloc(thr, pc, sz);
206 uptr oldsz = user_alloc_usable_size(p);
207 internal_memcpy(p2, p, min(oldsz, sz));
208 user_free(thr, pc, p);
213 uptr user_alloc_usable_size(const void *p) {
216 MBlock *b = ctx->metamap.GetBlock((uptr)p);
218 return 0; // Not a valid pointer.
220 return 1; // Zero-sized allocations are actually 1 byte.
224 void invoke_malloc_hook(void *ptr, uptr size) {
225 ThreadState *thr = cur_thread();
226 if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
228 __sanitizer_malloc_hook(ptr, size);
229 RunMallocHooks(ptr, size);
232 void invoke_free_hook(void *ptr) {
233 ThreadState *thr = cur_thread();
234 if (ctx == 0 || !ctx->initialized || thr->ignore_interceptors)
236 __sanitizer_free_hook(ptr);
240 void *internal_alloc(MBlockType typ, uptr sz) {
241 ThreadState *thr = cur_thread();
243 thr->nomalloc = 0; // CHECK calls internal_malloc().
246 return InternalAlloc(sz, &thr->proc()->internal_alloc_cache);
249 void internal_free(void *p) {
250 ThreadState *thr = cur_thread();
252 thr->nomalloc = 0; // CHECK calls internal_malloc().
255 InternalFree(p, &thr->proc()->internal_alloc_cache);
258 } // namespace __tsan
260 using namespace __tsan;
263 uptr __sanitizer_get_current_allocated_bytes() {
264 uptr stats[AllocatorStatCount];
265 allocator()->GetStats(stats);
266 return stats[AllocatorStatAllocated];
269 uptr __sanitizer_get_heap_size() {
270 uptr stats[AllocatorStatCount];
271 allocator()->GetStats(stats);
272 return stats[AllocatorStatMapped];
275 uptr __sanitizer_get_free_bytes() {
279 uptr __sanitizer_get_unmapped_bytes() {
283 uptr __sanitizer_get_estimated_allocated_size(uptr size) {
287 int __sanitizer_get_ownership(const void *p) {
288 return allocator()->GetBlockBegin(p) != 0;
291 uptr __sanitizer_get_allocated_size(const void *p) {
292 return user_alloc_usable_size(p);
295 void __tsan_on_thread_idle() {
296 ThreadState *thr = cur_thread();
297 allocator()->SwallowCache(&thr->proc()->alloc_cache);
298 internal_allocator()->SwallowCache(&thr->proc()->internal_alloc_cache);
299 ctx->metamap.OnProcIdle(thr->proc());