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 "tsan_rtl.h"
15 
16 #include "sanitizer_common/sanitizer_atomic.h"
17 #include "sanitizer_common/sanitizer_common.h"
18 #include "sanitizer_common/sanitizer_file.h"
19 #include "sanitizer_common/sanitizer_libc.h"
20 #include "sanitizer_common/sanitizer_placement_new.h"
21 #include "sanitizer_common/sanitizer_stackdepot.h"
22 #include "sanitizer_common/sanitizer_symbolizer.h"
23 #include "tsan_defs.h"
24 #include "tsan_interface.h"
25 #include "tsan_mman.h"
26 #include "tsan_platform.h"
27 #include "tsan_suppressions.h"
28 #include "tsan_symbolize.h"
29 #include "ubsan/ubsan_init.h"
30 
31 volatile int __tsan_resumed = 0;
32 
33 extern "C" void __tsan_resume() {
34   __tsan_resumed = 1;
35 }
36 
37 namespace __tsan {
38 
39 #if !SANITIZER_GO
40 void (*on_initialize)(void);
41 int (*on_finalize)(int);
42 #endif
43 
44 #if !SANITIZER_GO && !SANITIZER_MAC
45 __attribute__((tls_model("initial-exec")))
46 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
47 #endif
48 static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
49 Context *ctx;
50 
51 // Can be overriden by a front-end.
52 #ifdef TSAN_EXTERNAL_HOOKS
53 bool OnFinalize(bool failed);
54 void OnInitialize();
55 #else
56 #include <dlfcn.h>
57 SANITIZER_WEAK_CXX_DEFAULT_IMPL
58 bool OnFinalize(bool failed) {
59 #if !SANITIZER_GO
60   if (on_finalize)
61     return on_finalize(failed);
62 #endif
63   return failed;
64 }
65 SANITIZER_WEAK_CXX_DEFAULT_IMPL
66 void OnInitialize() {
67 #if !SANITIZER_GO
68   if (on_initialize)
69     on_initialize();
70 #endif
71 }
72 #endif
73 
74 static ThreadContextBase *CreateThreadContext(Tid tid) {
75   // Map thread trace when context is created.
76   char name[50];
77   internal_snprintf(name, sizeof(name), "trace %u", tid);
78   MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
79   const uptr hdr = GetThreadTraceHeader(tid);
80   internal_snprintf(name, sizeof(name), "trace header %u", tid);
81   MapThreadTrace(hdr, sizeof(Trace), name);
82   new((void*)hdr) Trace();
83   // We are going to use only a small part of the trace with the default
84   // value of history_size. However, the constructor writes to the whole trace.
85   // Release the unused part.
86   uptr hdr_end = hdr + sizeof(Trace);
87   hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
88   hdr_end = RoundUp(hdr_end, GetPageSizeCached());
89   if (hdr_end < hdr + sizeof(Trace)) {
90     ReleaseMemoryPagesToOS(hdr_end, hdr + sizeof(Trace));
91     uptr unused = hdr + sizeof(Trace) - hdr_end;
92     if (hdr_end != (uptr)MmapFixedNoAccess(hdr_end, unused)) {
93       Report("ThreadSanitizer: failed to mprotect [0x%zx-0x%zx) \n", hdr_end,
94              unused);
95       CHECK("unable to mprotect" && 0);
96     }
97   }
98   return New<ThreadContext>(tid);
99 }
100 
101 #if !SANITIZER_GO
102 static const u32 kThreadQuarantineSize = 16;
103 #else
104 static const u32 kThreadQuarantineSize = 64;
105 #endif
106 
107 Context::Context()
108     : initialized(),
109       report_mtx(MutexTypeReport),
110       nreported(),
111       thread_registry(CreateThreadContext, kMaxTid, kThreadQuarantineSize,
112                       kMaxTidReuse),
113       racy_mtx(MutexTypeRacy),
114       racy_stacks(),
115       racy_addresses(),
116       fired_suppressions_mtx(MutexTypeFired),
117       clock_alloc(LINKER_INITIALIZED, "clock allocator") {
118   fired_suppressions.reserve(8);
119 }
120 
121 // The objects are allocated in TLS, so one may rely on zero-initialization.
122 ThreadState::ThreadState(Context *ctx, Tid tid, int unique_id, u64 epoch,
123                          unsigned reuse_count, uptr stk_addr, uptr stk_size,
124                          uptr tls_addr, uptr tls_size)
125     : fast_state(tid, epoch)
126       // Do not touch these, rely on zero initialization,
127       // they may be accessed before the ctor.
128       // , ignore_reads_and_writes()
129       // , ignore_interceptors()
130       ,
131       clock(tid, reuse_count)
132 #if !SANITIZER_GO
133       ,
134       jmp_bufs()
135 #endif
136       ,
137       tid(tid),
138       unique_id(unique_id),
139       stk_addr(stk_addr),
140       stk_size(stk_size),
141       tls_addr(tls_addr),
142       tls_size(tls_size)
143 #if !SANITIZER_GO
144       ,
145       last_sleep_clock(tid)
146 #endif
147 {
148 }
149 
150 #if !SANITIZER_GO
151 void MemoryProfiler(u64 uptime) {
152   if (ctx->memprof_fd == kInvalidFd)
153     return;
154   InternalMmapVector<char> buf(4096);
155   WriteMemoryProfile(buf.data(), buf.size(), uptime);
156   WriteToFile(ctx->memprof_fd, buf.data(), internal_strlen(buf.data()));
157 }
158 
159 void InitializeMemoryProfiler() {
160   ctx->memprof_fd = kInvalidFd;
161   const char *fname = flags()->profile_memory;
162   if (!fname || !fname[0])
163     return;
164   if (internal_strcmp(fname, "stdout") == 0) {
165     ctx->memprof_fd = 1;
166   } else if (internal_strcmp(fname, "stderr") == 0) {
167     ctx->memprof_fd = 2;
168   } else {
169     InternalScopedString filename;
170     filename.append("%s.%d", fname, (int)internal_getpid());
171     ctx->memprof_fd = OpenFile(filename.data(), WrOnly);
172     if (ctx->memprof_fd == kInvalidFd) {
173       Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
174              filename.data());
175       return;
176     }
177   }
178   MemoryProfiler(0);
179   MaybeSpawnBackgroundThread();
180 }
181 
182 static void *BackgroundThread(void *arg) {
183   // This is a non-initialized non-user thread, nothing to see here.
184   // We don't use ScopedIgnoreInterceptors, because we want ignores to be
185   // enabled even when the thread function exits (e.g. during pthread thread
186   // shutdown code).
187   cur_thread_init();
188   cur_thread()->ignore_interceptors++;
189   const u64 kMs2Ns = 1000 * 1000;
190   const u64 start = NanoTime();
191 
192   u64 last_flush = NanoTime();
193   uptr last_rss = 0;
194   for (int i = 0;
195       atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
196       i++) {
197     SleepForMillis(100);
198     u64 now = NanoTime();
199 
200     // Flush memory if requested.
201     if (flags()->flush_memory_ms > 0) {
202       if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
203         VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
204         FlushShadowMemory();
205         last_flush = NanoTime();
206       }
207     }
208     if (flags()->memory_limit_mb > 0) {
209       uptr rss = GetRSS();
210       uptr limit = uptr(flags()->memory_limit_mb) << 20;
211       VPrintf(1, "ThreadSanitizer: memory flush check"
212                  " RSS=%llu LAST=%llu LIMIT=%llu\n",
213               (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
214       if (2 * rss > limit + last_rss) {
215         VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
216         FlushShadowMemory();
217         rss = GetRSS();
218         VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
219       }
220       last_rss = rss;
221     }
222 
223     MemoryProfiler(now - start);
224 
225     // Flush symbolizer cache if requested.
226     if (flags()->flush_symbolizer_ms > 0) {
227       u64 last = atomic_load(&ctx->last_symbolize_time_ns,
228                              memory_order_relaxed);
229       if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
230         Lock l(&ctx->report_mtx);
231         ScopedErrorReportLock l2;
232         SymbolizeFlush();
233         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
234       }
235     }
236   }
237   return nullptr;
238 }
239 
240 static void StartBackgroundThread() {
241   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
242 }
243 
244 #ifndef __mips__
245 static void StopBackgroundThread() {
246   atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
247   internal_join_thread(ctx->background_thread);
248   ctx->background_thread = 0;
249 }
250 #endif
251 #endif
252 
253 void DontNeedShadowFor(uptr addr, uptr size) {
254   ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)),
255                          reinterpret_cast<uptr>(MemToShadow(addr + size)));
256 }
257 
258 #if !SANITIZER_GO
259 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
260   if (size == 0) return;
261   DontNeedShadowFor(addr, size);
262   ScopedGlobalProcessor sgp;
263   ctx->metamap.ResetRange(thr->proc(), addr, size);
264 }
265 #endif
266 
267 void MapShadow(uptr addr, uptr size) {
268   // Global data is not 64K aligned, but there are no adjacent mappings,
269   // so we can get away with unaligned mapping.
270   // CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
271   const uptr kPageSize = GetPageSizeCached();
272   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
273   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
274   if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
275                                "shadow"))
276     Die();
277 
278   // Meta shadow is 2:1, so tread carefully.
279   static bool data_mapped = false;
280   static uptr mapped_meta_end = 0;
281   uptr meta_begin = (uptr)MemToMeta(addr);
282   uptr meta_end = (uptr)MemToMeta(addr + size);
283   meta_begin = RoundDownTo(meta_begin, 64 << 10);
284   meta_end = RoundUpTo(meta_end, 64 << 10);
285   if (!data_mapped) {
286     // First call maps data+bss.
287     data_mapped = true;
288     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
289                                  "meta shadow"))
290       Die();
291   } else {
292     // Mapping continuous heap.
293     // Windows wants 64K alignment.
294     meta_begin = RoundDownTo(meta_begin, 64 << 10);
295     meta_end = RoundUpTo(meta_end, 64 << 10);
296     if (meta_end <= mapped_meta_end)
297       return;
298     if (meta_begin < mapped_meta_end)
299       meta_begin = mapped_meta_end;
300     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
301                                  "meta shadow"))
302       Die();
303     mapped_meta_end = meta_end;
304   }
305   VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr,
306           addr + size, meta_begin, meta_end);
307 }
308 
309 void MapThreadTrace(uptr addr, uptr size, const char *name) {
310   DPrintf("#0: Mapping trace at 0x%zx-0x%zx(0x%zx)\n", addr, addr + size, size);
311   CHECK_GE(addr, TraceMemBeg());
312   CHECK_LE(addr + size, TraceMemEnd());
313   CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
314   if (!MmapFixedSuperNoReserve(addr, size, name)) {
315     Printf("FATAL: ThreadSanitizer can not mmap thread trace (0x%zx/0x%zx)\n",
316            addr, size);
317     Die();
318   }
319 }
320 
321 #if !SANITIZER_GO
322 static void OnStackUnwind(const SignalContext &sig, const void *,
323                           BufferedStackTrace *stack) {
324   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
325                 common_flags()->fast_unwind_on_fatal);
326 }
327 
328 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
329   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
330 }
331 #endif
332 
333 void CheckUnwind() {
334   // There is high probability that interceptors will check-fail as well,
335   // on the other hand there is no sense in processing interceptors
336   // since we are going to die soon.
337   ScopedIgnoreInterceptors ignore;
338 #if !SANITIZER_GO
339   cur_thread()->ignore_sync++;
340   cur_thread()->ignore_reads_and_writes++;
341 #endif
342   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
343 }
344 
345 bool is_initialized;
346 
347 void Initialize(ThreadState *thr) {
348   // Thread safe because done before all threads exist.
349   if (is_initialized)
350     return;
351   is_initialized = true;
352   // We are not ready to handle interceptors yet.
353   ScopedIgnoreInterceptors ignore;
354   SanitizerToolName = "ThreadSanitizer";
355   // Install tool-specific callbacks in sanitizer_common.
356   SetCheckUnwindCallback(CheckUnwind);
357 
358   ctx = new(ctx_placeholder) Context;
359   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
360   const char *options = GetEnv(env_name);
361   CacheBinaryName();
362   CheckASLR();
363   InitializeFlags(&ctx->flags, options, env_name);
364   AvoidCVE_2016_2143();
365   __sanitizer::InitializePlatformEarly();
366   __tsan::InitializePlatformEarly();
367 
368 #if !SANITIZER_GO
369   // Re-exec ourselves if we need to set additional env or command line args.
370   MaybeReexec();
371 
372   InitializeAllocator();
373   ReplaceSystemMalloc();
374 #endif
375   if (common_flags()->detect_deadlocks)
376     ctx->dd = DDetector::Create(flags());
377   Processor *proc = ProcCreate();
378   ProcWire(proc, thr);
379   InitializeInterceptors();
380   InitializePlatform();
381   InitializeDynamicAnnotations();
382 #if !SANITIZER_GO
383   InitializeShadowMemory();
384   InitializeAllocatorLate();
385   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
386 #endif
387   // Setup correct file descriptor for error reports.
388   __sanitizer_set_report_path(common_flags()->log_path);
389   InitializeSuppressions();
390 #if !SANITIZER_GO
391   InitializeLibIgnore();
392   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
393 #endif
394 
395   VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
396           (int)internal_getpid());
397 
398   // Initialize thread 0.
399   Tid tid = ThreadCreate(thr, 0, 0, true);
400   CHECK_EQ(tid, kMainTid);
401   ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
402 #if TSAN_CONTAINS_UBSAN
403   __ubsan::InitAsPlugin();
404 #endif
405   ctx->initialized = true;
406 
407 #if !SANITIZER_GO
408   Symbolizer::LateInitialize();
409   InitializeMemoryProfiler();
410 #endif
411 
412   if (flags()->stop_on_start) {
413     Printf("ThreadSanitizer is suspended at startup (pid %d)."
414            " Call __tsan_resume().\n",
415            (int)internal_getpid());
416     while (__tsan_resumed == 0) {}
417   }
418 
419   OnInitialize();
420 }
421 
422 void MaybeSpawnBackgroundThread() {
423   // On MIPS, TSan initialization is run before
424   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
425   // new threads.
426 #if !SANITIZER_GO && !defined(__mips__)
427   static atomic_uint32_t bg_thread = {};
428   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
429       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
430     StartBackgroundThread();
431     SetSandboxingCallback(StopBackgroundThread);
432   }
433 #endif
434 }
435 
436 
437 int Finalize(ThreadState *thr) {
438   bool failed = false;
439 
440   if (common_flags()->print_module_map == 1)
441     DumpProcessMap();
442 
443   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
444     SleepForMillis(flags()->atexit_sleep_ms);
445 
446   // Wait for pending reports.
447   ctx->report_mtx.Lock();
448   { ScopedErrorReportLock l; }
449   ctx->report_mtx.Unlock();
450 
451 #if !SANITIZER_GO
452   if (Verbosity()) AllocatorPrintStats();
453 #endif
454 
455   ThreadFinalize(thr);
456 
457   if (ctx->nreported) {
458     failed = true;
459 #if !SANITIZER_GO
460     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
461 #else
462     Printf("Found %d data race(s)\n", ctx->nreported);
463 #endif
464   }
465 
466   if (common_flags()->print_suppressions)
467     PrintMatchedSuppressions();
468 
469   failed = OnFinalize(failed);
470 
471   return failed ? common_flags()->exitcode : 0;
472 }
473 
474 #if !SANITIZER_GO
475 void ForkBefore(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
476   ctx->thread_registry.Lock();
477   ctx->report_mtx.Lock();
478   ScopedErrorReportLock::Lock();
479   // Suppress all reports in the pthread_atfork callbacks.
480   // Reports will deadlock on the report_mtx.
481   // We could ignore sync operations as well,
482   // but so far it's unclear if it will do more good or harm.
483   // Unnecessarily ignoring things can lead to false positives later.
484   thr->suppress_reports++;
485   // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
486   // we'll assert in CheckNoLocks() unless we ignore interceptors.
487   thr->ignore_interceptors++;
488 }
489 
490 void ForkParentAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
491   thr->suppress_reports--;  // Enabled in ForkBefore.
492   thr->ignore_interceptors--;
493   ScopedErrorReportLock::Unlock();
494   ctx->report_mtx.Unlock();
495   ctx->thread_registry.Unlock();
496 }
497 
498 void ForkChildAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
499   thr->suppress_reports--;  // Enabled in ForkBefore.
500   thr->ignore_interceptors--;
501   ScopedErrorReportLock::Unlock();
502   ctx->report_mtx.Unlock();
503   ctx->thread_registry.Unlock();
504 
505   uptr nthread = 0;
506   ctx->thread_registry.GetNumberOfThreads(0, 0, &nthread /* alive threads */);
507   VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
508       " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
509   if (nthread == 1) {
510     StartBackgroundThread();
511   } else {
512     // We've just forked a multi-threaded process. We cannot reasonably function
513     // after that (some mutexes may be locked before fork). So just enable
514     // ignores for everything in the hope that we will exec soon.
515     ctx->after_multithreaded_fork = true;
516     thr->ignore_interceptors++;
517     ThreadIgnoreBegin(thr, pc);
518     ThreadIgnoreSyncBegin(thr, pc);
519   }
520 }
521 #endif
522 
523 #if SANITIZER_GO
524 NOINLINE
525 void GrowShadowStack(ThreadState *thr) {
526   const int sz = thr->shadow_stack_end - thr->shadow_stack;
527   const int newsz = 2 * sz;
528   auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr));
529   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
530   Free(thr->shadow_stack);
531   thr->shadow_stack = newstack;
532   thr->shadow_stack_pos = newstack + sz;
533   thr->shadow_stack_end = newstack + newsz;
534 }
535 #endif
536 
537 StackID CurrentStackId(ThreadState *thr, uptr pc) {
538   if (!thr->is_inited)  // May happen during bootstrap.
539     return kInvalidStackID;
540   if (pc != 0) {
541 #if !SANITIZER_GO
542     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
543 #else
544     if (thr->shadow_stack_pos == thr->shadow_stack_end)
545       GrowShadowStack(thr);
546 #endif
547     thr->shadow_stack_pos[0] = pc;
548     thr->shadow_stack_pos++;
549   }
550   StackID id = StackDepotPut(
551       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
552   if (pc != 0)
553     thr->shadow_stack_pos--;
554   return id;
555 }
556 
557 namespace v3 {
558 
559 ALWAYS_INLINE USED bool TryTraceMemoryAccess(ThreadState *thr, uptr pc,
560                                              uptr addr, uptr size,
561                                              AccessType typ) {
562   DCHECK(size == 1 || size == 2 || size == 4 || size == 8);
563   if (!kCollectHistory)
564     return true;
565   EventAccess *ev;
566   if (UNLIKELY(!TraceAcquire(thr, &ev)))
567     return false;
568   u64 size_log = size == 1 ? 0 : size == 2 ? 1 : size == 4 ? 2 : 3;
569   uptr pc_delta = pc - thr->trace_prev_pc + (1 << (EventAccess::kPCBits - 1));
570   thr->trace_prev_pc = pc;
571   if (LIKELY(pc_delta < (1 << EventAccess::kPCBits))) {
572     ev->is_access = 1;
573     ev->is_read = !!(typ & kAccessRead);
574     ev->is_atomic = !!(typ & kAccessAtomic);
575     ev->size_log = size_log;
576     ev->pc_delta = pc_delta;
577     DCHECK_EQ(ev->pc_delta, pc_delta);
578     ev->addr = CompressAddr(addr);
579     TraceRelease(thr, ev);
580     return true;
581   }
582   auto *evex = reinterpret_cast<EventAccessExt *>(ev);
583   evex->is_access = 0;
584   evex->is_func = 0;
585   evex->type = EventType::kAccessExt;
586   evex->is_read = !!(typ & kAccessRead);
587   evex->is_atomic = !!(typ & kAccessAtomic);
588   evex->size_log = size_log;
589   evex->addr = CompressAddr(addr);
590   evex->pc = pc;
591   TraceRelease(thr, evex);
592   return true;
593 }
594 
595 ALWAYS_INLINE USED bool TryTraceMemoryAccessRange(ThreadState *thr, uptr pc,
596                                                   uptr addr, uptr size,
597                                                   AccessType typ) {
598   if (!kCollectHistory)
599     return true;
600   EventAccessRange *ev;
601   if (UNLIKELY(!TraceAcquire(thr, &ev)))
602     return false;
603   thr->trace_prev_pc = pc;
604   ev->is_access = 0;
605   ev->is_func = 0;
606   ev->type = EventType::kAccessRange;
607   ev->is_read = !!(typ & kAccessRead);
608   ev->is_free = !!(typ & kAccessFree);
609   ev->size_lo = size;
610   ev->pc = CompressAddr(pc);
611   ev->addr = CompressAddr(addr);
612   ev->size_hi = size >> EventAccessRange::kSizeLoBits;
613   TraceRelease(thr, ev);
614   return true;
615 }
616 
617 void TraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
618                             AccessType typ) {
619   if (LIKELY(TryTraceMemoryAccessRange(thr, pc, addr, size, typ)))
620     return;
621   TraceSwitchPart(thr);
622   UNUSED bool res = TryTraceMemoryAccessRange(thr, pc, addr, size, typ);
623   DCHECK(res);
624 }
625 
626 void TraceFunc(ThreadState *thr, uptr pc) {
627   if (LIKELY(TryTraceFunc(thr, pc)))
628     return;
629   TraceSwitchPart(thr);
630   UNUSED bool res = TryTraceFunc(thr, pc);
631   DCHECK(res);
632 }
633 
634 void TraceMutexLock(ThreadState *thr, EventType type, uptr pc, uptr addr,
635                     StackID stk) {
636   DCHECK(type == EventType::kLock || type == EventType::kRLock);
637   if (!kCollectHistory)
638     return;
639   EventLock ev;
640   ev.is_access = 0;
641   ev.is_func = 0;
642   ev.type = type;
643   ev.pc = CompressAddr(pc);
644   ev.stack_lo = stk;
645   ev.stack_hi = stk >> EventLock::kStackIDLoBits;
646   ev._ = 0;
647   ev.addr = CompressAddr(addr);
648   TraceEvent(thr, ev);
649 }
650 
651 void TraceMutexUnlock(ThreadState *thr, uptr addr) {
652   if (!kCollectHistory)
653     return;
654   EventUnlock ev;
655   ev.is_access = 0;
656   ev.is_func = 0;
657   ev.type = EventType::kUnlock;
658   ev._ = 0;
659   ev.addr = CompressAddr(addr);
660   TraceEvent(thr, ev);
661 }
662 
663 void TraceTime(ThreadState *thr) {
664   if (!kCollectHistory)
665     return;
666   EventTime ev;
667   ev.is_access = 0;
668   ev.is_func = 0;
669   ev.type = EventType::kTime;
670   ev.sid = static_cast<u64>(thr->sid);
671   ev.epoch = static_cast<u64>(thr->epoch);
672   ev._ = 0;
673   TraceEvent(thr, ev);
674 }
675 
676 NOINLINE
677 void TraceSwitchPart(ThreadState *thr) {
678   Trace *trace = &thr->tctx->trace;
679   Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
680   DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0);
681   auto *part = trace->parts.Back();
682   DPrintf("TraceSwitchPart part=%p pos=%p\n", part, pos);
683   if (part) {
684     // We can get here when we still have space in the current trace part.
685     // The fast-path check in TraceAcquire has false positives in the middle of
686     // the part. Check if we are indeed at the end of the current part or not,
687     // and fill any gaps with NopEvent's.
688     Event *end = &part->events[TracePart::kSize];
689     DCHECK_GE(pos, &part->events[0]);
690     DCHECK_LE(pos, end);
691     if (pos + 1 < end) {
692       if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) ==
693           TracePart::kAlignment)
694         *pos++ = NopEvent;
695       *pos++ = NopEvent;
696       DCHECK_LE(pos + 2, end);
697       atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos));
698       // Ensure we setup trace so that the next TraceAcquire
699       // won't detect trace part end.
700       Event *ev;
701       CHECK(TraceAcquire(thr, &ev));
702       return;
703     }
704     // We are indeed at the end.
705     for (; pos < end; pos++) *pos = NopEvent;
706   }
707 #if !SANITIZER_GO
708   if (ctx->after_multithreaded_fork) {
709     // We just need to survive till exec.
710     CHECK(part);
711     atomic_store_relaxed(&thr->trace_pos,
712                          reinterpret_cast<uptr>(&part->events[0]));
713     return;
714   }
715 #endif
716   part = new (MmapOrDie(sizeof(TracePart), "TracePart")) TracePart();
717   part->trace = trace;
718   thr->trace_prev_pc = 0;
719   {
720     Lock lock(&trace->mtx);
721     trace->parts.PushBack(part);
722     atomic_store_relaxed(&thr->trace_pos,
723                          reinterpret_cast<uptr>(&part->events[0]));
724   }
725   // Make this part self-sufficient by restoring the current stack
726   // and mutex set in the beginning of the trace.
727   TraceTime(thr);
728   for (uptr *pos = &thr->shadow_stack[0]; pos < thr->shadow_stack_pos; pos++)
729     CHECK(TryTraceFunc(thr, *pos));
730   for (uptr i = 0; i < thr->mset.Size(); i++) {
731     MutexSet::Desc d = thr->mset.Get(i);
732     TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0,
733                    d.addr, d.stack_id);
734   }
735 }
736 
737 }  // namespace v3
738 
739 void TraceSwitch(ThreadState *thr) {
740 #if !SANITIZER_GO
741   if (ctx->after_multithreaded_fork)
742     return;
743 #endif
744   thr->nomalloc++;
745   Trace *thr_trace = ThreadTrace(thr->tid);
746   Lock l(&thr_trace->mtx);
747   unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
748   TraceHeader *hdr = &thr_trace->headers[trace];
749   hdr->epoch0 = thr->fast_state.epoch();
750   ObtainCurrentStack(thr, 0, &hdr->stack0);
751   hdr->mset0 = thr->mset;
752   thr->nomalloc--;
753 }
754 
755 Trace *ThreadTrace(Tid tid) { return (Trace *)GetThreadTraceHeader(tid); }
756 
757 uptr TraceTopPC(ThreadState *thr) {
758   Event *events = (Event*)GetThreadTrace(thr->tid);
759   uptr pc = events[thr->fast_state.GetTracePos()];
760   return pc;
761 }
762 
763 uptr TraceSize() {
764   return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
765 }
766 
767 uptr TraceParts() {
768   return TraceSize() / kTracePartSize;
769 }
770 
771 #if !SANITIZER_GO
772 extern "C" void __tsan_trace_switch() {
773   TraceSwitch(cur_thread());
774 }
775 
776 extern "C" void __tsan_report_race() {
777   ReportRace(cur_thread());
778 }
779 #endif
780 
781 ALWAYS_INLINE
782 Shadow LoadShadow(u64 *p) {
783   u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
784   return Shadow(raw);
785 }
786 
787 ALWAYS_INLINE
788 void StoreShadow(u64 *sp, u64 s) {
789   atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
790 }
791 
792 ALWAYS_INLINE
793 void StoreIfNotYetStored(u64 *sp, u64 *s) {
794   StoreShadow(sp, *s);
795   *s = 0;
796 }
797 
798 ALWAYS_INLINE
799 void HandleRace(ThreadState *thr, u64 *shadow_mem,
800                               Shadow cur, Shadow old) {
801   thr->racy_state[0] = cur.raw();
802   thr->racy_state[1] = old.raw();
803   thr->racy_shadow_addr = shadow_mem;
804 #if !SANITIZER_GO
805   HACKY_CALL(__tsan_report_race);
806 #else
807   ReportRace(thr);
808 #endif
809 }
810 
811 static inline bool HappensBefore(Shadow old, ThreadState *thr) {
812   return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
813 }
814 
815 ALWAYS_INLINE
816 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
817     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
818     u64 *shadow_mem, Shadow cur) {
819 
820   // This potentially can live in an MMX/SSE scratch register.
821   // The required intrinsics are:
822   // __m128i _mm_move_epi64(__m128i*);
823   // _mm_storel_epi64(u64*, __m128i);
824   u64 store_word = cur.raw();
825   bool stored = false;
826 
827   // scan all the shadow values and dispatch to 4 categories:
828   // same, replace, candidate and race (see comments below).
829   // we consider only 3 cases regarding access sizes:
830   // equal, intersect and not intersect. initially I considered
831   // larger and smaller as well, it allowed to replace some
832   // 'candidates' with 'same' or 'replace', but I think
833   // it's just not worth it (performance- and complexity-wise).
834 
835   Shadow old(0);
836 
837   // It release mode we manually unroll the loop,
838   // because empirically gcc generates better code this way.
839   // However, we can't afford unrolling in debug mode, because the function
840   // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
841   // threads, which is not enough for the unrolled loop.
842 #if SANITIZER_DEBUG
843   for (int idx = 0; idx < 4; idx++) {
844 #  include "tsan_update_shadow_word.inc"
845   }
846 #else
847   int idx = 0;
848 #  include "tsan_update_shadow_word.inc"
849   idx = 1;
850   if (stored) {
851 #  include "tsan_update_shadow_word.inc"
852   } else {
853 #  include "tsan_update_shadow_word.inc"
854   }
855   idx = 2;
856   if (stored) {
857 #  include "tsan_update_shadow_word.inc"
858   } else {
859 #  include "tsan_update_shadow_word.inc"
860   }
861   idx = 3;
862   if (stored) {
863 #  include "tsan_update_shadow_word.inc"
864   } else {
865 #  include "tsan_update_shadow_word.inc"
866   }
867 #endif
868 
869   // we did not find any races and had already stored
870   // the current access info, so we are done
871   if (LIKELY(stored))
872     return;
873   // choose a random candidate slot and replace it
874   StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
875   return;
876  RACE:
877   HandleRace(thr, shadow_mem, cur, old);
878   return;
879 }
880 
881 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
882                            AccessType typ) {
883   DCHECK(!(typ & kAccessAtomic));
884   const bool kAccessIsWrite = !(typ & kAccessRead);
885   const bool kIsAtomic = false;
886   while (size) {
887     int size1 = 1;
888     int kAccessSizeLog = kSizeLog1;
889     if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
890       size1 = 8;
891       kAccessSizeLog = kSizeLog8;
892     } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
893       size1 = 4;
894       kAccessSizeLog = kSizeLog4;
895     } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
896       size1 = 2;
897       kAccessSizeLog = kSizeLog2;
898     }
899     MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
900     addr += size1;
901     size -= size1;
902   }
903 }
904 
905 ALWAYS_INLINE
906 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
907   Shadow cur(a);
908   for (uptr i = 0; i < kShadowCnt; i++) {
909     Shadow old(LoadShadow(&s[i]));
910     if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
911         old.TidWithIgnore() == cur.TidWithIgnore() &&
912         old.epoch() > sync_epoch &&
913         old.IsAtomic() == cur.IsAtomic() &&
914         old.IsRead() <= cur.IsRead())
915       return true;
916   }
917   return false;
918 }
919 
920 #if TSAN_VECTORIZE
921 #  define SHUF(v0, v1, i0, i1, i2, i3)                    \
922     _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(v0), \
923                                     _mm_castsi128_ps(v1), \
924                                     (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
925 ALWAYS_INLINE
926 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
927   // This is an optimized version of ContainsSameAccessSlow.
928   // load current access into access[0:63]
929   const m128 access     = _mm_cvtsi64_si128(a);
930   // duplicate high part of access in addr0:
931   // addr0[0:31]        = access[32:63]
932   // addr0[32:63]       = access[32:63]
933   // addr0[64:95]       = access[32:63]
934   // addr0[96:127]      = access[32:63]
935   const m128 addr0      = SHUF(access, access, 1, 1, 1, 1);
936   // load 4 shadow slots
937   const m128 shadow0    = _mm_load_si128((__m128i*)s);
938   const m128 shadow1    = _mm_load_si128((__m128i*)s + 1);
939   // load high parts of 4 shadow slots into addr_vect:
940   // addr_vect[0:31]    = shadow0[32:63]
941   // addr_vect[32:63]   = shadow0[96:127]
942   // addr_vect[64:95]   = shadow1[32:63]
943   // addr_vect[96:127]  = shadow1[96:127]
944   m128 addr_vect        = SHUF(shadow0, shadow1, 1, 3, 1, 3);
945   if (!is_write) {
946     // set IsRead bit in addr_vect
947     const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
948     const m128 rw_mask  = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
949     addr_vect           = _mm_or_si128(addr_vect, rw_mask);
950   }
951   // addr0 == addr_vect?
952   const m128 addr_res   = _mm_cmpeq_epi32(addr0, addr_vect);
953   // epoch1[0:63]       = sync_epoch
954   const m128 epoch1     = _mm_cvtsi64_si128(sync_epoch);
955   // epoch[0:31]        = sync_epoch[0:31]
956   // epoch[32:63]       = sync_epoch[0:31]
957   // epoch[64:95]       = sync_epoch[0:31]
958   // epoch[96:127]      = sync_epoch[0:31]
959   const m128 epoch      = SHUF(epoch1, epoch1, 0, 0, 0, 0);
960   // load low parts of shadow cell epochs into epoch_vect:
961   // epoch_vect[0:31]   = shadow0[0:31]
962   // epoch_vect[32:63]  = shadow0[64:95]
963   // epoch_vect[64:95]  = shadow1[0:31]
964   // epoch_vect[96:127] = shadow1[64:95]
965   const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
966   // epoch_vect >= sync_epoch?
967   const m128 epoch_res  = _mm_cmpgt_epi32(epoch_vect, epoch);
968   // addr_res & epoch_res
969   const m128 res        = _mm_and_si128(addr_res, epoch_res);
970   // mask[0] = res[7]
971   // mask[1] = res[15]
972   // ...
973   // mask[15] = res[127]
974   const int mask        = _mm_movemask_epi8(res);
975   return mask != 0;
976 }
977 #endif
978 
979 ALWAYS_INLINE
980 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
981 #if TSAN_VECTORIZE
982   bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
983   // NOTE: this check can fail if the shadow is concurrently mutated
984   // by other threads. But it still can be useful if you modify
985   // ContainsSameAccessFast and want to ensure that it's not completely broken.
986   // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
987   return res;
988 #else
989   return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
990 #endif
991 }
992 
993 ALWAYS_INLINE USED
994 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
995     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
996   RawShadow *shadow_mem = MemToShadow(addr);
997   DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
998       " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
999       (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
1000       (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
1001       (uptr)shadow_mem[0], (uptr)shadow_mem[1],
1002       (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
1003 #if SANITIZER_DEBUG
1004   if (!IsAppMem(addr)) {
1005     Printf("Access to non app mem %zx\n", addr);
1006     DCHECK(IsAppMem(addr));
1007   }
1008   if (!IsShadowMem(shadow_mem)) {
1009     Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
1010     DCHECK(IsShadowMem(shadow_mem));
1011   }
1012 #endif
1013 
1014   if (!SANITIZER_GO && !kAccessIsWrite && *shadow_mem == kShadowRodata) {
1015     // Access to .rodata section, no races here.
1016     // Measurements show that it can be 10-20% of all memory accesses.
1017     return;
1018   }
1019 
1020   FastState fast_state = thr->fast_state;
1021   if (UNLIKELY(fast_state.GetIgnoreBit())) {
1022     return;
1023   }
1024 
1025   Shadow cur(fast_state);
1026   cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
1027   cur.SetWrite(kAccessIsWrite);
1028   cur.SetAtomic(kIsAtomic);
1029 
1030   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
1031       thr->fast_synch_epoch, kAccessIsWrite))) {
1032     return;
1033   }
1034 
1035   if (kCollectHistory) {
1036     fast_state.IncrementEpoch();
1037     thr->fast_state = fast_state;
1038     TraceAddEvent(thr, fast_state, EventTypeMop, pc);
1039     cur.IncrementEpoch();
1040   }
1041 
1042   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
1043       shadow_mem, cur);
1044 }
1045 
1046 // Called by MemoryAccessRange in tsan_rtl_thread.cpp
1047 ALWAYS_INLINE USED
1048 void MemoryAccessImpl(ThreadState *thr, uptr addr,
1049     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
1050     u64 *shadow_mem, Shadow cur) {
1051   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
1052       thr->fast_synch_epoch, kAccessIsWrite))) {
1053     return;
1054   }
1055 
1056   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
1057       shadow_mem, cur);
1058 }
1059 
1060 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
1061                            u64 val) {
1062   (void)thr;
1063   (void)pc;
1064   if (size == 0)
1065     return;
1066   // FIXME: fix me.
1067   uptr offset = addr % kShadowCell;
1068   if (offset) {
1069     offset = kShadowCell - offset;
1070     if (size <= offset)
1071       return;
1072     addr += offset;
1073     size -= offset;
1074   }
1075   DCHECK_EQ(addr % 8, 0);
1076   // If a user passes some insane arguments (memset(0)),
1077   // let it just crash as usual.
1078   if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
1079     return;
1080   // Don't want to touch lots of shadow memory.
1081   // If a program maps 10MB stack, there is no need reset the whole range.
1082   size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
1083   // UnmapOrDie/MmapFixedNoReserve does not work on Windows.
1084   if (SANITIZER_WINDOWS || size < common_flags()->clear_shadow_mmap_threshold) {
1085     RawShadow *p = MemToShadow(addr);
1086     CHECK(IsShadowMem(p));
1087     CHECK(IsShadowMem(p + size * kShadowCnt / kShadowCell - 1));
1088     // FIXME: may overwrite a part outside the region
1089     for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
1090       p[i++] = val;
1091       for (uptr j = 1; j < kShadowCnt; j++)
1092         p[i++] = 0;
1093     }
1094   } else {
1095     // The region is big, reset only beginning and end.
1096     const uptr kPageSize = GetPageSizeCached();
1097     RawShadow *begin = MemToShadow(addr);
1098     RawShadow *end = begin + size / kShadowCell * kShadowCnt;
1099     RawShadow *p = begin;
1100     // Set at least first kPageSize/2 to page boundary.
1101     while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
1102       *p++ = val;
1103       for (uptr j = 1; j < kShadowCnt; j++)
1104         *p++ = 0;
1105     }
1106     // Reset middle part.
1107     RawShadow *p1 = p;
1108     p = RoundDown(end, kPageSize);
1109     if (!MmapFixedSuperNoReserve((uptr)p1, (uptr)p - (uptr)p1))
1110       Die();
1111     // Set the ending.
1112     while (p < end) {
1113       *p++ = val;
1114       for (uptr j = 1; j < kShadowCnt; j++)
1115         *p++ = 0;
1116     }
1117   }
1118 }
1119 
1120 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1121   MemoryRangeSet(thr, pc, addr, size, 0);
1122 }
1123 
1124 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1125   // Processing more than 1k (4k of shadow) is expensive,
1126   // can cause excessive memory consumption (user does not necessary touch
1127   // the whole range) and most likely unnecessary.
1128   if (size > 1024)
1129     size = 1024;
1130   CHECK_EQ(thr->is_freeing, false);
1131   thr->is_freeing = true;
1132   MemoryAccessRange(thr, pc, addr, size, true);
1133   thr->is_freeing = false;
1134   if (kCollectHistory) {
1135     thr->fast_state.IncrementEpoch();
1136     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
1137   }
1138   Shadow s(thr->fast_state);
1139   s.ClearIgnoreBit();
1140   s.MarkAsFreed();
1141   s.SetWrite(true);
1142   s.SetAddr0AndSizeLog(0, 3);
1143   MemoryRangeSet(thr, pc, addr, size, s.raw());
1144 }
1145 
1146 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1147   if (kCollectHistory) {
1148     thr->fast_state.IncrementEpoch();
1149     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
1150   }
1151   Shadow s(thr->fast_state);
1152   s.ClearIgnoreBit();
1153   s.SetWrite(true);
1154   s.SetAddr0AndSizeLog(0, 3);
1155   MemoryRangeSet(thr, pc, addr, size, s.raw());
1156 }
1157 
1158 void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
1159                                          uptr size) {
1160   if (thr->ignore_reads_and_writes == 0)
1161     MemoryRangeImitateWrite(thr, pc, addr, size);
1162   else
1163     MemoryResetRange(thr, pc, addr, size);
1164 }
1165 
1166 ALWAYS_INLINE USED
1167 void FuncEntry(ThreadState *thr, uptr pc) {
1168   DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
1169   if (kCollectHistory) {
1170     thr->fast_state.IncrementEpoch();
1171     TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
1172   }
1173 
1174   // Shadow stack maintenance can be replaced with
1175   // stack unwinding during trace switch (which presumably must be faster).
1176   DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
1177 #if !SANITIZER_GO
1178   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1179 #else
1180   if (thr->shadow_stack_pos == thr->shadow_stack_end)
1181     GrowShadowStack(thr);
1182 #endif
1183   thr->shadow_stack_pos[0] = pc;
1184   thr->shadow_stack_pos++;
1185 }
1186 
1187 ALWAYS_INLINE USED
1188 void FuncExit(ThreadState *thr) {
1189   DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
1190   if (kCollectHistory) {
1191     thr->fast_state.IncrementEpoch();
1192     TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
1193   }
1194 
1195   DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
1196 #if !SANITIZER_GO
1197   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1198 #endif
1199   thr->shadow_stack_pos--;
1200 }
1201 
1202 void ThreadIgnoreBegin(ThreadState *thr, uptr pc) {
1203   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
1204   thr->ignore_reads_and_writes++;
1205   CHECK_GT(thr->ignore_reads_and_writes, 0);
1206   thr->fast_state.SetIgnoreBit();
1207 #if !SANITIZER_GO
1208   if (pc && !ctx->after_multithreaded_fork)
1209     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
1210 #endif
1211 }
1212 
1213 void ThreadIgnoreEnd(ThreadState *thr) {
1214   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
1215   CHECK_GT(thr->ignore_reads_and_writes, 0);
1216   thr->ignore_reads_and_writes--;
1217   if (thr->ignore_reads_and_writes == 0) {
1218     thr->fast_state.ClearIgnoreBit();
1219 #if !SANITIZER_GO
1220     thr->mop_ignore_set.Reset();
1221 #endif
1222   }
1223 }
1224 
1225 #if !SANITIZER_GO
1226 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
1227 uptr __tsan_testonly_shadow_stack_current_size() {
1228   ThreadState *thr = cur_thread();
1229   return thr->shadow_stack_pos - thr->shadow_stack;
1230 }
1231 #endif
1232 
1233 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
1234   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1235   thr->ignore_sync++;
1236   CHECK_GT(thr->ignore_sync, 0);
1237 #if !SANITIZER_GO
1238   if (pc && !ctx->after_multithreaded_fork)
1239     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1240 #endif
1241 }
1242 
1243 void ThreadIgnoreSyncEnd(ThreadState *thr) {
1244   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1245   CHECK_GT(thr->ignore_sync, 0);
1246   thr->ignore_sync--;
1247 #if !SANITIZER_GO
1248   if (thr->ignore_sync == 0)
1249     thr->sync_ignore_set.Reset();
1250 #endif
1251 }
1252 
1253 bool MD5Hash::operator==(const MD5Hash &other) const {
1254   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1255 }
1256 
1257 #if SANITIZER_DEBUG
1258 void build_consistency_debug() {}
1259 #else
1260 void build_consistency_release() {}
1261 #endif
1262 
1263 }  // namespace __tsan
1264 
1265 #if SANITIZER_CHECK_DEADLOCKS
1266 namespace __sanitizer {
1267 using namespace __tsan;
1268 MutexMeta mutex_meta[] = {
1269     {MutexInvalid, "Invalid", {}},
1270     {MutexThreadRegistry, "ThreadRegistry", {}},
1271     {MutexTypeTrace, "Trace", {MutexLeaf}},
1272     {MutexTypeReport, "Report", {MutexTypeSyncVar}},
1273     {MutexTypeSyncVar, "SyncVar", {}},
1274     {MutexTypeAnnotations, "Annotations", {}},
1275     {MutexTypeAtExit, "AtExit", {MutexTypeSyncVar}},
1276     {MutexTypeFired, "Fired", {MutexLeaf}},
1277     {MutexTypeRacy, "Racy", {MutexLeaf}},
1278     {MutexTypeGlobalProc, "GlobalProc", {}},
1279     {},
1280 };
1281 
1282 void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
1283 }  // namespace __sanitizer
1284 #endif
1285 
1286 #if !SANITIZER_GO
1287 // Must be included in this file to make sure everything is inlined.
1288 #  include "tsan_interface.inc"
1289 #endif
1290