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