1 //===-- tsan_rtl.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 // Main file (entry points) for the TSan run-time.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_atomic.h"
16 #include "sanitizer_common/sanitizer_common.h"
17 #include "sanitizer_common/sanitizer_file.h"
18 #include "sanitizer_common/sanitizer_libc.h"
19 #include "sanitizer_common/sanitizer_stackdepot.h"
20 #include "sanitizer_common/sanitizer_placement_new.h"
21 #include "sanitizer_common/sanitizer_symbolizer.h"
22 #include "tsan_defs.h"
23 #include "tsan_platform.h"
25 #include "tsan_mman.h"
26 #include "tsan_suppressions.h"
27 #include "tsan_symbolize.h"
28 #include "ubsan/ubsan_init.h"
31 // <emmintrin.h> transitively includes <stdlib.h>,
32 // and it's prohibited to include std headers into tsan runtime.
33 // So we do this dirty trick.
34 #define _MM_MALLOC_H_INCLUDED
36 #include <emmintrin.h>
40 volatile int __tsan_resumed = 0;
42 extern "C" void __tsan_resume() {
48 #if !SANITIZER_GO && !SANITIZER_MAC
49 __attribute__((tls_model("initial-exec")))
50 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
52 static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
55 // Can be overriden by a front-end.
56 #ifdef TSAN_EXTERNAL_HOOKS
57 bool OnFinalize(bool failed);
60 SANITIZER_WEAK_CXX_DEFAULT_IMPL
61 bool OnFinalize(bool failed) {
64 SANITIZER_WEAK_CXX_DEFAULT_IMPL
65 void OnInitialize() {}
68 static char thread_registry_placeholder[sizeof(ThreadRegistry)];
70 static ThreadContextBase *CreateThreadContext(u32 tid) {
71 // Map thread trace when context is created.
73 internal_snprintf(name, sizeof(name), "trace %u", tid);
74 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
75 const uptr hdr = GetThreadTraceHeader(tid);
76 internal_snprintf(name, sizeof(name), "trace header %u", tid);
77 MapThreadTrace(hdr, sizeof(Trace), name);
78 new((void*)hdr) Trace();
79 // We are going to use only a small part of the trace with the default
80 // value of history_size. However, the constructor writes to the whole trace.
81 // Unmap the unused part.
82 uptr hdr_end = hdr + sizeof(Trace);
83 hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
84 hdr_end = RoundUp(hdr_end, GetPageSizeCached());
85 if (hdr_end < hdr + sizeof(Trace))
86 UnmapOrDie((void*)hdr_end, hdr + sizeof(Trace) - hdr_end);
87 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
88 return new(mem) ThreadContext(tid);
92 static const u32 kThreadQuarantineSize = 16;
94 static const u32 kThreadQuarantineSize = 64;
99 , report_mtx(MutexTypeReport, StatMtxReport)
102 , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
103 CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
104 , racy_mtx(MutexTypeRacy, StatMtxRacy)
107 , fired_suppressions_mtx(MutexTypeFired, StatMtxFired)
108 , clock_alloc("clock allocator") {
109 fired_suppressions.reserve(8);
112 // The objects are allocated in TLS, so one may rely on zero-initialization.
113 ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
114 unsigned reuse_count,
115 uptr stk_addr, uptr stk_size,
116 uptr tls_addr, uptr tls_size)
117 : fast_state(tid, epoch)
118 // Do not touch these, rely on zero initialization,
119 // they may be accessed before the ctor.
120 // , ignore_reads_and_writes()
121 // , ignore_interceptors()
122 , clock(tid, reuse_count)
127 , unique_id(unique_id)
133 , last_sleep_clock(tid)
139 static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
141 uptr n_running_threads;
142 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
143 InternalMmapVector<char> buf(4096);
144 WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
145 WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
148 static void BackgroundThread(void *arg) {
149 // This is a non-initialized non-user thread, nothing to see here.
150 // We don't use ScopedIgnoreInterceptors, because we want ignores to be
151 // enabled even when the thread function exits (e.g. during pthread thread
153 cur_thread()->ignore_interceptors++;
154 const u64 kMs2Ns = 1000 * 1000;
156 fd_t mprof_fd = kInvalidFd;
157 if (flags()->profile_memory && flags()->profile_memory[0]) {
158 if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
160 } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
163 InternalScopedString filename(kMaxPathLength);
164 filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
165 fd_t fd = OpenFile(filename.data(), WrOnly);
166 if (fd == kInvalidFd) {
167 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
175 u64 last_flush = NanoTime();
178 atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
181 u64 now = NanoTime();
183 // Flush memory if requested.
184 if (flags()->flush_memory_ms > 0) {
185 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
186 VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
188 last_flush = NanoTime();
191 // GetRSS can be expensive on huge programs, so don't do it every 100ms.
192 if (flags()->memory_limit_mb > 0) {
194 uptr limit = uptr(flags()->memory_limit_mb) << 20;
195 VPrintf(1, "ThreadSanitizer: memory flush check"
196 " RSS=%llu LAST=%llu LIMIT=%llu\n",
197 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
198 if (2 * rss > limit + last_rss) {
199 VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
202 VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
207 // Write memory profile if requested.
208 if (mprof_fd != kInvalidFd)
209 MemoryProfiler(ctx, mprof_fd, i);
211 // Flush symbolizer cache if requested.
212 if (flags()->flush_symbolizer_ms > 0) {
213 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
214 memory_order_relaxed);
215 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
216 Lock l(&ctx->report_mtx);
217 ScopedErrorReportLock l2;
219 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
225 static void StartBackgroundThread() {
226 ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
230 static void StopBackgroundThread() {
231 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
232 internal_join_thread(ctx->background_thread);
233 ctx->background_thread = 0;
238 void DontNeedShadowFor(uptr addr, uptr size) {
239 ReleaseMemoryPagesToOS(MemToShadow(addr), MemToShadow(addr + size));
242 void MapShadow(uptr addr, uptr size) {
243 // Global data is not 64K aligned, but there are no adjacent mappings,
244 // so we can get away with unaligned mapping.
245 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
246 const uptr kPageSize = GetPageSizeCached();
247 uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
248 uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
249 if (!MmapFixedNoReserve(shadow_begin, shadow_end - shadow_begin, "shadow"))
252 // Meta shadow is 2:1, so tread carefully.
253 static bool data_mapped = false;
254 static uptr mapped_meta_end = 0;
255 uptr meta_begin = (uptr)MemToMeta(addr);
256 uptr meta_end = (uptr)MemToMeta(addr + size);
257 meta_begin = RoundDownTo(meta_begin, 64 << 10);
258 meta_end = RoundUpTo(meta_end, 64 << 10);
260 // First call maps data+bss.
262 if (!MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow"))
265 // Mapping continous heap.
266 // Windows wants 64K alignment.
267 meta_begin = RoundDownTo(meta_begin, 64 << 10);
268 meta_end = RoundUpTo(meta_end, 64 << 10);
269 if (meta_end <= mapped_meta_end)
271 if (meta_begin < mapped_meta_end)
272 meta_begin = mapped_meta_end;
273 if (!MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow"))
275 mapped_meta_end = meta_end;
277 VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n",
278 addr, addr+size, meta_begin, meta_end);
281 void MapThreadTrace(uptr addr, uptr size, const char *name) {
282 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
283 CHECK_GE(addr, TraceMemBeg());
284 CHECK_LE(addr + size, TraceMemEnd());
285 CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
286 if (!MmapFixedNoReserve(addr, size, name)) {
287 Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p)\n",
293 static void CheckShadowMapping() {
295 for (int i = 0; GetUserRegion(i, &beg, &end); i++) {
296 // Skip cases for empty regions (heap definition for architectures that
297 // do not use 64-bit allocator).
300 VPrintf(3, "checking shadow region %p-%p\n", beg, end);
302 for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) {
303 for (int x = -(int)kShadowCell; x <= (int)kShadowCell; x += kShadowCell) {
304 const uptr p = RoundDown(p0 + x, kShadowCell);
305 if (p < beg || p >= end)
307 const uptr s = MemToShadow(p);
308 const uptr m = (uptr)MemToMeta(p);
309 VPrintf(3, " checking pointer %p: shadow=%p meta=%p\n", p, s, m);
311 CHECK(IsShadowMem(s));
312 CHECK_EQ(p, ShadowToMem(s));
315 // Ensure that shadow and meta mappings are linear within a single
316 // user range. Lots of code that processes memory ranges assumes it.
317 const uptr prev_s = MemToShadow(prev);
318 const uptr prev_m = (uptr)MemToMeta(prev);
319 CHECK_EQ(s - prev_s, (p - prev) * kShadowMultiplier);
320 CHECK_EQ((m - prev_m) / kMetaShadowSize,
321 (p - prev) / kMetaShadowCell);
330 static void OnStackUnwind(const SignalContext &sig, const void *,
331 BufferedStackTrace *stack) {
334 bool fast = common_flags()->fast_unwind_on_fatal;
335 if (fast) GetThreadStackTopAndBottom(false, &top, &bottom);
336 stack->Unwind(kStackTraceMax, sig.pc, sig.bp, sig.context, top, bottom, fast);
339 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
340 HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
344 void Initialize(ThreadState *thr) {
345 // Thread safe because done before all threads exist.
346 static bool is_initialized = false;
349 is_initialized = true;
350 // We are not ready to handle interceptors yet.
351 ScopedIgnoreInterceptors ignore;
352 SanitizerToolName = "ThreadSanitizer";
353 // Install tool-specific callbacks in sanitizer_common.
354 SetCheckFailedCallback(TsanCheckFailed);
356 ctx = new(ctx_placeholder) Context;
357 const char *options = GetEnv(SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS");
360 InitializeFlags(&ctx->flags, options);
361 AvoidCVE_2016_2143();
362 __sanitizer::InitializePlatformEarly();
363 __tsan::InitializePlatformEarly();
366 // Re-exec ourselves if we need to set additional env or command line args.
369 InitializeAllocator();
370 ReplaceSystemMalloc();
372 if (common_flags()->detect_deadlocks)
373 ctx->dd = DDetector::Create(flags());
374 Processor *proc = ProcCreate();
376 InitializeInterceptors();
377 CheckShadowMapping();
378 InitializePlatform();
380 InitializeDynamicAnnotations();
382 InitializeShadowMemory();
383 InitializeAllocatorLate();
384 InstallDeadlySignalHandlers(TsanOnDeadlySignal);
386 // Setup correct file descriptor for error reports.
387 __sanitizer_set_report_path(common_flags()->log_path);
388 InitializeSuppressions();
390 InitializeLibIgnore();
391 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
394 VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
395 (int)internal_getpid());
397 // Initialize thread 0.
398 int tid = ThreadCreate(thr, 0, 0, true);
400 ThreadStart(thr, tid, GetTid(), /*workerthread*/ false);
401 #if TSAN_CONTAINS_UBSAN
402 __ubsan::InitAsPlugin();
404 ctx->initialized = true;
407 Symbolizer::LateInitialize();
410 if (flags()->stop_on_start) {
411 Printf("ThreadSanitizer is suspended at startup (pid %d)."
412 " Call __tsan_resume().\n",
413 (int)internal_getpid());
414 while (__tsan_resumed == 0) {}
420 void MaybeSpawnBackgroundThread() {
421 // On MIPS, TSan initialization is run before
422 // __pthread_initialize_minimal_internal() is finished, so we can not spawn
424 #if !SANITIZER_GO && !defined(__mips__)
425 static atomic_uint32_t bg_thread = {};
426 if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
427 atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
428 StartBackgroundThread();
429 SetSandboxingCallback(StopBackgroundThread);
435 int Finalize(ThreadState *thr) {
438 if (common_flags()->print_module_map == 1) PrintModuleMap();
440 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
441 SleepForMillis(flags()->atexit_sleep_ms);
443 // Wait for pending reports.
444 ctx->report_mtx.Lock();
445 { ScopedErrorReportLock l; }
446 ctx->report_mtx.Unlock();
449 if (Verbosity()) AllocatorPrintStats();
454 if (ctx->nreported) {
457 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
459 Printf("Found %d data race(s)\n", ctx->nreported);
463 if (ctx->nmissed_expected) {
465 Printf("ThreadSanitizer: missed %d expected races\n",
466 ctx->nmissed_expected);
469 if (common_flags()->print_suppressions)
470 PrintMatchedSuppressions();
472 if (flags()->print_benign)
473 PrintMatchedBenignRaces();
476 failed = OnFinalize(failed);
478 #if TSAN_COLLECT_STATS
479 StatAggregate(ctx->stat, thr->stat);
480 StatOutput(ctx->stat);
483 return failed ? common_flags()->exitcode : 0;
487 void ForkBefore(ThreadState *thr, uptr pc) {
488 ctx->thread_registry->Lock();
489 ctx->report_mtx.Lock();
492 void ForkParentAfter(ThreadState *thr, uptr pc) {
493 ctx->report_mtx.Unlock();
494 ctx->thread_registry->Unlock();
497 void ForkChildAfter(ThreadState *thr, uptr pc) {
498 ctx->report_mtx.Unlock();
499 ctx->thread_registry->Unlock();
502 ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */);
503 VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
504 " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
506 StartBackgroundThread();
508 // We've just forked a multi-threaded process. We cannot reasonably function
509 // after that (some mutexes may be locked before fork). So just enable
510 // ignores for everything in the hope that we will exec soon.
511 ctx->after_multithreaded_fork = true;
512 thr->ignore_interceptors++;
513 ThreadIgnoreBegin(thr, pc);
514 ThreadIgnoreSyncBegin(thr, pc);
521 void GrowShadowStack(ThreadState *thr) {
522 const int sz = thr->shadow_stack_end - thr->shadow_stack;
523 const int newsz = 2 * sz;
524 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
525 newsz * sizeof(uptr));
526 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
527 internal_free(thr->shadow_stack);
528 thr->shadow_stack = newstack;
529 thr->shadow_stack_pos = newstack + sz;
530 thr->shadow_stack_end = newstack + newsz;
534 u32 CurrentStackId(ThreadState *thr, uptr pc) {
535 if (!thr->is_inited) // May happen during bootstrap.
539 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
541 if (thr->shadow_stack_pos == thr->shadow_stack_end)
542 GrowShadowStack(thr);
544 thr->shadow_stack_pos[0] = pc;
545 thr->shadow_stack_pos++;
547 u32 id = StackDepotPut(
548 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
550 thr->shadow_stack_pos--;
554 void TraceSwitch(ThreadState *thr) {
556 if (ctx->after_multithreaded_fork)
560 Trace *thr_trace = ThreadTrace(thr->tid);
561 Lock l(&thr_trace->mtx);
562 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
563 TraceHeader *hdr = &thr_trace->headers[trace];
564 hdr->epoch0 = thr->fast_state.epoch();
565 ObtainCurrentStack(thr, 0, &hdr->stack0);
566 hdr->mset0 = thr->mset;
570 Trace *ThreadTrace(int tid) {
571 return (Trace*)GetThreadTraceHeader(tid);
574 uptr TraceTopPC(ThreadState *thr) {
575 Event *events = (Event*)GetThreadTrace(thr->tid);
576 uptr pc = events[thr->fast_state.GetTracePos()];
581 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
585 return TraceSize() / kTracePartSize;
589 extern "C" void __tsan_trace_switch() {
590 TraceSwitch(cur_thread());
593 extern "C" void __tsan_report_race() {
594 ReportRace(cur_thread());
599 Shadow LoadShadow(u64 *p) {
600 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
605 void StoreShadow(u64 *sp, u64 s) {
606 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
610 void StoreIfNotYetStored(u64 *sp, u64 *s) {
616 void HandleRace(ThreadState *thr, u64 *shadow_mem,
617 Shadow cur, Shadow old) {
618 thr->racy_state[0] = cur.raw();
619 thr->racy_state[1] = old.raw();
620 thr->racy_shadow_addr = shadow_mem;
622 HACKY_CALL(__tsan_report_race);
628 static inline bool HappensBefore(Shadow old, ThreadState *thr) {
629 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
633 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
634 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
635 u64 *shadow_mem, Shadow cur) {
636 StatInc(thr, StatMop);
637 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
638 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
640 // This potentially can live in an MMX/SSE scratch register.
641 // The required intrinsics are:
642 // __m128i _mm_move_epi64(__m128i*);
643 // _mm_storel_epi64(u64*, __m128i);
644 u64 store_word = cur.raw();
646 // scan all the shadow values and dispatch to 4 categories:
647 // same, replace, candidate and race (see comments below).
648 // we consider only 3 cases regarding access sizes:
649 // equal, intersect and not intersect. initially I considered
650 // larger and smaller as well, it allowed to replace some
651 // 'candidates' with 'same' or 'replace', but I think
652 // it's just not worth it (performance- and complexity-wise).
656 // It release mode we manually unroll the loop,
657 // because empirically gcc generates better code this way.
658 // However, we can't afford unrolling in debug mode, because the function
659 // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
660 // threads, which is not enough for the unrolled loop.
662 for (int idx = 0; idx < 4; idx++) {
663 #include "tsan_update_shadow_word_inl.h"
667 #include "tsan_update_shadow_word_inl.h"
669 #include "tsan_update_shadow_word_inl.h"
671 #include "tsan_update_shadow_word_inl.h"
673 #include "tsan_update_shadow_word_inl.h"
676 // we did not find any races and had already stored
677 // the current access info, so we are done
678 if (LIKELY(store_word == 0))
680 // choose a random candidate slot and replace it
681 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
682 StatInc(thr, StatShadowReplace);
685 HandleRace(thr, shadow_mem, cur, old);
689 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
690 int size, bool kAccessIsWrite, bool kIsAtomic) {
693 int kAccessSizeLog = kSizeLog1;
694 if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
696 kAccessSizeLog = kSizeLog8;
697 } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
699 kAccessSizeLog = kSizeLog4;
700 } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
702 kAccessSizeLog = kSizeLog2;
704 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
711 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
713 for (uptr i = 0; i < kShadowCnt; i++) {
714 Shadow old(LoadShadow(&s[i]));
715 if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
716 old.TidWithIgnore() == cur.TidWithIgnore() &&
717 old.epoch() > sync_epoch &&
718 old.IsAtomic() == cur.IsAtomic() &&
719 old.IsRead() <= cur.IsRead())
725 #if defined(__SSE3__)
726 #define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \
727 _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \
728 (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
730 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
731 // This is an optimized version of ContainsSameAccessSlow.
732 // load current access into access[0:63]
733 const m128 access = _mm_cvtsi64_si128(a);
734 // duplicate high part of access in addr0:
735 // addr0[0:31] = access[32:63]
736 // addr0[32:63] = access[32:63]
737 // addr0[64:95] = access[32:63]
738 // addr0[96:127] = access[32:63]
739 const m128 addr0 = SHUF(access, access, 1, 1, 1, 1);
740 // load 4 shadow slots
741 const m128 shadow0 = _mm_load_si128((__m128i*)s);
742 const m128 shadow1 = _mm_load_si128((__m128i*)s + 1);
743 // load high parts of 4 shadow slots into addr_vect:
744 // addr_vect[0:31] = shadow0[32:63]
745 // addr_vect[32:63] = shadow0[96:127]
746 // addr_vect[64:95] = shadow1[32:63]
747 // addr_vect[96:127] = shadow1[96:127]
748 m128 addr_vect = SHUF(shadow0, shadow1, 1, 3, 1, 3);
750 // set IsRead bit in addr_vect
751 const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
752 const m128 rw_mask = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
753 addr_vect = _mm_or_si128(addr_vect, rw_mask);
755 // addr0 == addr_vect?
756 const m128 addr_res = _mm_cmpeq_epi32(addr0, addr_vect);
757 // epoch1[0:63] = sync_epoch
758 const m128 epoch1 = _mm_cvtsi64_si128(sync_epoch);
759 // epoch[0:31] = sync_epoch[0:31]
760 // epoch[32:63] = sync_epoch[0:31]
761 // epoch[64:95] = sync_epoch[0:31]
762 // epoch[96:127] = sync_epoch[0:31]
763 const m128 epoch = SHUF(epoch1, epoch1, 0, 0, 0, 0);
764 // load low parts of shadow cell epochs into epoch_vect:
765 // epoch_vect[0:31] = shadow0[0:31]
766 // epoch_vect[32:63] = shadow0[64:95]
767 // epoch_vect[64:95] = shadow1[0:31]
768 // epoch_vect[96:127] = shadow1[64:95]
769 const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
770 // epoch_vect >= sync_epoch?
771 const m128 epoch_res = _mm_cmpgt_epi32(epoch_vect, epoch);
772 // addr_res & epoch_res
773 const m128 res = _mm_and_si128(addr_res, epoch_res);
777 // mask[15] = res[127]
778 const int mask = _mm_movemask_epi8(res);
784 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
785 #if defined(__SSE3__)
786 bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
787 // NOTE: this check can fail if the shadow is concurrently mutated
788 // by other threads. But it still can be useful if you modify
789 // ContainsSameAccessFast and want to ensure that it's not completely broken.
790 // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
793 return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
798 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
799 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
800 u64 *shadow_mem = (u64*)MemToShadow(addr);
801 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
802 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
803 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
804 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
805 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
806 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
808 if (!IsAppMem(addr)) {
809 Printf("Access to non app mem %zx\n", addr);
810 DCHECK(IsAppMem(addr));
812 if (!IsShadowMem((uptr)shadow_mem)) {
813 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
814 DCHECK(IsShadowMem((uptr)shadow_mem));
818 if (!SANITIZER_GO && *shadow_mem == kShadowRodata) {
819 // Access to .rodata section, no races here.
820 // Measurements show that it can be 10-20% of all memory accesses.
821 StatInc(thr, StatMop);
822 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
823 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
824 StatInc(thr, StatMopRodata);
828 FastState fast_state = thr->fast_state;
829 if (fast_state.GetIgnoreBit()) {
830 StatInc(thr, StatMop);
831 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
832 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
833 StatInc(thr, StatMopIgnored);
837 Shadow cur(fast_state);
838 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
839 cur.SetWrite(kAccessIsWrite);
840 cur.SetAtomic(kIsAtomic);
842 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
843 thr->fast_synch_epoch, kAccessIsWrite))) {
844 StatInc(thr, StatMop);
845 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
846 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
847 StatInc(thr, StatMopSame);
851 if (kCollectHistory) {
852 fast_state.IncrementEpoch();
853 thr->fast_state = fast_state;
854 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
855 cur.IncrementEpoch();
858 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
862 // Called by MemoryAccessRange in tsan_rtl_thread.cc
864 void MemoryAccessImpl(ThreadState *thr, uptr addr,
865 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
866 u64 *shadow_mem, Shadow cur) {
867 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
868 thr->fast_synch_epoch, kAccessIsWrite))) {
869 StatInc(thr, StatMop);
870 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
871 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
872 StatInc(thr, StatMopSame);
876 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
880 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
887 uptr offset = addr % kShadowCell;
889 offset = kShadowCell - offset;
895 DCHECK_EQ(addr % 8, 0);
896 // If a user passes some insane arguments (memset(0)),
897 // let it just crash as usual.
898 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
900 // Don't want to touch lots of shadow memory.
901 // If a program maps 10MB stack, there is no need reset the whole range.
902 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
903 // UnmapOrDie/MmapFixedNoReserve does not work on Windows.
904 if (SANITIZER_WINDOWS || size < common_flags()->clear_shadow_mmap_threshold) {
905 u64 *p = (u64*)MemToShadow(addr);
906 CHECK(IsShadowMem((uptr)p));
907 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
908 // FIXME: may overwrite a part outside the region
909 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
911 for (uptr j = 1; j < kShadowCnt; j++)
915 // The region is big, reset only beginning and end.
916 const uptr kPageSize = GetPageSizeCached();
917 u64 *begin = (u64*)MemToShadow(addr);
918 u64 *end = begin + size / kShadowCell * kShadowCnt;
920 // Set at least first kPageSize/2 to page boundary.
921 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
923 for (uptr j = 1; j < kShadowCnt; j++)
926 // Reset middle part.
928 p = RoundDown(end, kPageSize);
929 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
930 if (!MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1))
935 for (uptr j = 1; j < kShadowCnt; j++)
941 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
942 MemoryRangeSet(thr, pc, addr, size, 0);
945 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
946 // Processing more than 1k (4k of shadow) is expensive,
947 // can cause excessive memory consumption (user does not necessary touch
948 // the whole range) and most likely unnecessary.
951 CHECK_EQ(thr->is_freeing, false);
952 thr->is_freeing = true;
953 MemoryAccessRange(thr, pc, addr, size, true);
954 thr->is_freeing = false;
955 if (kCollectHistory) {
956 thr->fast_state.IncrementEpoch();
957 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
959 Shadow s(thr->fast_state);
963 s.SetAddr0AndSizeLog(0, 3);
964 MemoryRangeSet(thr, pc, addr, size, s.raw());
967 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
968 if (kCollectHistory) {
969 thr->fast_state.IncrementEpoch();
970 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
972 Shadow s(thr->fast_state);
975 s.SetAddr0AndSizeLog(0, 3);
976 MemoryRangeSet(thr, pc, addr, size, s.raw());
980 void FuncEntry(ThreadState *thr, uptr pc) {
981 StatInc(thr, StatFuncEnter);
982 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
983 if (kCollectHistory) {
984 thr->fast_state.IncrementEpoch();
985 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
988 // Shadow stack maintenance can be replaced with
989 // stack unwinding during trace switch (which presumably must be faster).
990 DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
992 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
994 if (thr->shadow_stack_pos == thr->shadow_stack_end)
995 GrowShadowStack(thr);
997 thr->shadow_stack_pos[0] = pc;
998 thr->shadow_stack_pos++;
1002 void FuncExit(ThreadState *thr) {
1003 StatInc(thr, StatFuncExit);
1004 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
1005 if (kCollectHistory) {
1006 thr->fast_state.IncrementEpoch();
1007 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
1010 DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
1012 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1014 thr->shadow_stack_pos--;
1017 void ThreadIgnoreBegin(ThreadState *thr, uptr pc, bool save_stack) {
1018 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
1019 thr->ignore_reads_and_writes++;
1020 CHECK_GT(thr->ignore_reads_and_writes, 0);
1021 thr->fast_state.SetIgnoreBit();
1023 if (save_stack && !ctx->after_multithreaded_fork)
1024 thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
1028 void ThreadIgnoreEnd(ThreadState *thr, uptr pc) {
1029 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
1030 CHECK_GT(thr->ignore_reads_and_writes, 0);
1031 thr->ignore_reads_and_writes--;
1032 if (thr->ignore_reads_and_writes == 0) {
1033 thr->fast_state.ClearIgnoreBit();
1035 thr->mop_ignore_set.Reset();
1041 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
1042 uptr __tsan_testonly_shadow_stack_current_size() {
1043 ThreadState *thr = cur_thread();
1044 return thr->shadow_stack_pos - thr->shadow_stack;
1048 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc, bool save_stack) {
1049 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1051 CHECK_GT(thr->ignore_sync, 0);
1053 if (save_stack && !ctx->after_multithreaded_fork)
1054 thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1058 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) {
1059 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1060 CHECK_GT(thr->ignore_sync, 0);
1063 if (thr->ignore_sync == 0)
1064 thr->sync_ignore_set.Reset();
1068 bool MD5Hash::operator==(const MD5Hash &other) const {
1069 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1073 void build_consistency_debug() {}
1075 void build_consistency_release() {}
1078 #if TSAN_COLLECT_STATS
1079 void build_consistency_stats() {}
1081 void build_consistency_nostats() {}
1084 } // namespace __tsan
1087 // Must be included in this file to make sure everything is inlined.
1088 #include "tsan_interface_inl.h"