2016-10-21 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / libsanitizer / tsan / tsan_rtl.cc
blob4fceca6f41f91441c73d86729dfe043490e7e6a7
1 //===-- tsan_rtl.cc -------------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of ThreadSanitizer (TSan), a race detector.
9 //
10 // Main file (entry points) for the TSan run-time.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common/sanitizer_atomic.h"
14 #include "sanitizer_common/sanitizer_common.h"
15 #include "sanitizer_common/sanitizer_libc.h"
16 #include "sanitizer_common/sanitizer_stackdepot.h"
17 #include "sanitizer_common/sanitizer_placement_new.h"
18 #include "sanitizer_common/sanitizer_symbolizer.h"
19 #include "tsan_defs.h"
20 #include "tsan_platform.h"
21 #include "tsan_rtl.h"
22 #include "tsan_mman.h"
23 #include "tsan_suppressions.h"
24 #include "tsan_symbolize.h"
25 #include "ubsan/ubsan_init.h"
27 #ifdef __SSE3__
28 // <emmintrin.h> transitively includes <stdlib.h>,
29 // and it's prohibited to include std headers into tsan runtime.
30 // So we do this dirty trick.
31 #define _MM_MALLOC_H_INCLUDED
32 #define __MM_MALLOC_H
33 #include <emmintrin.h>
34 typedef __m128i m128;
35 #endif
37 volatile int __tsan_resumed = 0;
39 extern "C" void __tsan_resume() {
40 __tsan_resumed = 1;
43 namespace __tsan {
45 #if !defined(SANITIZER_GO) && !SANITIZER_MAC
46 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
47 #endif
48 static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
49 Context *ctx;
51 // Can be overriden by a front-end.
52 #ifdef TSAN_EXTERNAL_HOOKS
53 bool OnFinalize(bool failed);
54 void OnInitialize();
55 #else
56 SANITIZER_INTERFACE_ATTRIBUTE
57 bool WEAK OnFinalize(bool failed) {
58 return failed;
60 SANITIZER_INTERFACE_ATTRIBUTE
61 void WEAK OnInitialize() {}
62 #endif
64 static char thread_registry_placeholder[sizeof(ThreadRegistry)];
66 static ThreadContextBase *CreateThreadContext(u32 tid) {
67 // Map thread trace when context is created.
68 char name[50];
69 internal_snprintf(name, sizeof(name), "trace %u", tid);
70 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
71 const uptr hdr = GetThreadTraceHeader(tid);
72 internal_snprintf(name, sizeof(name), "trace header %u", tid);
73 MapThreadTrace(hdr, sizeof(Trace), name);
74 new((void*)hdr) Trace();
75 // We are going to use only a small part of the trace with the default
76 // value of history_size. However, the constructor writes to the whole trace.
77 // Unmap the unused part.
78 uptr hdr_end = hdr + sizeof(Trace);
79 hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
80 hdr_end = RoundUp(hdr_end, GetPageSizeCached());
81 if (hdr_end < hdr + sizeof(Trace))
82 UnmapOrDie((void*)hdr_end, hdr + sizeof(Trace) - hdr_end);
83 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
84 return new(mem) ThreadContext(tid);
87 #ifndef SANITIZER_GO
88 static const u32 kThreadQuarantineSize = 16;
89 #else
90 static const u32 kThreadQuarantineSize = 64;
91 #endif
93 Context::Context()
94 : initialized()
95 , report_mtx(MutexTypeReport, StatMtxReport)
96 , nreported()
97 , nmissed_expected()
98 , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
99 CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
100 , racy_mtx(MutexTypeRacy, StatMtxRacy)
101 , racy_stacks(MBlockRacyStacks)
102 , racy_addresses(MBlockRacyAddresses)
103 , fired_suppressions_mtx(MutexTypeFired, StatMtxFired)
104 , fired_suppressions(8) {
107 // The objects are allocated in TLS, so one may rely on zero-initialization.
108 ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
109 unsigned reuse_count,
110 uptr stk_addr, uptr stk_size,
111 uptr tls_addr, uptr tls_size)
112 : fast_state(tid, epoch)
113 // Do not touch these, rely on zero initialization,
114 // they may be accessed before the ctor.
115 // , ignore_reads_and_writes()
116 // , ignore_interceptors()
117 , clock(tid, reuse_count)
118 #ifndef SANITIZER_GO
119 , jmp_bufs(MBlockJmpBuf)
120 #endif
121 , tid(tid)
122 , unique_id(unique_id)
123 , stk_addr(stk_addr)
124 , stk_size(stk_size)
125 , tls_addr(tls_addr)
126 , tls_size(tls_size)
127 #ifndef SANITIZER_GO
128 , last_sleep_clock(tid)
129 #endif
133 #ifndef SANITIZER_GO
134 static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
135 uptr n_threads;
136 uptr n_running_threads;
137 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
138 InternalScopedBuffer<char> buf(4096);
139 WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
140 WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
143 static void BackgroundThread(void *arg) {
144 // This is a non-initialized non-user thread, nothing to see here.
145 // We don't use ScopedIgnoreInterceptors, because we want ignores to be
146 // enabled even when the thread function exits (e.g. during pthread thread
147 // shutdown code).
148 cur_thread()->ignore_interceptors++;
149 const u64 kMs2Ns = 1000 * 1000;
151 fd_t mprof_fd = kInvalidFd;
152 if (flags()->profile_memory && flags()->profile_memory[0]) {
153 if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
154 mprof_fd = 1;
155 } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
156 mprof_fd = 2;
157 } else {
158 InternalScopedString filename(kMaxPathLength);
159 filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
160 fd_t fd = OpenFile(filename.data(), WrOnly);
161 if (fd == kInvalidFd) {
162 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
163 &filename[0]);
164 } else {
165 mprof_fd = fd;
170 u64 last_flush = NanoTime();
171 uptr last_rss = 0;
172 for (int i = 0;
173 atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
174 i++) {
175 SleepForMillis(100);
176 u64 now = NanoTime();
178 // Flush memory if requested.
179 if (flags()->flush_memory_ms > 0) {
180 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
181 VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
182 FlushShadowMemory();
183 last_flush = NanoTime();
186 // GetRSS can be expensive on huge programs, so don't do it every 100ms.
187 if (flags()->memory_limit_mb > 0) {
188 uptr rss = GetRSS();
189 uptr limit = uptr(flags()->memory_limit_mb) << 20;
190 VPrintf(1, "ThreadSanitizer: memory flush check"
191 " RSS=%llu LAST=%llu LIMIT=%llu\n",
192 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
193 if (2 * rss > limit + last_rss) {
194 VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
195 FlushShadowMemory();
196 rss = GetRSS();
197 VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
199 last_rss = rss;
202 // Write memory profile if requested.
203 if (mprof_fd != kInvalidFd)
204 MemoryProfiler(ctx, mprof_fd, i);
206 // Flush symbolizer cache if requested.
207 if (flags()->flush_symbolizer_ms > 0) {
208 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
209 memory_order_relaxed);
210 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
211 Lock l(&ctx->report_mtx);
212 SpinMutexLock l2(&CommonSanitizerReportMutex);
213 SymbolizeFlush();
214 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
220 static void StartBackgroundThread() {
221 ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
224 #ifndef __mips__
225 static void StopBackgroundThread() {
226 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
227 internal_join_thread(ctx->background_thread);
228 ctx->background_thread = 0;
230 #endif
231 #endif
233 void DontNeedShadowFor(uptr addr, uptr size) {
234 uptr shadow_beg = MemToShadow(addr);
235 uptr shadow_end = MemToShadow(addr + size);
236 FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
239 void MapShadow(uptr addr, uptr size) {
240 // Global data is not 64K aligned, but there are no adjacent mappings,
241 // so we can get away with unaligned mapping.
242 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
243 MmapFixedNoReserve(MemToShadow(addr), size * kShadowMultiplier, "shadow");
245 // Meta shadow is 2:1, so tread carefully.
246 static bool data_mapped = false;
247 static uptr mapped_meta_end = 0;
248 uptr meta_begin = (uptr)MemToMeta(addr);
249 uptr meta_end = (uptr)MemToMeta(addr + size);
250 meta_begin = RoundDownTo(meta_begin, 64 << 10);
251 meta_end = RoundUpTo(meta_end, 64 << 10);
252 if (!data_mapped) {
253 // First call maps data+bss.
254 data_mapped = true;
255 MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
256 } else {
257 // Mapping continous heap.
258 // Windows wants 64K alignment.
259 meta_begin = RoundDownTo(meta_begin, 64 << 10);
260 meta_end = RoundUpTo(meta_end, 64 << 10);
261 if (meta_end <= mapped_meta_end)
262 return;
263 if (meta_begin < mapped_meta_end)
264 meta_begin = mapped_meta_end;
265 MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
266 mapped_meta_end = meta_end;
268 VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n",
269 addr, addr+size, meta_begin, meta_end);
272 void MapThreadTrace(uptr addr, uptr size, const char *name) {
273 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
274 CHECK_GE(addr, kTraceMemBeg);
275 CHECK_LE(addr + size, kTraceMemEnd);
276 CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
277 uptr addr1 = (uptr)MmapFixedNoReserve(addr, size, name);
278 if (addr1 != addr) {
279 Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p->%p)\n",
280 addr, size, addr1);
281 Die();
285 static void CheckShadowMapping() {
286 for (uptr i = 0; i < ARRAY_SIZE(UserRegions); i += 2) {
287 const uptr beg = UserRegions[i];
288 const uptr end = UserRegions[i + 1];
289 VPrintf(3, "checking shadow region %p-%p\n", beg, end);
290 for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) {
291 for (int x = -1; x <= 1; x++) {
292 const uptr p = p0 + x;
293 if (p < beg || p >= end)
294 continue;
295 const uptr s = MemToShadow(p);
296 const uptr m = (uptr)MemToMeta(p);
297 VPrintf(3, " checking pointer %p: shadow=%p meta=%p\n", p, s, m);
298 CHECK(IsAppMem(p));
299 CHECK(IsShadowMem(s));
300 CHECK_EQ(p & ~(kShadowCell - 1), ShadowToMem(s));
301 CHECK(IsMetaMem(m));
307 void Initialize(ThreadState *thr) {
308 // Thread safe because done before all threads exist.
309 static bool is_initialized = false;
310 if (is_initialized)
311 return;
312 is_initialized = true;
313 // We are not ready to handle interceptors yet.
314 ScopedIgnoreInterceptors ignore;
315 SanitizerToolName = "ThreadSanitizer";
316 // Install tool-specific callbacks in sanitizer_common.
317 SetCheckFailedCallback(TsanCheckFailed);
319 ctx = new(ctx_placeholder) Context;
320 const char *options = GetEnv(kTsanOptionsEnv);
321 CacheBinaryName();
322 InitializeFlags(&ctx->flags, options);
323 CheckVMASize();
324 #ifndef SANITIZER_GO
325 InitializeAllocator();
326 ReplaceSystemMalloc();
327 #endif
328 InitializeInterceptors();
329 CheckShadowMapping();
330 InitializePlatform();
331 InitializeMutex();
332 InitializeDynamicAnnotations();
333 #ifndef SANITIZER_GO
334 InitializeShadowMemory();
335 #endif
336 // Setup correct file descriptor for error reports.
337 __sanitizer_set_report_path(common_flags()->log_path);
338 InitializeSuppressions();
339 #ifndef SANITIZER_GO
340 InitializeLibIgnore();
341 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
342 // On MIPS, TSan initialization is run before
343 // __pthread_initialize_minimal_internal() is finished, so we can not spawn
344 // new threads.
345 #ifndef __mips__
346 StartBackgroundThread();
347 SetSandboxingCallback(StopBackgroundThread);
348 #endif
349 #endif
350 if (common_flags()->detect_deadlocks)
351 ctx->dd = DDetector::Create(flags());
353 VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
354 (int)internal_getpid());
356 // Initialize thread 0.
357 int tid = ThreadCreate(thr, 0, 0, true);
358 CHECK_EQ(tid, 0);
359 ThreadStart(thr, tid, internal_getpid());
360 #if TSAN_CONTAINS_UBSAN
361 __ubsan::InitAsPlugin();
362 #endif
363 ctx->initialized = true;
365 if (flags()->stop_on_start) {
366 Printf("ThreadSanitizer is suspended at startup (pid %d)."
367 " Call __tsan_resume().\n",
368 (int)internal_getpid());
369 while (__tsan_resumed == 0) {}
372 OnInitialize();
375 int Finalize(ThreadState *thr) {
376 bool failed = false;
378 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
379 SleepForMillis(flags()->atexit_sleep_ms);
381 // Wait for pending reports.
382 ctx->report_mtx.Lock();
383 CommonSanitizerReportMutex.Lock();
384 CommonSanitizerReportMutex.Unlock();
385 ctx->report_mtx.Unlock();
387 #ifndef SANITIZER_GO
388 if (Verbosity()) AllocatorPrintStats();
389 #endif
391 ThreadFinalize(thr);
393 if (ctx->nreported) {
394 failed = true;
395 #ifndef SANITIZER_GO
396 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
397 #else
398 Printf("Found %d data race(s)\n", ctx->nreported);
399 #endif
402 if (ctx->nmissed_expected) {
403 failed = true;
404 Printf("ThreadSanitizer: missed %d expected races\n",
405 ctx->nmissed_expected);
408 if (common_flags()->print_suppressions)
409 PrintMatchedSuppressions();
410 #ifndef SANITIZER_GO
411 if (flags()->print_benign)
412 PrintMatchedBenignRaces();
413 #endif
415 failed = OnFinalize(failed);
417 #if TSAN_COLLECT_STATS
418 StatAggregate(ctx->stat, thr->stat);
419 StatOutput(ctx->stat);
420 #endif
422 return failed ? common_flags()->exitcode : 0;
425 #ifndef SANITIZER_GO
426 void ForkBefore(ThreadState *thr, uptr pc) {
427 ctx->thread_registry->Lock();
428 ctx->report_mtx.Lock();
431 void ForkParentAfter(ThreadState *thr, uptr pc) {
432 ctx->report_mtx.Unlock();
433 ctx->thread_registry->Unlock();
436 void ForkChildAfter(ThreadState *thr, uptr pc) {
437 ctx->report_mtx.Unlock();
438 ctx->thread_registry->Unlock();
440 uptr nthread = 0;
441 ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */);
442 VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
443 " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
444 if (nthread == 1) {
445 StartBackgroundThread();
446 } else {
447 // We've just forked a multi-threaded process. We cannot reasonably function
448 // after that (some mutexes may be locked before fork). So just enable
449 // ignores for everything in the hope that we will exec soon.
450 ctx->after_multithreaded_fork = true;
451 thr->ignore_interceptors++;
452 ThreadIgnoreBegin(thr, pc);
453 ThreadIgnoreSyncBegin(thr, pc);
456 #endif
458 #ifdef SANITIZER_GO
459 NOINLINE
460 void GrowShadowStack(ThreadState *thr) {
461 const int sz = thr->shadow_stack_end - thr->shadow_stack;
462 const int newsz = 2 * sz;
463 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
464 newsz * sizeof(uptr));
465 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
466 internal_free(thr->shadow_stack);
467 thr->shadow_stack = newstack;
468 thr->shadow_stack_pos = newstack + sz;
469 thr->shadow_stack_end = newstack + newsz;
471 #endif
473 u32 CurrentStackId(ThreadState *thr, uptr pc) {
474 if (!thr->is_inited) // May happen during bootstrap.
475 return 0;
476 if (pc != 0) {
477 #ifndef SANITIZER_GO
478 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
479 #else
480 if (thr->shadow_stack_pos == thr->shadow_stack_end)
481 GrowShadowStack(thr);
482 #endif
483 thr->shadow_stack_pos[0] = pc;
484 thr->shadow_stack_pos++;
486 u32 id = StackDepotPut(
487 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
488 if (pc != 0)
489 thr->shadow_stack_pos--;
490 return id;
493 void TraceSwitch(ThreadState *thr) {
494 thr->nomalloc++;
495 Trace *thr_trace = ThreadTrace(thr->tid);
496 Lock l(&thr_trace->mtx);
497 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
498 TraceHeader *hdr = &thr_trace->headers[trace];
499 hdr->epoch0 = thr->fast_state.epoch();
500 ObtainCurrentStack(thr, 0, &hdr->stack0);
501 hdr->mset0 = thr->mset;
502 thr->nomalloc--;
505 Trace *ThreadTrace(int tid) {
506 return (Trace*)GetThreadTraceHeader(tid);
509 uptr TraceTopPC(ThreadState *thr) {
510 Event *events = (Event*)GetThreadTrace(thr->tid);
511 uptr pc = events[thr->fast_state.GetTracePos()];
512 return pc;
515 uptr TraceSize() {
516 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
519 uptr TraceParts() {
520 return TraceSize() / kTracePartSize;
523 #ifndef SANITIZER_GO
524 extern "C" void __tsan_trace_switch() {
525 TraceSwitch(cur_thread());
528 extern "C" void __tsan_report_race() {
529 ReportRace(cur_thread());
531 #endif
533 ALWAYS_INLINE
534 Shadow LoadShadow(u64 *p) {
535 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
536 return Shadow(raw);
539 ALWAYS_INLINE
540 void StoreShadow(u64 *sp, u64 s) {
541 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
544 ALWAYS_INLINE
545 void StoreIfNotYetStored(u64 *sp, u64 *s) {
546 StoreShadow(sp, *s);
547 *s = 0;
550 ALWAYS_INLINE
551 void HandleRace(ThreadState *thr, u64 *shadow_mem,
552 Shadow cur, Shadow old) {
553 thr->racy_state[0] = cur.raw();
554 thr->racy_state[1] = old.raw();
555 thr->racy_shadow_addr = shadow_mem;
556 #ifndef SANITIZER_GO
557 HACKY_CALL(__tsan_report_race);
558 #else
559 ReportRace(thr);
560 #endif
563 static inline bool HappensBefore(Shadow old, ThreadState *thr) {
564 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
567 ALWAYS_INLINE
568 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
569 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
570 u64 *shadow_mem, Shadow cur) {
571 StatInc(thr, StatMop);
572 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
573 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
575 // This potentially can live in an MMX/SSE scratch register.
576 // The required intrinsics are:
577 // __m128i _mm_move_epi64(__m128i*);
578 // _mm_storel_epi64(u64*, __m128i);
579 u64 store_word = cur.raw();
581 // scan all the shadow values and dispatch to 4 categories:
582 // same, replace, candidate and race (see comments below).
583 // we consider only 3 cases regarding access sizes:
584 // equal, intersect and not intersect. initially I considered
585 // larger and smaller as well, it allowed to replace some
586 // 'candidates' with 'same' or 'replace', but I think
587 // it's just not worth it (performance- and complexity-wise).
589 Shadow old(0);
591 // It release mode we manually unroll the loop,
592 // because empirically gcc generates better code this way.
593 // However, we can't afford unrolling in debug mode, because the function
594 // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
595 // threads, which is not enough for the unrolled loop.
596 #if SANITIZER_DEBUG
597 for (int idx = 0; idx < 4; idx++) {
598 #include "tsan_update_shadow_word_inl.h"
600 #else
601 int idx = 0;
602 #include "tsan_update_shadow_word_inl.h"
603 idx = 1;
604 #include "tsan_update_shadow_word_inl.h"
605 idx = 2;
606 #include "tsan_update_shadow_word_inl.h"
607 idx = 3;
608 #include "tsan_update_shadow_word_inl.h"
609 #endif
611 // we did not find any races and had already stored
612 // the current access info, so we are done
613 if (LIKELY(store_word == 0))
614 return;
615 // choose a random candidate slot and replace it
616 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
617 StatInc(thr, StatShadowReplace);
618 return;
619 RACE:
620 HandleRace(thr, shadow_mem, cur, old);
621 return;
624 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
625 int size, bool kAccessIsWrite, bool kIsAtomic) {
626 while (size) {
627 int size1 = 1;
628 int kAccessSizeLog = kSizeLog1;
629 if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
630 size1 = 8;
631 kAccessSizeLog = kSizeLog8;
632 } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
633 size1 = 4;
634 kAccessSizeLog = kSizeLog4;
635 } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
636 size1 = 2;
637 kAccessSizeLog = kSizeLog2;
639 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
640 addr += size1;
641 size -= size1;
645 ALWAYS_INLINE
646 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
647 Shadow cur(a);
648 for (uptr i = 0; i < kShadowCnt; i++) {
649 Shadow old(LoadShadow(&s[i]));
650 if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
651 old.TidWithIgnore() == cur.TidWithIgnore() &&
652 old.epoch() > sync_epoch &&
653 old.IsAtomic() == cur.IsAtomic() &&
654 old.IsRead() <= cur.IsRead())
655 return true;
657 return false;
660 #if defined(__SSE3__)
661 #define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \
662 _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \
663 (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
664 ALWAYS_INLINE
665 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
666 // This is an optimized version of ContainsSameAccessSlow.
667 // load current access into access[0:63]
668 const m128 access = _mm_cvtsi64_si128(a);
669 // duplicate high part of access in addr0:
670 // addr0[0:31] = access[32:63]
671 // addr0[32:63] = access[32:63]
672 // addr0[64:95] = access[32:63]
673 // addr0[96:127] = access[32:63]
674 const m128 addr0 = SHUF(access, access, 1, 1, 1, 1);
675 // load 4 shadow slots
676 const m128 shadow0 = _mm_load_si128((__m128i*)s);
677 const m128 shadow1 = _mm_load_si128((__m128i*)s + 1);
678 // load high parts of 4 shadow slots into addr_vect:
679 // addr_vect[0:31] = shadow0[32:63]
680 // addr_vect[32:63] = shadow0[96:127]
681 // addr_vect[64:95] = shadow1[32:63]
682 // addr_vect[96:127] = shadow1[96:127]
683 m128 addr_vect = SHUF(shadow0, shadow1, 1, 3, 1, 3);
684 if (!is_write) {
685 // set IsRead bit in addr_vect
686 const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
687 const m128 rw_mask = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
688 addr_vect = _mm_or_si128(addr_vect, rw_mask);
690 // addr0 == addr_vect?
691 const m128 addr_res = _mm_cmpeq_epi32(addr0, addr_vect);
692 // epoch1[0:63] = sync_epoch
693 const m128 epoch1 = _mm_cvtsi64_si128(sync_epoch);
694 // epoch[0:31] = sync_epoch[0:31]
695 // epoch[32:63] = sync_epoch[0:31]
696 // epoch[64:95] = sync_epoch[0:31]
697 // epoch[96:127] = sync_epoch[0:31]
698 const m128 epoch = SHUF(epoch1, epoch1, 0, 0, 0, 0);
699 // load low parts of shadow cell epochs into epoch_vect:
700 // epoch_vect[0:31] = shadow0[0:31]
701 // epoch_vect[32:63] = shadow0[64:95]
702 // epoch_vect[64:95] = shadow1[0:31]
703 // epoch_vect[96:127] = shadow1[64:95]
704 const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
705 // epoch_vect >= sync_epoch?
706 const m128 epoch_res = _mm_cmpgt_epi32(epoch_vect, epoch);
707 // addr_res & epoch_res
708 const m128 res = _mm_and_si128(addr_res, epoch_res);
709 // mask[0] = res[7]
710 // mask[1] = res[15]
711 // ...
712 // mask[15] = res[127]
713 const int mask = _mm_movemask_epi8(res);
714 return mask != 0;
716 #endif
718 ALWAYS_INLINE
719 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
720 #if defined(__SSE3__)
721 bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
722 // NOTE: this check can fail if the shadow is concurrently mutated
723 // by other threads. But it still can be useful if you modify
724 // ContainsSameAccessFast and want to ensure that it's not completely broken.
725 // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
726 return res;
727 #else
728 return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
729 #endif
732 ALWAYS_INLINE USED
733 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
734 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
735 u64 *shadow_mem = (u64*)MemToShadow(addr);
736 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
737 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
738 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
739 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
740 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
741 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
742 #if SANITIZER_DEBUG
743 if (!IsAppMem(addr)) {
744 Printf("Access to non app mem %zx\n", addr);
745 DCHECK(IsAppMem(addr));
747 if (!IsShadowMem((uptr)shadow_mem)) {
748 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
749 DCHECK(IsShadowMem((uptr)shadow_mem));
751 #endif
753 if (kCppMode && *shadow_mem == kShadowRodata) {
754 // Access to .rodata section, no races here.
755 // Measurements show that it can be 10-20% of all memory accesses.
756 StatInc(thr, StatMop);
757 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
758 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
759 StatInc(thr, StatMopRodata);
760 return;
763 FastState fast_state = thr->fast_state;
764 if (fast_state.GetIgnoreBit()) {
765 StatInc(thr, StatMop);
766 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
767 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
768 StatInc(thr, StatMopIgnored);
769 return;
772 Shadow cur(fast_state);
773 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
774 cur.SetWrite(kAccessIsWrite);
775 cur.SetAtomic(kIsAtomic);
777 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
778 thr->fast_synch_epoch, kAccessIsWrite))) {
779 StatInc(thr, StatMop);
780 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
781 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
782 StatInc(thr, StatMopSame);
783 return;
786 if (kCollectHistory) {
787 fast_state.IncrementEpoch();
788 thr->fast_state = fast_state;
789 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
790 cur.IncrementEpoch();
793 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
794 shadow_mem, cur);
797 // Called by MemoryAccessRange in tsan_rtl_thread.cc
798 ALWAYS_INLINE USED
799 void MemoryAccessImpl(ThreadState *thr, uptr addr,
800 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
801 u64 *shadow_mem, Shadow cur) {
802 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
803 thr->fast_synch_epoch, kAccessIsWrite))) {
804 StatInc(thr, StatMop);
805 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
806 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
807 StatInc(thr, StatMopSame);
808 return;
811 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
812 shadow_mem, cur);
815 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
816 u64 val) {
817 (void)thr;
818 (void)pc;
819 if (size == 0)
820 return;
821 // FIXME: fix me.
822 uptr offset = addr % kShadowCell;
823 if (offset) {
824 offset = kShadowCell - offset;
825 if (size <= offset)
826 return;
827 addr += offset;
828 size -= offset;
830 DCHECK_EQ(addr % 8, 0);
831 // If a user passes some insane arguments (memset(0)),
832 // let it just crash as usual.
833 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
834 return;
835 // Don't want to touch lots of shadow memory.
836 // If a program maps 10MB stack, there is no need reset the whole range.
837 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
838 // UnmapOrDie/MmapFixedNoReserve does not work on Windows,
839 // so we do it only for C/C++.
840 if (kGoMode || size < common_flags()->clear_shadow_mmap_threshold) {
841 u64 *p = (u64*)MemToShadow(addr);
842 CHECK(IsShadowMem((uptr)p));
843 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
844 // FIXME: may overwrite a part outside the region
845 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
846 p[i++] = val;
847 for (uptr j = 1; j < kShadowCnt; j++)
848 p[i++] = 0;
850 } else {
851 // The region is big, reset only beginning and end.
852 const uptr kPageSize = GetPageSizeCached();
853 u64 *begin = (u64*)MemToShadow(addr);
854 u64 *end = begin + size / kShadowCell * kShadowCnt;
855 u64 *p = begin;
856 // Set at least first kPageSize/2 to page boundary.
857 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
858 *p++ = val;
859 for (uptr j = 1; j < kShadowCnt; j++)
860 *p++ = 0;
862 // Reset middle part.
863 u64 *p1 = p;
864 p = RoundDown(end, kPageSize);
865 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
866 MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1);
867 // Set the ending.
868 while (p < end) {
869 *p++ = val;
870 for (uptr j = 1; j < kShadowCnt; j++)
871 *p++ = 0;
876 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
877 MemoryRangeSet(thr, pc, addr, size, 0);
880 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
881 // Processing more than 1k (4k of shadow) is expensive,
882 // can cause excessive memory consumption (user does not necessary touch
883 // the whole range) and most likely unnecessary.
884 if (size > 1024)
885 size = 1024;
886 CHECK_EQ(thr->is_freeing, false);
887 thr->is_freeing = true;
888 MemoryAccessRange(thr, pc, addr, size, true);
889 thr->is_freeing = false;
890 if (kCollectHistory) {
891 thr->fast_state.IncrementEpoch();
892 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
894 Shadow s(thr->fast_state);
895 s.ClearIgnoreBit();
896 s.MarkAsFreed();
897 s.SetWrite(true);
898 s.SetAddr0AndSizeLog(0, 3);
899 MemoryRangeSet(thr, pc, addr, size, s.raw());
902 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
903 if (kCollectHistory) {
904 thr->fast_state.IncrementEpoch();
905 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
907 Shadow s(thr->fast_state);
908 s.ClearIgnoreBit();
909 s.SetWrite(true);
910 s.SetAddr0AndSizeLog(0, 3);
911 MemoryRangeSet(thr, pc, addr, size, s.raw());
914 ALWAYS_INLINE USED
915 void FuncEntry(ThreadState *thr, uptr pc) {
916 StatInc(thr, StatFuncEnter);
917 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
918 if (kCollectHistory) {
919 thr->fast_state.IncrementEpoch();
920 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
923 // Shadow stack maintenance can be replaced with
924 // stack unwinding during trace switch (which presumably must be faster).
925 DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
926 #ifndef SANITIZER_GO
927 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
928 #else
929 if (thr->shadow_stack_pos == thr->shadow_stack_end)
930 GrowShadowStack(thr);
931 #endif
932 thr->shadow_stack_pos[0] = pc;
933 thr->shadow_stack_pos++;
936 ALWAYS_INLINE USED
937 void FuncExit(ThreadState *thr) {
938 StatInc(thr, StatFuncExit);
939 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
940 if (kCollectHistory) {
941 thr->fast_state.IncrementEpoch();
942 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
945 DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
946 #ifndef SANITIZER_GO
947 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
948 #endif
949 thr->shadow_stack_pos--;
952 void ThreadIgnoreBegin(ThreadState *thr, uptr pc) {
953 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
954 thr->ignore_reads_and_writes++;
955 CHECK_GT(thr->ignore_reads_and_writes, 0);
956 thr->fast_state.SetIgnoreBit();
957 #ifndef SANITIZER_GO
958 if (!ctx->after_multithreaded_fork)
959 thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
960 #endif
963 void ThreadIgnoreEnd(ThreadState *thr, uptr pc) {
964 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
965 thr->ignore_reads_and_writes--;
966 CHECK_GE(thr->ignore_reads_and_writes, 0);
967 if (thr->ignore_reads_and_writes == 0) {
968 thr->fast_state.ClearIgnoreBit();
969 #ifndef SANITIZER_GO
970 thr->mop_ignore_set.Reset();
971 #endif
975 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
976 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
977 thr->ignore_sync++;
978 CHECK_GT(thr->ignore_sync, 0);
979 #ifndef SANITIZER_GO
980 if (!ctx->after_multithreaded_fork)
981 thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
982 #endif
985 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) {
986 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
987 thr->ignore_sync--;
988 CHECK_GE(thr->ignore_sync, 0);
989 #ifndef SANITIZER_GO
990 if (thr->ignore_sync == 0)
991 thr->sync_ignore_set.Reset();
992 #endif
995 bool MD5Hash::operator==(const MD5Hash &other) const {
996 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
999 #if SANITIZER_DEBUG
1000 void build_consistency_debug() {}
1001 #else
1002 void build_consistency_release() {}
1003 #endif
1005 #if TSAN_COLLECT_STATS
1006 void build_consistency_stats() {}
1007 #else
1008 void build_consistency_nostats() {}
1009 #endif
1011 } // namespace __tsan
1013 #ifndef SANITIZER_GO
1014 // Must be included in this file to make sure everything is inlined.
1015 #include "tsan_interface_inl.h"
1016 #endif