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 SANITIZER_WEAK_DEFAULT_IMPL
38 void __tsan_test_only_on_fork() {}
39 
40 namespace __tsan {
41 
42 #if !SANITIZER_GO
43 void (*on_initialize)(void);
44 int (*on_finalize)(int);
45 #endif
46 
47 #if !SANITIZER_GO && !SANITIZER_MAC
48 __attribute__((tls_model("initial-exec")))
49 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(
50     SANITIZER_CACHE_LINE_SIZE);
51 #endif
52 static char ctx_placeholder[sizeof(Context)] ALIGNED(SANITIZER_CACHE_LINE_SIZE);
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 #include <dlfcn.h>
61 SANITIZER_WEAK_CXX_DEFAULT_IMPL
62 bool OnFinalize(bool failed) {
63 #if !SANITIZER_GO
64   if (on_finalize)
65     return on_finalize(failed);
66 #endif
67   return failed;
68 }
69 SANITIZER_WEAK_CXX_DEFAULT_IMPL
70 void OnInitialize() {
71 #if !SANITIZER_GO
72   if (on_initialize)
73     on_initialize();
74 #endif
75 }
76 #endif
77 
78 static ThreadContextBase *CreateThreadContext(Tid tid) {
79   // Map thread trace when context is created.
80   char name[50];
81   internal_snprintf(name, sizeof(name), "trace %u", tid);
82   MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
83   const uptr hdr = GetThreadTraceHeader(tid);
84   internal_snprintf(name, sizeof(name), "trace header %u", tid);
85   MapThreadTrace(hdr, sizeof(Trace), name);
86   new((void*)hdr) Trace();
87   // We are going to use only a small part of the trace with the default
88   // value of history_size. However, the constructor writes to the whole trace.
89   // Release the unused part.
90   uptr hdr_end = hdr + sizeof(Trace);
91   hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
92   hdr_end = RoundUp(hdr_end, GetPageSizeCached());
93   if (hdr_end < hdr + sizeof(Trace)) {
94     ReleaseMemoryPagesToOS(hdr_end, hdr + sizeof(Trace));
95     uptr unused = hdr + sizeof(Trace) - hdr_end;
96     if (hdr_end != (uptr)MmapFixedNoAccess(hdr_end, unused)) {
97       Report("ThreadSanitizer: failed to mprotect [0x%zx-0x%zx) \n", hdr_end,
98              unused);
99       CHECK("unable to mprotect" && 0);
100     }
101   }
102   return New<ThreadContext>(tid);
103 }
104 
105 #if !SANITIZER_GO
106 static const u32 kThreadQuarantineSize = 16;
107 #else
108 static const u32 kThreadQuarantineSize = 64;
109 #endif
110 
111 Context::Context()
112     : initialized(),
113       report_mtx(MutexTypeReport),
114       nreported(),
115       thread_registry(CreateThreadContext, kMaxTid, kThreadQuarantineSize,
116                       kMaxTidReuse),
117       racy_mtx(MutexTypeRacy),
118       racy_stacks(),
119       racy_addresses(),
120       fired_suppressions_mtx(MutexTypeFired),
121       clock_alloc(LINKER_INITIALIZED, "clock allocator") {
122   fired_suppressions.reserve(8);
123 }
124 
125 // The objects are allocated in TLS, so one may rely on zero-initialization.
126 ThreadState::ThreadState(Context *ctx, Tid tid, int unique_id, u64 epoch,
127                          unsigned reuse_count, uptr stk_addr, uptr stk_size,
128                          uptr tls_addr, uptr tls_size)
129     : fast_state(tid, epoch)
130       // Do not touch these, rely on zero initialization,
131       // they may be accessed before the ctor.
132       // , ignore_reads_and_writes()
133       // , ignore_interceptors()
134       ,
135       clock(tid, reuse_count)
136 #if !SANITIZER_GO
137       ,
138       jmp_bufs()
139 #endif
140       ,
141       tid(tid),
142       unique_id(unique_id),
143       stk_addr(stk_addr),
144       stk_size(stk_size),
145       tls_addr(tls_addr),
146       tls_size(tls_size)
147 #if !SANITIZER_GO
148       ,
149       last_sleep_clock(tid)
150 #endif
151 {
152   CHECK_EQ(reinterpret_cast<uptr>(this) % SANITIZER_CACHE_LINE_SIZE, 0);
153 #if !SANITIZER_GO
154   // C/C++ uses fixed size shadow stack.
155   const int kInitStackSize = kShadowStackSize;
156   shadow_stack = static_cast<uptr *>(
157       MmapNoReserveOrDie(kInitStackSize * sizeof(uptr), "shadow stack"));
158   SetShadowRegionHugePageMode(reinterpret_cast<uptr>(shadow_stack),
159                               kInitStackSize * sizeof(uptr));
160 #else
161   // Go uses malloc-allocated shadow stack with dynamic size.
162   const int kInitStackSize = 8;
163   shadow_stack = static_cast<uptr *>(Alloc(kInitStackSize * sizeof(uptr)));
164 #endif
165   shadow_stack_pos = shadow_stack;
166   shadow_stack_end = shadow_stack + kInitStackSize;
167 }
168 
169 #if !SANITIZER_GO
170 void MemoryProfiler(u64 uptime) {
171   if (ctx->memprof_fd == kInvalidFd)
172     return;
173   InternalMmapVector<char> buf(4096);
174   WriteMemoryProfile(buf.data(), buf.size(), uptime);
175   WriteToFile(ctx->memprof_fd, buf.data(), internal_strlen(buf.data()));
176 }
177 
178 void InitializeMemoryProfiler() {
179   ctx->memprof_fd = kInvalidFd;
180   const char *fname = flags()->profile_memory;
181   if (!fname || !fname[0])
182     return;
183   if (internal_strcmp(fname, "stdout") == 0) {
184     ctx->memprof_fd = 1;
185   } else if (internal_strcmp(fname, "stderr") == 0) {
186     ctx->memprof_fd = 2;
187   } else {
188     InternalScopedString filename;
189     filename.append("%s.%d", fname, (int)internal_getpid());
190     ctx->memprof_fd = OpenFile(filename.data(), WrOnly);
191     if (ctx->memprof_fd == kInvalidFd) {
192       Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
193              filename.data());
194       return;
195     }
196   }
197   MemoryProfiler(0);
198   MaybeSpawnBackgroundThread();
199 }
200 
201 static void *BackgroundThread(void *arg) {
202   // This is a non-initialized non-user thread, nothing to see here.
203   // We don't use ScopedIgnoreInterceptors, because we want ignores to be
204   // enabled even when the thread function exits (e.g. during pthread thread
205   // shutdown code).
206   cur_thread_init()->ignore_interceptors++;
207   const u64 kMs2Ns = 1000 * 1000;
208   const u64 start = NanoTime();
209 
210   u64 last_flush = NanoTime();
211   uptr last_rss = 0;
212   for (int i = 0;
213       atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
214       i++) {
215     SleepForMillis(100);
216     u64 now = NanoTime();
217 
218     // Flush memory if requested.
219     if (flags()->flush_memory_ms > 0) {
220       if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
221         VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
222         FlushShadowMemory();
223         last_flush = NanoTime();
224       }
225     }
226     if (flags()->memory_limit_mb > 0) {
227       uptr rss = GetRSS();
228       uptr limit = uptr(flags()->memory_limit_mb) << 20;
229       VPrintf(1, "ThreadSanitizer: memory flush check"
230                  " RSS=%llu LAST=%llu LIMIT=%llu\n",
231               (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
232       if (2 * rss > limit + last_rss) {
233         VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
234         FlushShadowMemory();
235         rss = GetRSS();
236         VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
237       }
238       last_rss = rss;
239     }
240 
241     MemoryProfiler(now - start);
242 
243     // Flush symbolizer cache if requested.
244     if (flags()->flush_symbolizer_ms > 0) {
245       u64 last = atomic_load(&ctx->last_symbolize_time_ns,
246                              memory_order_relaxed);
247       if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
248         Lock l(&ctx->report_mtx);
249         ScopedErrorReportLock l2;
250         SymbolizeFlush();
251         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
252       }
253     }
254   }
255   return nullptr;
256 }
257 
258 static void StartBackgroundThread() {
259   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
260 }
261 
262 #ifndef __mips__
263 static void StopBackgroundThread() {
264   atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
265   internal_join_thread(ctx->background_thread);
266   ctx->background_thread = 0;
267 }
268 #endif
269 #endif
270 
271 void DontNeedShadowFor(uptr addr, uptr size) {
272   ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)),
273                          reinterpret_cast<uptr>(MemToShadow(addr + size)));
274 }
275 
276 #if !SANITIZER_GO
277 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
278   if (size == 0) return;
279   DontNeedShadowFor(addr, size);
280   ScopedGlobalProcessor sgp;
281   ctx->metamap.ResetRange(thr->proc(), addr, size);
282 }
283 #endif
284 
285 void MapShadow(uptr addr, uptr size) {
286   // Global data is not 64K aligned, but there are no adjacent mappings,
287   // so we can get away with unaligned mapping.
288   // CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
289   const uptr kPageSize = GetPageSizeCached();
290   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
291   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
292   if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
293                                "shadow"))
294     Die();
295 
296   // Meta shadow is 2:1, so tread carefully.
297   static bool data_mapped = false;
298   static uptr mapped_meta_end = 0;
299   uptr meta_begin = (uptr)MemToMeta(addr);
300   uptr meta_end = (uptr)MemToMeta(addr + size);
301   meta_begin = RoundDownTo(meta_begin, 64 << 10);
302   meta_end = RoundUpTo(meta_end, 64 << 10);
303   if (!data_mapped) {
304     // First call maps data+bss.
305     data_mapped = true;
306     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
307                                  "meta shadow"))
308       Die();
309   } else {
310     // Mapping continuous heap.
311     // Windows wants 64K alignment.
312     meta_begin = RoundDownTo(meta_begin, 64 << 10);
313     meta_end = RoundUpTo(meta_end, 64 << 10);
314     if (meta_end <= mapped_meta_end)
315       return;
316     if (meta_begin < mapped_meta_end)
317       meta_begin = mapped_meta_end;
318     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
319                                  "meta shadow"))
320       Die();
321     mapped_meta_end = meta_end;
322   }
323   VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr,
324           addr + size, meta_begin, meta_end);
325 }
326 
327 void MapThreadTrace(uptr addr, uptr size, const char *name) {
328   DPrintf("#0: Mapping trace at 0x%zx-0x%zx(0x%zx)\n", addr, addr + size, size);
329   CHECK_GE(addr, TraceMemBeg());
330   CHECK_LE(addr + size, TraceMemEnd());
331   CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
332   if (!MmapFixedSuperNoReserve(addr, size, name)) {
333     Printf("FATAL: ThreadSanitizer can not mmap thread trace (0x%zx/0x%zx)\n",
334            addr, size);
335     Die();
336   }
337 }
338 
339 #if !SANITIZER_GO
340 static void OnStackUnwind(const SignalContext &sig, const void *,
341                           BufferedStackTrace *stack) {
342   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
343                 common_flags()->fast_unwind_on_fatal);
344 }
345 
346 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
347   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
348 }
349 #endif
350 
351 void CheckUnwind() {
352   // There is high probability that interceptors will check-fail as well,
353   // on the other hand there is no sense in processing interceptors
354   // since we are going to die soon.
355   ScopedIgnoreInterceptors ignore;
356 #if !SANITIZER_GO
357   cur_thread()->ignore_sync++;
358   cur_thread()->ignore_reads_and_writes++;
359 #endif
360   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
361 }
362 
363 bool is_initialized;
364 
365 void Initialize(ThreadState *thr) {
366   // Thread safe because done before all threads exist.
367   if (is_initialized)
368     return;
369   is_initialized = true;
370   // We are not ready to handle interceptors yet.
371   ScopedIgnoreInterceptors ignore;
372   SanitizerToolName = "ThreadSanitizer";
373   // Install tool-specific callbacks in sanitizer_common.
374   SetCheckUnwindCallback(CheckUnwind);
375 
376   ctx = new(ctx_placeholder) Context;
377   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
378   const char *options = GetEnv(env_name);
379   CacheBinaryName();
380   CheckASLR();
381   InitializeFlags(&ctx->flags, options, env_name);
382   AvoidCVE_2016_2143();
383   __sanitizer::InitializePlatformEarly();
384   __tsan::InitializePlatformEarly();
385 
386 #if !SANITIZER_GO
387   // Re-exec ourselves if we need to set additional env or command line args.
388   MaybeReexec();
389 
390   InitializeAllocator();
391   ReplaceSystemMalloc();
392 #endif
393   if (common_flags()->detect_deadlocks)
394     ctx->dd = DDetector::Create(flags());
395   Processor *proc = ProcCreate();
396   ProcWire(proc, thr);
397   InitializeInterceptors();
398   InitializePlatform();
399   InitializeDynamicAnnotations();
400 #if !SANITIZER_GO
401   InitializeShadowMemory();
402   InitializeAllocatorLate();
403   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
404 #endif
405   // Setup correct file descriptor for error reports.
406   __sanitizer_set_report_path(common_flags()->log_path);
407   InitializeSuppressions();
408 #if !SANITIZER_GO
409   InitializeLibIgnore();
410   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
411 #endif
412 
413   VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
414           (int)internal_getpid());
415 
416   // Initialize thread 0.
417   Tid tid = ThreadCreate(thr, 0, 0, true);
418   CHECK_EQ(tid, kMainTid);
419   ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
420 #if TSAN_CONTAINS_UBSAN
421   __ubsan::InitAsPlugin();
422 #endif
423   ctx->initialized = true;
424 
425 #if !SANITIZER_GO
426   Symbolizer::LateInitialize();
427   InitializeMemoryProfiler();
428 #endif
429 
430   if (flags()->stop_on_start) {
431     Printf("ThreadSanitizer is suspended at startup (pid %d)."
432            " Call __tsan_resume().\n",
433            (int)internal_getpid());
434     while (__tsan_resumed == 0) {}
435   }
436 
437   OnInitialize();
438 }
439 
440 void MaybeSpawnBackgroundThread() {
441   // On MIPS, TSan initialization is run before
442   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
443   // new threads.
444 #if !SANITIZER_GO && !defined(__mips__)
445   static atomic_uint32_t bg_thread = {};
446   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
447       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
448     StartBackgroundThread();
449     SetSandboxingCallback(StopBackgroundThread);
450   }
451 #endif
452 }
453 
454 
455 int Finalize(ThreadState *thr) {
456   bool failed = false;
457 
458   if (common_flags()->print_module_map == 1)
459     DumpProcessMap();
460 
461   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
462     SleepForMillis(flags()->atexit_sleep_ms);
463 
464   // Wait for pending reports.
465   ctx->report_mtx.Lock();
466   { ScopedErrorReportLock l; }
467   ctx->report_mtx.Unlock();
468 
469 #if !SANITIZER_GO
470   if (Verbosity()) AllocatorPrintStats();
471 #endif
472 
473   ThreadFinalize(thr);
474 
475   if (ctx->nreported) {
476     failed = true;
477 #if !SANITIZER_GO
478     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
479 #else
480     Printf("Found %d data race(s)\n", ctx->nreported);
481 #endif
482   }
483 
484   if (common_flags()->print_suppressions)
485     PrintMatchedSuppressions();
486 
487   failed = OnFinalize(failed);
488 
489   return failed ? common_flags()->exitcode : 0;
490 }
491 
492 #if !SANITIZER_GO
493 void ForkBefore(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
494   ctx->thread_registry.Lock();
495   ctx->report_mtx.Lock();
496   ScopedErrorReportLock::Lock();
497   AllocatorLock();
498   // Suppress all reports in the pthread_atfork callbacks.
499   // Reports will deadlock on the report_mtx.
500   // We could ignore sync operations as well,
501   // but so far it's unclear if it will do more good or harm.
502   // Unnecessarily ignoring things can lead to false positives later.
503   thr->suppress_reports++;
504   // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
505   // we'll assert in CheckNoLocks() unless we ignore interceptors.
506   // On OS X libSystem_atfork_prepare/parent/child callbacks are called
507   // after/before our callbacks and they call free.
508   thr->ignore_interceptors++;
509   // Disables memory write in OnUserAlloc/Free.
510   thr->ignore_reads_and_writes++;
511 
512   __tsan_test_only_on_fork();
513 }
514 
515 void ForkParentAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
516   thr->suppress_reports--;  // Enabled in ForkBefore.
517   thr->ignore_interceptors--;
518   thr->ignore_reads_and_writes--;
519   AllocatorUnlock();
520   ScopedErrorReportLock::Unlock();
521   ctx->report_mtx.Unlock();
522   ctx->thread_registry.Unlock();
523 }
524 
525 void ForkChildAfter(ThreadState *thr, uptr pc,
526                     bool start_thread) NO_THREAD_SAFETY_ANALYSIS {
527   thr->suppress_reports--;  // Enabled in ForkBefore.
528   thr->ignore_interceptors--;
529   thr->ignore_reads_and_writes--;
530   AllocatorUnlock();
531   ScopedErrorReportLock::Unlock();
532   ctx->report_mtx.Unlock();
533   ctx->thread_registry.Unlock();
534 
535   uptr nthread = 0;
536   ctx->thread_registry.GetNumberOfThreads(0, 0, &nthread /* alive threads */);
537   VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
538       " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
539   if (nthread == 1) {
540     if (start_thread)
541       StartBackgroundThread();
542   } else {
543     // We've just forked a multi-threaded process. We cannot reasonably function
544     // after that (some mutexes may be locked before fork). So just enable
545     // ignores for everything in the hope that we will exec soon.
546     ctx->after_multithreaded_fork = true;
547     thr->ignore_interceptors++;
548     ThreadIgnoreBegin(thr, pc);
549     ThreadIgnoreSyncBegin(thr, pc);
550   }
551 }
552 #endif
553 
554 #if SANITIZER_GO
555 NOINLINE
556 void GrowShadowStack(ThreadState *thr) {
557   const int sz = thr->shadow_stack_end - thr->shadow_stack;
558   const int newsz = 2 * sz;
559   auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr));
560   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
561   Free(thr->shadow_stack);
562   thr->shadow_stack = newstack;
563   thr->shadow_stack_pos = newstack + sz;
564   thr->shadow_stack_end = newstack + newsz;
565 }
566 #endif
567 
568 StackID CurrentStackId(ThreadState *thr, uptr pc) {
569   if (!thr->is_inited)  // May happen during bootstrap.
570     return kInvalidStackID;
571   if (pc != 0) {
572 #if !SANITIZER_GO
573     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
574 #else
575     if (thr->shadow_stack_pos == thr->shadow_stack_end)
576       GrowShadowStack(thr);
577 #endif
578     thr->shadow_stack_pos[0] = pc;
579     thr->shadow_stack_pos++;
580   }
581   StackID id = StackDepotPut(
582       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
583   if (pc != 0)
584     thr->shadow_stack_pos--;
585   return id;
586 }
587 
588 namespace v3 {
589 
590 NOINLINE
591 void TraceSwitchPart(ThreadState *thr) {
592   Trace *trace = &thr->tctx->trace;
593   Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
594   DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0);
595   auto *part = trace->parts.Back();
596   DPrintf("TraceSwitchPart part=%p pos=%p\n", part, pos);
597   if (part) {
598     // We can get here when we still have space in the current trace part.
599     // The fast-path check in TraceAcquire has false positives in the middle of
600     // the part. Check if we are indeed at the end of the current part or not,
601     // and fill any gaps with NopEvent's.
602     Event *end = &part->events[TracePart::kSize];
603     DCHECK_GE(pos, &part->events[0]);
604     DCHECK_LE(pos, end);
605     if (pos + 1 < end) {
606       if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) ==
607           TracePart::kAlignment)
608         *pos++ = NopEvent;
609       *pos++ = NopEvent;
610       DCHECK_LE(pos + 2, end);
611       atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos));
612       // Ensure we setup trace so that the next TraceAcquire
613       // won't detect trace part end.
614       Event *ev;
615       CHECK(TraceAcquire(thr, &ev));
616       return;
617     }
618     // We are indeed at the end.
619     for (; pos < end; pos++) *pos = NopEvent;
620   }
621 #if !SANITIZER_GO
622   if (ctx->after_multithreaded_fork) {
623     // We just need to survive till exec.
624     CHECK(part);
625     atomic_store_relaxed(&thr->trace_pos,
626                          reinterpret_cast<uptr>(&part->events[0]));
627     return;
628   }
629 #endif
630   part = new (MmapOrDie(sizeof(TracePart), "TracePart")) TracePart();
631   part->trace = trace;
632   thr->trace_prev_pc = 0;
633   {
634     Lock lock(&trace->mtx);
635     trace->parts.PushBack(part);
636     atomic_store_relaxed(&thr->trace_pos,
637                          reinterpret_cast<uptr>(&part->events[0]));
638   }
639   // Make this part self-sufficient by restoring the current stack
640   // and mutex set in the beginning of the trace.
641   TraceTime(thr);
642   for (uptr *pos = &thr->shadow_stack[0]; pos < thr->shadow_stack_pos; pos++)
643     CHECK(TryTraceFunc(thr, *pos));
644   for (uptr i = 0; i < thr->mset.Size(); i++) {
645     MutexSet::Desc d = thr->mset.Get(i);
646     TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0,
647                    d.addr, d.stack_id);
648   }
649 }
650 
651 }  // namespace v3
652 
653 void TraceSwitch(ThreadState *thr) {
654 #if !SANITIZER_GO
655   if (ctx->after_multithreaded_fork)
656     return;
657 #endif
658   thr->nomalloc++;
659   Trace *thr_trace = ThreadTrace(thr->tid);
660   Lock l(&thr_trace->mtx);
661   unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
662   TraceHeader *hdr = &thr_trace->headers[trace];
663   hdr->epoch0 = thr->fast_state.epoch();
664   ObtainCurrentStack(thr, 0, &hdr->stack0);
665   hdr->mset0 = thr->mset;
666   thr->nomalloc--;
667 }
668 
669 Trace *ThreadTrace(Tid tid) { return (Trace *)GetThreadTraceHeader(tid); }
670 
671 uptr TraceTopPC(ThreadState *thr) {
672   Event *events = (Event*)GetThreadTrace(thr->tid);
673   uptr pc = events[thr->fast_state.GetTracePos()];
674   return pc;
675 }
676 
677 uptr TraceSize() {
678   return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
679 }
680 
681 uptr TraceParts() {
682   return TraceSize() / kTracePartSize;
683 }
684 
685 #if !SANITIZER_GO
686 extern "C" void __tsan_trace_switch() {
687   TraceSwitch(cur_thread());
688 }
689 
690 extern "C" void __tsan_report_race() {
691   ReportRace(cur_thread());
692 }
693 #endif
694 
695 void ThreadIgnoreBegin(ThreadState *thr, uptr pc) {
696   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
697   thr->ignore_reads_and_writes++;
698   CHECK_GT(thr->ignore_reads_and_writes, 0);
699   thr->fast_state.SetIgnoreBit();
700 #if !SANITIZER_GO
701   if (pc && !ctx->after_multithreaded_fork)
702     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
703 #endif
704 }
705 
706 void ThreadIgnoreEnd(ThreadState *thr) {
707   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
708   CHECK_GT(thr->ignore_reads_and_writes, 0);
709   thr->ignore_reads_and_writes--;
710   if (thr->ignore_reads_and_writes == 0) {
711     thr->fast_state.ClearIgnoreBit();
712 #if !SANITIZER_GO
713     thr->mop_ignore_set.Reset();
714 #endif
715   }
716 }
717 
718 #if !SANITIZER_GO
719 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
720 uptr __tsan_testonly_shadow_stack_current_size() {
721   ThreadState *thr = cur_thread();
722   return thr->shadow_stack_pos - thr->shadow_stack;
723 }
724 #endif
725 
726 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
727   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
728   thr->ignore_sync++;
729   CHECK_GT(thr->ignore_sync, 0);
730 #if !SANITIZER_GO
731   if (pc && !ctx->after_multithreaded_fork)
732     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
733 #endif
734 }
735 
736 void ThreadIgnoreSyncEnd(ThreadState *thr) {
737   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
738   CHECK_GT(thr->ignore_sync, 0);
739   thr->ignore_sync--;
740 #if !SANITIZER_GO
741   if (thr->ignore_sync == 0)
742     thr->sync_ignore_set.Reset();
743 #endif
744 }
745 
746 bool MD5Hash::operator==(const MD5Hash &other) const {
747   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
748 }
749 
750 #if SANITIZER_DEBUG
751 void build_consistency_debug() {}
752 #else
753 void build_consistency_release() {}
754 #endif
755 
756 }  // namespace __tsan
757 
758 #if SANITIZER_CHECK_DEADLOCKS
759 namespace __sanitizer {
760 using namespace __tsan;
761 MutexMeta mutex_meta[] = {
762     {MutexInvalid, "Invalid", {}},
763     {MutexThreadRegistry, "ThreadRegistry", {}},
764     {MutexTypeTrace, "Trace", {}},
765     {MutexTypeReport,
766      "Report",
767      {MutexTypeSyncVar, MutexTypeGlobalProc, MutexTypeTrace}},
768     {MutexTypeSyncVar, "SyncVar", {MutexTypeTrace}},
769     {MutexTypeAnnotations, "Annotations", {}},
770     {MutexTypeAtExit, "AtExit", {MutexTypeSyncVar}},
771     {MutexTypeFired, "Fired", {MutexLeaf}},
772     {MutexTypeRacy, "Racy", {MutexLeaf}},
773     {MutexTypeGlobalProc, "GlobalProc", {}},
774     {MutexTypeInternalAlloc, "InternalAlloc", {MutexLeaf}},
775     {},
776 };
777 
778 void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
779 }  // namespace __sanitizer
780 #endif
781