]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.cc
Merge compiler-rt trunk r321017 to contrib/compiler-rt.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / tsan / rtl / tsan_rtl.cc
1 //===-- tsan_rtl.cc -------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
11 //
12 // Main file (entry points) for the TSan run-time.
13 //===----------------------------------------------------------------------===//
14
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"
24 #include "tsan_rtl.h"
25 #include "tsan_mman.h"
26 #include "tsan_suppressions.h"
27 #include "tsan_symbolize.h"
28 #include "ubsan/ubsan_init.h"
29
30 #ifdef __SSE3__
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
35 #define __MM_MALLOC_H
36 #include <emmintrin.h>
37 typedef __m128i m128;
38 #endif
39
40 volatile int __tsan_resumed = 0;
41
42 extern "C" void __tsan_resume() {
43   __tsan_resumed = 1;
44 }
45
46 namespace __tsan {
47
48 #if !SANITIZER_GO && !SANITIZER_MAC
49 __attribute__((tls_model("initial-exec")))
50 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
51 #endif
52 static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
53 Context *ctx;
54
55 // Can be overriden by a front-end.
56 #ifdef TSAN_EXTERNAL_HOOKS
57 bool OnFinalize(bool failed);
58 void OnInitialize();
59 #else
60 SANITIZER_WEAK_CXX_DEFAULT_IMPL
61 bool OnFinalize(bool failed) {
62   return failed;
63 }
64 SANITIZER_WEAK_CXX_DEFAULT_IMPL
65 void OnInitialize() {}
66 #endif
67
68 static char thread_registry_placeholder[sizeof(ThreadRegistry)];
69
70 static ThreadContextBase *CreateThreadContext(u32 tid) {
71   // Map thread trace when context is created.
72   char name[50];
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);
89 }
90
91 #if !SANITIZER_GO
92 static const u32 kThreadQuarantineSize = 16;
93 #else
94 static const u32 kThreadQuarantineSize = 64;
95 #endif
96
97 Context::Context()
98   : initialized()
99   , report_mtx(MutexTypeReport, StatMtxReport)
100   , nreported()
101   , nmissed_expected()
102   , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
103       CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
104   , racy_mtx(MutexTypeRacy, StatMtxRacy)
105   , racy_stacks()
106   , racy_addresses()
107   , fired_suppressions_mtx(MutexTypeFired, StatMtxFired)
108   , fired_suppressions(8)
109   , clock_alloc("clock allocator") {
110 }
111
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)
123 #if !SANITIZER_GO
124   , jmp_bufs()
125 #endif
126   , tid(tid)
127   , unique_id(unique_id)
128   , stk_addr(stk_addr)
129   , stk_size(stk_size)
130   , tls_addr(tls_addr)
131   , tls_size(tls_size)
132 #if !SANITIZER_GO
133   , last_sleep_clock(tid)
134 #endif
135 {
136 }
137
138 #if !SANITIZER_GO
139 static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
140   uptr n_threads;
141   uptr n_running_threads;
142   ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
143   InternalScopedBuffer<char> buf(4096);
144   WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
145   WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
146 }
147
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
152   // shutdown code).
153   cur_thread()->ignore_interceptors++;
154   const u64 kMs2Ns = 1000 * 1000;
155
156   fd_t mprof_fd = kInvalidFd;
157   if (flags()->profile_memory && flags()->profile_memory[0]) {
158     if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
159       mprof_fd = 1;
160     } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
161       mprof_fd = 2;
162     } else {
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",
168             &filename[0]);
169       } else {
170         mprof_fd = fd;
171       }
172     }
173   }
174
175   u64 last_flush = NanoTime();
176   uptr last_rss = 0;
177   for (int i = 0;
178       atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
179       i++) {
180     SleepForMillis(100);
181     u64 now = NanoTime();
182
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");
187         FlushShadowMemory();
188         last_flush = NanoTime();
189       }
190     }
191     // GetRSS can be expensive on huge programs, so don't do it every 100ms.
192     if (flags()->memory_limit_mb > 0) {
193       uptr rss = GetRSS();
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");
200         FlushShadowMemory();
201         rss = GetRSS();
202         VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
203       }
204       last_rss = rss;
205     }
206
207     // Write memory profile if requested.
208     if (mprof_fd != kInvalidFd)
209       MemoryProfiler(ctx, mprof_fd, i);
210
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;
218         SymbolizeFlush();
219         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
220       }
221     }
222   }
223 }
224
225 static void StartBackgroundThread() {
226   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
227 }
228
229 #ifndef __mips__
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;
234 }
235 #endif
236 #endif
237
238 void DontNeedShadowFor(uptr addr, uptr size) {
239   ReleaseMemoryPagesToOS(MemToShadow(addr), MemToShadow(addr + size));
240 }
241
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   MmapFixedNoReserve(shadow_begin, shadow_end - shadow_begin, "shadow");
250
251   // Meta shadow is 2:1, so tread carefully.
252   static bool data_mapped = false;
253   static uptr mapped_meta_end = 0;
254   uptr meta_begin = (uptr)MemToMeta(addr);
255   uptr meta_end = (uptr)MemToMeta(addr + size);
256   meta_begin = RoundDownTo(meta_begin, 64 << 10);
257   meta_end = RoundUpTo(meta_end, 64 << 10);
258   if (!data_mapped) {
259     // First call maps data+bss.
260     data_mapped = true;
261     MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
262   } else {
263     // Mapping continous heap.
264     // Windows wants 64K alignment.
265     meta_begin = RoundDownTo(meta_begin, 64 << 10);
266     meta_end = RoundUpTo(meta_end, 64 << 10);
267     if (meta_end <= mapped_meta_end)
268       return;
269     if (meta_begin < mapped_meta_end)
270       meta_begin = mapped_meta_end;
271     MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
272     mapped_meta_end = meta_end;
273   }
274   VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n",
275       addr, addr+size, meta_begin, meta_end);
276 }
277
278 void MapThreadTrace(uptr addr, uptr size, const char *name) {
279   DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
280   CHECK_GE(addr, TraceMemBeg());
281   CHECK_LE(addr + size, TraceMemEnd());
282   CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
283   uptr addr1 = (uptr)MmapFixedNoReserve(addr, size, name);
284   if (addr1 != addr) {
285     Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p->%p)\n",
286         addr, size, addr1);
287     Die();
288   }
289 }
290
291 static void CheckShadowMapping() {
292   uptr beg, end;
293   for (int i = 0; GetUserRegion(i, &beg, &end); i++) {
294     // Skip cases for empty regions (heap definition for architectures that
295     // do not use 64-bit allocator).
296     if (beg == end)
297       continue;
298     VPrintf(3, "checking shadow region %p-%p\n", beg, end);
299     uptr prev = 0;
300     for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) {
301       for (int x = -(int)kShadowCell; x <= (int)kShadowCell; x += kShadowCell) {
302         const uptr p = RoundDown(p0 + x, kShadowCell);
303         if (p < beg || p >= end)
304           continue;
305         const uptr s = MemToShadow(p);
306         const uptr m = (uptr)MemToMeta(p);
307         VPrintf(3, "  checking pointer %p: shadow=%p meta=%p\n", p, s, m);
308         CHECK(IsAppMem(p));
309         CHECK(IsShadowMem(s));
310         CHECK_EQ(p, ShadowToMem(s));
311         CHECK(IsMetaMem(m));
312         if (prev) {
313           // Ensure that shadow and meta mappings are linear within a single
314           // user range. Lots of code that processes memory ranges assumes it.
315           const uptr prev_s = MemToShadow(prev);
316           const uptr prev_m = (uptr)MemToMeta(prev);
317           CHECK_EQ(s - prev_s, (p - prev) * kShadowMultiplier);
318           CHECK_EQ((m - prev_m) / kMetaShadowSize,
319                    (p - prev) / kMetaShadowCell);
320         }
321         prev = p;
322       }
323     }
324   }
325 }
326
327 #if !SANITIZER_GO
328 static void OnStackUnwind(const SignalContext &sig, const void *,
329                           BufferedStackTrace *stack) {
330   uptr top = 0;
331   uptr bottom = 0;
332   bool fast = common_flags()->fast_unwind_on_fatal;
333   if (fast) GetThreadStackTopAndBottom(false, &top, &bottom);
334   stack->Unwind(kStackTraceMax, sig.pc, sig.bp, sig.context, top, bottom, fast);
335 }
336
337 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
338   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
339 }
340 #endif
341
342 void Initialize(ThreadState *thr) {
343   // Thread safe because done before all threads exist.
344   static bool is_initialized = false;
345   if (is_initialized)
346     return;
347   is_initialized = true;
348   // We are not ready to handle interceptors yet.
349   ScopedIgnoreInterceptors ignore;
350   SanitizerToolName = "ThreadSanitizer";
351   // Install tool-specific callbacks in sanitizer_common.
352   SetCheckFailedCallback(TsanCheckFailed);
353
354   ctx = new(ctx_placeholder) Context;
355   const char *options = GetEnv(SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS");
356   CacheBinaryName();
357   InitializeFlags(&ctx->flags, options);
358   AvoidCVE_2016_2143();
359   InitializePlatformEarly();
360 #if !SANITIZER_GO
361   // Re-exec ourselves if we need to set additional env or command line args.
362   MaybeReexec();
363
364   InitializeAllocator();
365   ReplaceSystemMalloc();
366 #endif
367   if (common_flags()->detect_deadlocks)
368     ctx->dd = DDetector::Create(flags());
369   Processor *proc = ProcCreate();
370   ProcWire(proc, thr);
371   InitializeInterceptors();
372   CheckShadowMapping();
373   InitializePlatform();
374   InitializeMutex();
375   InitializeDynamicAnnotations();
376 #if !SANITIZER_GO
377   InitializeShadowMemory();
378   InitializeAllocatorLate();
379   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
380 #endif
381   // Setup correct file descriptor for error reports.
382   __sanitizer_set_report_path(common_flags()->log_path);
383   InitializeSuppressions();
384 #if !SANITIZER_GO
385   InitializeLibIgnore();
386   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
387 #endif
388
389   VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
390           (int)internal_getpid());
391
392   // Initialize thread 0.
393   int tid = ThreadCreate(thr, 0, 0, true);
394   CHECK_EQ(tid, 0);
395   ThreadStart(thr, tid, GetTid(), /*workerthread*/ false);
396 #if TSAN_CONTAINS_UBSAN
397   __ubsan::InitAsPlugin();
398 #endif
399   ctx->initialized = true;
400
401 #if !SANITIZER_GO
402   Symbolizer::LateInitialize();
403 #endif
404
405   if (flags()->stop_on_start) {
406     Printf("ThreadSanitizer is suspended at startup (pid %d)."
407            " Call __tsan_resume().\n",
408            (int)internal_getpid());
409     while (__tsan_resumed == 0) {}
410   }
411
412   OnInitialize();
413 }
414
415 void MaybeSpawnBackgroundThread() {
416   // On MIPS, TSan initialization is run before
417   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
418   // new threads.
419 #if !SANITIZER_GO && !defined(__mips__)
420   static atomic_uint32_t bg_thread = {};
421   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
422       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
423     StartBackgroundThread();
424     SetSandboxingCallback(StopBackgroundThread);
425   }
426 #endif
427 }
428
429
430 int Finalize(ThreadState *thr) {
431   bool failed = false;
432
433   if (common_flags()->print_module_map == 1) PrintModuleMap();
434
435   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
436     SleepForMillis(flags()->atexit_sleep_ms);
437
438   // Wait for pending reports.
439   ctx->report_mtx.Lock();
440   { ScopedErrorReportLock l; }
441   ctx->report_mtx.Unlock();
442
443 #if !SANITIZER_GO
444   if (Verbosity()) AllocatorPrintStats();
445 #endif
446
447   ThreadFinalize(thr);
448
449   if (ctx->nreported) {
450     failed = true;
451 #if !SANITIZER_GO
452     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
453 #else
454     Printf("Found %d data race(s)\n", ctx->nreported);
455 #endif
456   }
457
458   if (ctx->nmissed_expected) {
459     failed = true;
460     Printf("ThreadSanitizer: missed %d expected races\n",
461         ctx->nmissed_expected);
462   }
463
464   if (common_flags()->print_suppressions)
465     PrintMatchedSuppressions();
466 #if !SANITIZER_GO
467   if (flags()->print_benign)
468     PrintMatchedBenignRaces();
469 #endif
470
471   failed = OnFinalize(failed);
472
473 #if TSAN_COLLECT_STATS
474   StatAggregate(ctx->stat, thr->stat);
475   StatOutput(ctx->stat);
476 #endif
477
478   return failed ? common_flags()->exitcode : 0;
479 }
480
481 #if !SANITIZER_GO
482 void ForkBefore(ThreadState *thr, uptr pc) {
483   ctx->thread_registry->Lock();
484   ctx->report_mtx.Lock();
485 }
486
487 void ForkParentAfter(ThreadState *thr, uptr pc) {
488   ctx->report_mtx.Unlock();
489   ctx->thread_registry->Unlock();
490 }
491
492 void ForkChildAfter(ThreadState *thr, uptr pc) {
493   ctx->report_mtx.Unlock();
494   ctx->thread_registry->Unlock();
495
496   uptr nthread = 0;
497   ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */);
498   VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
499       " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
500   if (nthread == 1) {
501     StartBackgroundThread();
502   } else {
503     // We've just forked a multi-threaded process. We cannot reasonably function
504     // after that (some mutexes may be locked before fork). So just enable
505     // ignores for everything in the hope that we will exec soon.
506     ctx->after_multithreaded_fork = true;
507     thr->ignore_interceptors++;
508     ThreadIgnoreBegin(thr, pc);
509     ThreadIgnoreSyncBegin(thr, pc);
510   }
511 }
512 #endif
513
514 #if SANITIZER_GO
515 NOINLINE
516 void GrowShadowStack(ThreadState *thr) {
517   const int sz = thr->shadow_stack_end - thr->shadow_stack;
518   const int newsz = 2 * sz;
519   uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
520       newsz * sizeof(uptr));
521   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
522   internal_free(thr->shadow_stack);
523   thr->shadow_stack = newstack;
524   thr->shadow_stack_pos = newstack + sz;
525   thr->shadow_stack_end = newstack + newsz;
526 }
527 #endif
528
529 u32 CurrentStackId(ThreadState *thr, uptr pc) {
530   if (!thr->is_inited)  // May happen during bootstrap.
531     return 0;
532   if (pc != 0) {
533 #if !SANITIZER_GO
534     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
535 #else
536     if (thr->shadow_stack_pos == thr->shadow_stack_end)
537       GrowShadowStack(thr);
538 #endif
539     thr->shadow_stack_pos[0] = pc;
540     thr->shadow_stack_pos++;
541   }
542   u32 id = StackDepotPut(
543       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
544   if (pc != 0)
545     thr->shadow_stack_pos--;
546   return id;
547 }
548
549 void TraceSwitch(ThreadState *thr) {
550   thr->nomalloc++;
551   Trace *thr_trace = ThreadTrace(thr->tid);
552   Lock l(&thr_trace->mtx);
553   unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
554   TraceHeader *hdr = &thr_trace->headers[trace];
555   hdr->epoch0 = thr->fast_state.epoch();
556   ObtainCurrentStack(thr, 0, &hdr->stack0);
557   hdr->mset0 = thr->mset;
558   thr->nomalloc--;
559 }
560
561 Trace *ThreadTrace(int tid) {
562   return (Trace*)GetThreadTraceHeader(tid);
563 }
564
565 uptr TraceTopPC(ThreadState *thr) {
566   Event *events = (Event*)GetThreadTrace(thr->tid);
567   uptr pc = events[thr->fast_state.GetTracePos()];
568   return pc;
569 }
570
571 uptr TraceSize() {
572   return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
573 }
574
575 uptr TraceParts() {
576   return TraceSize() / kTracePartSize;
577 }
578
579 #if !SANITIZER_GO
580 extern "C" void __tsan_trace_switch() {
581   TraceSwitch(cur_thread());
582 }
583
584 extern "C" void __tsan_report_race() {
585   ReportRace(cur_thread());
586 }
587 #endif
588
589 ALWAYS_INLINE
590 Shadow LoadShadow(u64 *p) {
591   u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
592   return Shadow(raw);
593 }
594
595 ALWAYS_INLINE
596 void StoreShadow(u64 *sp, u64 s) {
597   atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
598 }
599
600 ALWAYS_INLINE
601 void StoreIfNotYetStored(u64 *sp, u64 *s) {
602   StoreShadow(sp, *s);
603   *s = 0;
604 }
605
606 ALWAYS_INLINE
607 void HandleRace(ThreadState *thr, u64 *shadow_mem,
608                               Shadow cur, Shadow old) {
609   thr->racy_state[0] = cur.raw();
610   thr->racy_state[1] = old.raw();
611   thr->racy_shadow_addr = shadow_mem;
612 #if !SANITIZER_GO
613   HACKY_CALL(__tsan_report_race);
614 #else
615   ReportRace(thr);
616 #endif
617 }
618
619 static inline bool HappensBefore(Shadow old, ThreadState *thr) {
620   return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
621 }
622
623 ALWAYS_INLINE
624 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
625     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
626     u64 *shadow_mem, Shadow cur) {
627   StatInc(thr, StatMop);
628   StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
629   StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
630
631   // This potentially can live in an MMX/SSE scratch register.
632   // The required intrinsics are:
633   // __m128i _mm_move_epi64(__m128i*);
634   // _mm_storel_epi64(u64*, __m128i);
635   u64 store_word = cur.raw();
636
637   // scan all the shadow values and dispatch to 4 categories:
638   // same, replace, candidate and race (see comments below).
639   // we consider only 3 cases regarding access sizes:
640   // equal, intersect and not intersect. initially I considered
641   // larger and smaller as well, it allowed to replace some
642   // 'candidates' with 'same' or 'replace', but I think
643   // it's just not worth it (performance- and complexity-wise).
644
645   Shadow old(0);
646
647   // It release mode we manually unroll the loop,
648   // because empirically gcc generates better code this way.
649   // However, we can't afford unrolling in debug mode, because the function
650   // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
651   // threads, which is not enough for the unrolled loop.
652 #if SANITIZER_DEBUG
653   for (int idx = 0; idx < 4; idx++) {
654 #include "tsan_update_shadow_word_inl.h"
655   }
656 #else
657   int idx = 0;
658 #include "tsan_update_shadow_word_inl.h"
659   idx = 1;
660 #include "tsan_update_shadow_word_inl.h"
661   idx = 2;
662 #include "tsan_update_shadow_word_inl.h"
663   idx = 3;
664 #include "tsan_update_shadow_word_inl.h"
665 #endif
666
667   // we did not find any races and had already stored
668   // the current access info, so we are done
669   if (LIKELY(store_word == 0))
670     return;
671   // choose a random candidate slot and replace it
672   StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
673   StatInc(thr, StatShadowReplace);
674   return;
675  RACE:
676   HandleRace(thr, shadow_mem, cur, old);
677   return;
678 }
679
680 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
681     int size, bool kAccessIsWrite, bool kIsAtomic) {
682   while (size) {
683     int size1 = 1;
684     int kAccessSizeLog = kSizeLog1;
685     if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
686       size1 = 8;
687       kAccessSizeLog = kSizeLog8;
688     } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
689       size1 = 4;
690       kAccessSizeLog = kSizeLog4;
691     } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
692       size1 = 2;
693       kAccessSizeLog = kSizeLog2;
694     }
695     MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
696     addr += size1;
697     size -= size1;
698   }
699 }
700
701 ALWAYS_INLINE
702 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
703   Shadow cur(a);
704   for (uptr i = 0; i < kShadowCnt; i++) {
705     Shadow old(LoadShadow(&s[i]));
706     if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
707         old.TidWithIgnore() == cur.TidWithIgnore() &&
708         old.epoch() > sync_epoch &&
709         old.IsAtomic() == cur.IsAtomic() &&
710         old.IsRead() <= cur.IsRead())
711       return true;
712   }
713   return false;
714 }
715
716 #if defined(__SSE3__)
717 #define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \
718     _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \
719     (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
720 ALWAYS_INLINE
721 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
722   // This is an optimized version of ContainsSameAccessSlow.
723   // load current access into access[0:63]
724   const m128 access     = _mm_cvtsi64_si128(a);
725   // duplicate high part of access in addr0:
726   // addr0[0:31]        = access[32:63]
727   // addr0[32:63]       = access[32:63]
728   // addr0[64:95]       = access[32:63]
729   // addr0[96:127]      = access[32:63]
730   const m128 addr0      = SHUF(access, access, 1, 1, 1, 1);
731   // load 4 shadow slots
732   const m128 shadow0    = _mm_load_si128((__m128i*)s);
733   const m128 shadow1    = _mm_load_si128((__m128i*)s + 1);
734   // load high parts of 4 shadow slots into addr_vect:
735   // addr_vect[0:31]    = shadow0[32:63]
736   // addr_vect[32:63]   = shadow0[96:127]
737   // addr_vect[64:95]   = shadow1[32:63]
738   // addr_vect[96:127]  = shadow1[96:127]
739   m128 addr_vect        = SHUF(shadow0, shadow1, 1, 3, 1, 3);
740   if (!is_write) {
741     // set IsRead bit in addr_vect
742     const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
743     const m128 rw_mask  = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
744     addr_vect           = _mm_or_si128(addr_vect, rw_mask);
745   }
746   // addr0 == addr_vect?
747   const m128 addr_res   = _mm_cmpeq_epi32(addr0, addr_vect);
748   // epoch1[0:63]       = sync_epoch
749   const m128 epoch1     = _mm_cvtsi64_si128(sync_epoch);
750   // epoch[0:31]        = sync_epoch[0:31]
751   // epoch[32:63]       = sync_epoch[0:31]
752   // epoch[64:95]       = sync_epoch[0:31]
753   // epoch[96:127]      = sync_epoch[0:31]
754   const m128 epoch      = SHUF(epoch1, epoch1, 0, 0, 0, 0);
755   // load low parts of shadow cell epochs into epoch_vect:
756   // epoch_vect[0:31]   = shadow0[0:31]
757   // epoch_vect[32:63]  = shadow0[64:95]
758   // epoch_vect[64:95]  = shadow1[0:31]
759   // epoch_vect[96:127] = shadow1[64:95]
760   const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
761   // epoch_vect >= sync_epoch?
762   const m128 epoch_res  = _mm_cmpgt_epi32(epoch_vect, epoch);
763   // addr_res & epoch_res
764   const m128 res        = _mm_and_si128(addr_res, epoch_res);
765   // mask[0] = res[7]
766   // mask[1] = res[15]
767   // ...
768   // mask[15] = res[127]
769   const int mask        = _mm_movemask_epi8(res);
770   return mask != 0;
771 }
772 #endif
773
774 ALWAYS_INLINE
775 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
776 #if defined(__SSE3__)
777   bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
778   // NOTE: this check can fail if the shadow is concurrently mutated
779   // by other threads. But it still can be useful if you modify
780   // ContainsSameAccessFast and want to ensure that it's not completely broken.
781   // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
782   return res;
783 #else
784   return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
785 #endif
786 }
787
788 ALWAYS_INLINE USED
789 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
790     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
791   u64 *shadow_mem = (u64*)MemToShadow(addr);
792   DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
793       " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
794       (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
795       (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
796       (uptr)shadow_mem[0], (uptr)shadow_mem[1],
797       (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
798 #if SANITIZER_DEBUG
799   if (!IsAppMem(addr)) {
800     Printf("Access to non app mem %zx\n", addr);
801     DCHECK(IsAppMem(addr));
802   }
803   if (!IsShadowMem((uptr)shadow_mem)) {
804     Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
805     DCHECK(IsShadowMem((uptr)shadow_mem));
806   }
807 #endif
808
809   if (!SANITIZER_GO && *shadow_mem == kShadowRodata) {
810     // Access to .rodata section, no races here.
811     // Measurements show that it can be 10-20% of all memory accesses.
812     StatInc(thr, StatMop);
813     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
814     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
815     StatInc(thr, StatMopRodata);
816     return;
817   }
818
819   FastState fast_state = thr->fast_state;
820   if (fast_state.GetIgnoreBit()) {
821     StatInc(thr, StatMop);
822     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
823     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
824     StatInc(thr, StatMopIgnored);
825     return;
826   }
827
828   Shadow cur(fast_state);
829   cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
830   cur.SetWrite(kAccessIsWrite);
831   cur.SetAtomic(kIsAtomic);
832
833   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
834       thr->fast_synch_epoch, kAccessIsWrite))) {
835     StatInc(thr, StatMop);
836     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
837     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
838     StatInc(thr, StatMopSame);
839     return;
840   }
841
842   if (kCollectHistory) {
843     fast_state.IncrementEpoch();
844     thr->fast_state = fast_state;
845     TraceAddEvent(thr, fast_state, EventTypeMop, pc);
846     cur.IncrementEpoch();
847   }
848
849   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
850       shadow_mem, cur);
851 }
852
853 // Called by MemoryAccessRange in tsan_rtl_thread.cc
854 ALWAYS_INLINE USED
855 void MemoryAccessImpl(ThreadState *thr, uptr addr,
856     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
857     u64 *shadow_mem, Shadow cur) {
858   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
859       thr->fast_synch_epoch, kAccessIsWrite))) {
860     StatInc(thr, StatMop);
861     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
862     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
863     StatInc(thr, StatMopSame);
864     return;
865   }
866
867   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
868       shadow_mem, cur);
869 }
870
871 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
872                            u64 val) {
873   (void)thr;
874   (void)pc;
875   if (size == 0)
876     return;
877   // FIXME: fix me.
878   uptr offset = addr % kShadowCell;
879   if (offset) {
880     offset = kShadowCell - offset;
881     if (size <= offset)
882       return;
883     addr += offset;
884     size -= offset;
885   }
886   DCHECK_EQ(addr % 8, 0);
887   // If a user passes some insane arguments (memset(0)),
888   // let it just crash as usual.
889   if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
890     return;
891   // Don't want to touch lots of shadow memory.
892   // If a program maps 10MB stack, there is no need reset the whole range.
893   size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
894   // UnmapOrDie/MmapFixedNoReserve does not work on Windows.
895   if (SANITIZER_WINDOWS || size < common_flags()->clear_shadow_mmap_threshold) {
896     u64 *p = (u64*)MemToShadow(addr);
897     CHECK(IsShadowMem((uptr)p));
898     CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
899     // FIXME: may overwrite a part outside the region
900     for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
901       p[i++] = val;
902       for (uptr j = 1; j < kShadowCnt; j++)
903         p[i++] = 0;
904     }
905   } else {
906     // The region is big, reset only beginning and end.
907     const uptr kPageSize = GetPageSizeCached();
908     u64 *begin = (u64*)MemToShadow(addr);
909     u64 *end = begin + size / kShadowCell * kShadowCnt;
910     u64 *p = begin;
911     // Set at least first kPageSize/2 to page boundary.
912     while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
913       *p++ = val;
914       for (uptr j = 1; j < kShadowCnt; j++)
915         *p++ = 0;
916     }
917     // Reset middle part.
918     u64 *p1 = p;
919     p = RoundDown(end, kPageSize);
920     UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
921     MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1);
922     // Set the ending.
923     while (p < end) {
924       *p++ = val;
925       for (uptr j = 1; j < kShadowCnt; j++)
926         *p++ = 0;
927     }
928   }
929 }
930
931 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
932   MemoryRangeSet(thr, pc, addr, size, 0);
933 }
934
935 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
936   // Processing more than 1k (4k of shadow) is expensive,
937   // can cause excessive memory consumption (user does not necessary touch
938   // the whole range) and most likely unnecessary.
939   if (size > 1024)
940     size = 1024;
941   CHECK_EQ(thr->is_freeing, false);
942   thr->is_freeing = true;
943   MemoryAccessRange(thr, pc, addr, size, true);
944   thr->is_freeing = false;
945   if (kCollectHistory) {
946     thr->fast_state.IncrementEpoch();
947     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
948   }
949   Shadow s(thr->fast_state);
950   s.ClearIgnoreBit();
951   s.MarkAsFreed();
952   s.SetWrite(true);
953   s.SetAddr0AndSizeLog(0, 3);
954   MemoryRangeSet(thr, pc, addr, size, s.raw());
955 }
956
957 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
958   if (kCollectHistory) {
959     thr->fast_state.IncrementEpoch();
960     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
961   }
962   Shadow s(thr->fast_state);
963   s.ClearIgnoreBit();
964   s.SetWrite(true);
965   s.SetAddr0AndSizeLog(0, 3);
966   MemoryRangeSet(thr, pc, addr, size, s.raw());
967 }
968
969 ALWAYS_INLINE USED
970 void FuncEntry(ThreadState *thr, uptr pc) {
971   StatInc(thr, StatFuncEnter);
972   DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
973   if (kCollectHistory) {
974     thr->fast_state.IncrementEpoch();
975     TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
976   }
977
978   // Shadow stack maintenance can be replaced with
979   // stack unwinding during trace switch (which presumably must be faster).
980   DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
981 #if !SANITIZER_GO
982   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
983 #else
984   if (thr->shadow_stack_pos == thr->shadow_stack_end)
985     GrowShadowStack(thr);
986 #endif
987   thr->shadow_stack_pos[0] = pc;
988   thr->shadow_stack_pos++;
989 }
990
991 ALWAYS_INLINE USED
992 void FuncExit(ThreadState *thr) {
993   StatInc(thr, StatFuncExit);
994   DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
995   if (kCollectHistory) {
996     thr->fast_state.IncrementEpoch();
997     TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
998   }
999
1000   DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
1001 #if !SANITIZER_GO
1002   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1003 #endif
1004   thr->shadow_stack_pos--;
1005 }
1006
1007 void ThreadIgnoreBegin(ThreadState *thr, uptr pc, bool save_stack) {
1008   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
1009   thr->ignore_reads_and_writes++;
1010   CHECK_GT(thr->ignore_reads_and_writes, 0);
1011   thr->fast_state.SetIgnoreBit();
1012 #if !SANITIZER_GO
1013   if (save_stack && !ctx->after_multithreaded_fork)
1014     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
1015 #endif
1016 }
1017
1018 void ThreadIgnoreEnd(ThreadState *thr, uptr pc) {
1019   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
1020   CHECK_GT(thr->ignore_reads_and_writes, 0);
1021   thr->ignore_reads_and_writes--;
1022   if (thr->ignore_reads_and_writes == 0) {
1023     thr->fast_state.ClearIgnoreBit();
1024 #if !SANITIZER_GO
1025     thr->mop_ignore_set.Reset();
1026 #endif
1027   }
1028 }
1029
1030 #if !SANITIZER_GO
1031 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
1032 uptr __tsan_testonly_shadow_stack_current_size() {
1033   ThreadState *thr = cur_thread();
1034   return thr->shadow_stack_pos - thr->shadow_stack;
1035 }
1036 #endif
1037
1038 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc, bool save_stack) {
1039   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1040   thr->ignore_sync++;
1041   CHECK_GT(thr->ignore_sync, 0);
1042 #if !SANITIZER_GO
1043   if (save_stack && !ctx->after_multithreaded_fork)
1044     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1045 #endif
1046 }
1047
1048 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) {
1049   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1050   CHECK_GT(thr->ignore_sync, 0);
1051   thr->ignore_sync--;
1052 #if !SANITIZER_GO
1053   if (thr->ignore_sync == 0)
1054     thr->sync_ignore_set.Reset();
1055 #endif
1056 }
1057
1058 bool MD5Hash::operator==(const MD5Hash &other) const {
1059   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1060 }
1061
1062 #if SANITIZER_DEBUG
1063 void build_consistency_debug() {}
1064 #else
1065 void build_consistency_release() {}
1066 #endif
1067
1068 #if TSAN_COLLECT_STATS
1069 void build_consistency_stats() {}
1070 #else
1071 void build_consistency_nostats() {}
1072 #endif
1073
1074 }  // namespace __tsan
1075
1076 #if !SANITIZER_GO
1077 // Must be included in this file to make sure everything is inlined.
1078 #include "tsan_interface_inl.h"
1079 #endif