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_interface_internal.h"
20 #include "sanitizer_common/sanitizer_libc.h"
21 #include "sanitizer_common/sanitizer_placement_new.h"
22 #include "sanitizer_common/sanitizer_stackdepot.h"
23 #include "sanitizer_common/sanitizer_symbolizer.h"
24 #include "tsan_defs.h"
25 #include "tsan_interface.h"
26 #include "tsan_mman.h"
27 #include "tsan_platform.h"
28 #include "tsan_suppressions.h"
29 #include "tsan_symbolize.h"
30 #include "ubsan/ubsan_init.h"
31 
32 volatile int __tsan_resumed = 0;
33 
34 extern "C" void __tsan_resume() {
35   __tsan_resumed = 1;
36 }
37 
38 SANITIZER_WEAK_DEFAULT_IMPL
39 void __tsan_test_only_on_fork() {}
40 
41 namespace __tsan {
42 
43 #if !SANITIZER_GO
44 void (*on_initialize)(void);
45 int (*on_finalize)(int);
46 #endif
47 
48 #if !SANITIZER_GO && !SANITIZER_MAC
49 __attribute__((tls_model("initial-exec")))
50 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(
51     SANITIZER_CACHE_LINE_SIZE);
52 #endif
53 static char ctx_placeholder[sizeof(Context)] ALIGNED(SANITIZER_CACHE_LINE_SIZE);
54 Context *ctx;
55 
56 // Can be overriden by a front-end.
57 #ifdef TSAN_EXTERNAL_HOOKS
58 bool OnFinalize(bool failed);
59 void OnInitialize();
60 #else
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 
70 SANITIZER_WEAK_CXX_DEFAULT_IMPL
71 void OnInitialize() {
72 #  if !SANITIZER_GO
73   if (on_initialize)
74     on_initialize();
75 #  endif
76 }
77 #endif
78 
79 static TracePart* TracePartAlloc(ThreadState* thr) {
80   TracePart* part = nullptr;
81   {
82     Lock lock(&ctx->slot_mtx);
83     uptr max_parts = Trace::kMinParts + flags()->history_size;
84     Trace* trace = &thr->tctx->trace;
85     if (trace->parts_allocated == max_parts ||
86         ctx->trace_part_finished_excess) {
87       part = ctx->trace_part_recycle.PopFront();
88       DPrintf("#%d: TracePartAlloc: part=%p\n", thr->tid, part);
89       if (part && part->trace) {
90         Trace* trace1 = part->trace;
91         Lock trace_lock(&trace1->mtx);
92         part->trace = nullptr;
93         TracePart* part1 = trace1->parts.PopFront();
94         CHECK_EQ(part, part1);
95         if (trace1->parts_allocated > trace1->parts.Size()) {
96           ctx->trace_part_finished_excess +=
97               trace1->parts_allocated - trace1->parts.Size();
98           trace1->parts_allocated = trace1->parts.Size();
99         }
100       }
101     }
102     if (trace->parts_allocated < max_parts) {
103       trace->parts_allocated++;
104       if (ctx->trace_part_finished_excess)
105         ctx->trace_part_finished_excess--;
106     }
107     if (!part)
108       ctx->trace_part_total_allocated++;
109     else if (ctx->trace_part_recycle_finished)
110       ctx->trace_part_recycle_finished--;
111   }
112   if (!part)
113     part = new (MmapOrDie(sizeof(*part), "TracePart")) TracePart();
114   return part;
115 }
116 
117 static void TracePartFree(TracePart* part) SANITIZER_REQUIRES(ctx->slot_mtx) {
118   DCHECK(part->trace);
119   part->trace = nullptr;
120   ctx->trace_part_recycle.PushFront(part);
121 }
122 
123 void TraceResetForTesting() {
124   Lock lock(&ctx->slot_mtx);
125   while (auto* part = ctx->trace_part_recycle.PopFront()) {
126     if (auto trace = part->trace)
127       CHECK_EQ(trace->parts.PopFront(), part);
128     UnmapOrDie(part, sizeof(*part));
129   }
130   ctx->trace_part_total_allocated = 0;
131   ctx->trace_part_recycle_finished = 0;
132   ctx->trace_part_finished_excess = 0;
133 }
134 
135 static void DoResetImpl(uptr epoch) {
136   ThreadRegistryLock lock0(&ctx->thread_registry);
137   Lock lock1(&ctx->slot_mtx);
138   CHECK_EQ(ctx->global_epoch, epoch);
139   ctx->global_epoch++;
140   CHECK(!ctx->resetting);
141   ctx->resetting = true;
142   for (u32 i = ctx->thread_registry.NumThreadsLocked(); i--;) {
143     ThreadContext* tctx = (ThreadContext*)ctx->thread_registry.GetThreadLocked(
144         static_cast<Tid>(i));
145     // Potentially we could purge all ThreadStatusDead threads from the
146     // registry. Since we reset all shadow, they can't race with anything
147     // anymore. However, their tid's can still be stored in some aux places
148     // (e.g. tid of thread that created something).
149     auto trace = &tctx->trace;
150     Lock lock(&trace->mtx);
151     bool attached = tctx->thr && tctx->thr->slot;
152     auto parts = &trace->parts;
153     bool local = false;
154     while (!parts->Empty()) {
155       auto part = parts->Front();
156       local = local || part == trace->local_head;
157       if (local)
158         CHECK(!ctx->trace_part_recycle.Queued(part));
159       else
160         ctx->trace_part_recycle.Remove(part);
161       if (attached && parts->Size() == 1) {
162         // The thread is running and this is the last/current part.
163         // Set the trace position to the end of the current part
164         // to force the thread to call SwitchTracePart and re-attach
165         // to a new slot and allocate a new trace part.
166         // Note: the thread is concurrently modifying the position as well,
167         // so this is only best-effort. The thread can only modify position
168         // within this part, because switching parts is protected by
169         // slot/trace mutexes that we hold here.
170         atomic_store_relaxed(
171             &tctx->thr->trace_pos,
172             reinterpret_cast<uptr>(&part->events[TracePart::kSize]));
173         break;
174       }
175       parts->Remove(part);
176       TracePartFree(part);
177     }
178     CHECK_LE(parts->Size(), 1);
179     trace->local_head = parts->Front();
180     if (tctx->thr && !tctx->thr->slot) {
181       atomic_store_relaxed(&tctx->thr->trace_pos, 0);
182       tctx->thr->trace_prev_pc = 0;
183     }
184     if (trace->parts_allocated > trace->parts.Size()) {
185       ctx->trace_part_finished_excess +=
186           trace->parts_allocated - trace->parts.Size();
187       trace->parts_allocated = trace->parts.Size();
188     }
189   }
190   while (ctx->slot_queue.PopFront()) {
191   }
192   for (auto& slot : ctx->slots) {
193     slot.SetEpoch(kEpochZero);
194     slot.journal.Reset();
195     slot.thr = nullptr;
196     ctx->slot_queue.PushBack(&slot);
197   }
198 
199   DPrintf("Resetting shadow...\n");
200   if (!MmapFixedSuperNoReserve(ShadowBeg(), ShadowEnd() - ShadowBeg(),
201                                "shadow")) {
202     Printf("failed to reset shadow memory\n");
203     Die();
204   }
205   DPrintf("Resetting meta shadow...\n");
206   ctx->metamap.ResetClocks();
207   ctx->resetting = false;
208 }
209 
210 // Clang does not understand locking all slots in the loop:
211 // error: expecting mutex 'slot.mtx' to be held at start of each loop
212 void DoReset(ThreadState* thr, uptr epoch) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
213   {
214     for (auto& slot : ctx->slots) {
215       slot.mtx.Lock();
216       if (UNLIKELY(epoch == 0))
217         epoch = ctx->global_epoch;
218       if (UNLIKELY(epoch != ctx->global_epoch)) {
219         // Epoch can't change once we've locked the first slot.
220         CHECK_EQ(slot.sid, 0);
221         slot.mtx.Unlock();
222         return;
223       }
224     }
225   }
226   DPrintf("#%d: DoReset epoch=%lu\n", thr ? thr->tid : -1, epoch);
227   DoResetImpl(epoch);
228   for (auto& slot : ctx->slots) slot.mtx.Unlock();
229 }
230 
231 void FlushShadowMemory() { DoReset(nullptr, 0); }
232 
233 static TidSlot* FindSlotAndLock(ThreadState* thr)
234     SANITIZER_ACQUIRE(thr->slot->mtx) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
235   CHECK(!thr->slot);
236   TidSlot* slot = nullptr;
237   for (;;) {
238     uptr epoch;
239     {
240       Lock lock(&ctx->slot_mtx);
241       epoch = ctx->global_epoch;
242       if (slot) {
243         // This is an exhausted slot from the previous iteration.
244         if (ctx->slot_queue.Queued(slot))
245           ctx->slot_queue.Remove(slot);
246         thr->slot_locked = false;
247         slot->mtx.Unlock();
248       }
249       for (;;) {
250         slot = ctx->slot_queue.PopFront();
251         if (!slot)
252           break;
253         if (slot->epoch() != kEpochLast) {
254           ctx->slot_queue.PushBack(slot);
255           break;
256         }
257       }
258     }
259     if (!slot) {
260       DoReset(thr, epoch);
261       continue;
262     }
263     slot->mtx.Lock();
264     CHECK(!thr->slot_locked);
265     thr->slot_locked = true;
266     if (slot->thr) {
267       DPrintf("#%d: preempting sid=%d tid=%d\n", thr->tid, (u32)slot->sid,
268               slot->thr->tid);
269       slot->SetEpoch(slot->thr->fast_state.epoch());
270       slot->thr = nullptr;
271     }
272     if (slot->epoch() != kEpochLast)
273       return slot;
274   }
275 }
276 
277 void SlotAttachAndLock(ThreadState* thr) {
278   TidSlot* slot = FindSlotAndLock(thr);
279   DPrintf("#%d: SlotAttach: slot=%u\n", thr->tid, static_cast<int>(slot->sid));
280   CHECK(!slot->thr);
281   CHECK(!thr->slot);
282   slot->thr = thr;
283   thr->slot = slot;
284   Epoch epoch = EpochInc(slot->epoch());
285   CHECK(!EpochOverflow(epoch));
286   slot->SetEpoch(epoch);
287   thr->fast_state.SetSid(slot->sid);
288   thr->fast_state.SetEpoch(epoch);
289   if (thr->slot_epoch != ctx->global_epoch) {
290     thr->slot_epoch = ctx->global_epoch;
291     thr->clock.Reset();
292 #if !SANITIZER_GO
293     thr->last_sleep_stack_id = kInvalidStackID;
294     thr->last_sleep_clock.Reset();
295 #endif
296   }
297   thr->clock.Set(slot->sid, epoch);
298   slot->journal.PushBack({thr->tid, epoch});
299 }
300 
301 static void SlotDetachImpl(ThreadState* thr, bool exiting) {
302   TidSlot* slot = thr->slot;
303   thr->slot = nullptr;
304   if (thr != slot->thr) {
305     slot = nullptr;  // we don't own the slot anymore
306     if (thr->slot_epoch != ctx->global_epoch) {
307       TracePart* part = nullptr;
308       auto* trace = &thr->tctx->trace;
309       {
310         Lock l(&trace->mtx);
311         auto* parts = &trace->parts;
312         // The trace can be completely empty in an unlikely event
313         // the thread is preempted right after it acquired the slot
314         // in ThreadStart and did not trace any events yet.
315         CHECK_LE(parts->Size(), 1);
316         part = parts->PopFront();
317         thr->tctx->trace.local_head = nullptr;
318         atomic_store_relaxed(&thr->trace_pos, 0);
319         thr->trace_prev_pc = 0;
320       }
321       if (part) {
322         Lock l(&ctx->slot_mtx);
323         TracePartFree(part);
324       }
325     }
326     return;
327   }
328   CHECK(exiting || thr->fast_state.epoch() == kEpochLast);
329   slot->SetEpoch(thr->fast_state.epoch());
330   slot->thr = nullptr;
331 }
332 
333 void SlotDetach(ThreadState* thr) {
334   Lock lock(&thr->slot->mtx);
335   SlotDetachImpl(thr, true);
336 }
337 
338 void SlotLock(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
339   DCHECK(!thr->slot_locked);
340 #if SANITIZER_DEBUG
341   // Check these mutexes are not locked.
342   // We can call DoReset from SlotAttachAndLock, which will lock
343   // these mutexes, but it happens only every once in a while.
344   { ThreadRegistryLock lock(&ctx->thread_registry); }
345   { Lock lock(&ctx->slot_mtx); }
346 #endif
347   TidSlot* slot = thr->slot;
348   slot->mtx.Lock();
349   thr->slot_locked = true;
350   if (LIKELY(thr == slot->thr && thr->fast_state.epoch() != kEpochLast))
351     return;
352   SlotDetachImpl(thr, false);
353   thr->slot_locked = false;
354   slot->mtx.Unlock();
355   SlotAttachAndLock(thr);
356 }
357 
358 void SlotUnlock(ThreadState* thr) {
359   DCHECK(thr->slot_locked);
360   thr->slot_locked = false;
361   thr->slot->mtx.Unlock();
362 }
363 
364 Context::Context()
365     : initialized(),
366       report_mtx(MutexTypeReport),
367       nreported(),
368       thread_registry([](Tid tid) -> ThreadContextBase* {
369         return new (Alloc(sizeof(ThreadContext))) ThreadContext(tid);
370       }),
371       racy_mtx(MutexTypeRacy),
372       racy_stacks(),
373       racy_addresses(),
374       fired_suppressions_mtx(MutexTypeFired),
375       slot_mtx(MutexTypeSlots),
376       resetting() {
377   fired_suppressions.reserve(8);
378   for (uptr i = 0; i < ARRAY_SIZE(slots); i++) {
379     TidSlot* slot = &slots[i];
380     slot->sid = static_cast<Sid>(i);
381     slot_queue.PushBack(slot);
382   }
383   global_epoch = 1;
384 }
385 
386 TidSlot::TidSlot() : mtx(MutexTypeSlot) {}
387 
388 // The objects are allocated in TLS, so one may rely on zero-initialization.
389 ThreadState::ThreadState(Tid tid)
390     // Do not touch these, rely on zero initialization,
391     // they may be accessed before the ctor.
392     // ignore_reads_and_writes()
393     // ignore_interceptors()
394     : tid(tid) {
395   CHECK_EQ(reinterpret_cast<uptr>(this) % SANITIZER_CACHE_LINE_SIZE, 0);
396 #if !SANITIZER_GO
397   // C/C++ uses fixed size shadow stack.
398   const int kInitStackSize = kShadowStackSize;
399   shadow_stack = static_cast<uptr*>(
400       MmapNoReserveOrDie(kInitStackSize * sizeof(uptr), "shadow stack"));
401   SetShadowRegionHugePageMode(reinterpret_cast<uptr>(shadow_stack),
402                               kInitStackSize * sizeof(uptr));
403 #else
404   // Go uses malloc-allocated shadow stack with dynamic size.
405   const int kInitStackSize = 8;
406   shadow_stack = static_cast<uptr*>(Alloc(kInitStackSize * sizeof(uptr)));
407 #endif
408   shadow_stack_pos = shadow_stack;
409   shadow_stack_end = shadow_stack + kInitStackSize;
410 }
411 
412 #if !SANITIZER_GO
413 void MemoryProfiler(u64 uptime) {
414   if (ctx->memprof_fd == kInvalidFd)
415     return;
416   InternalMmapVector<char> buf(4096);
417   WriteMemoryProfile(buf.data(), buf.size(), uptime);
418   WriteToFile(ctx->memprof_fd, buf.data(), internal_strlen(buf.data()));
419 }
420 
421 static bool InitializeMemoryProfiler() {
422   ctx->memprof_fd = kInvalidFd;
423   const char *fname = flags()->profile_memory;
424   if (!fname || !fname[0])
425     return false;
426   if (internal_strcmp(fname, "stdout") == 0) {
427     ctx->memprof_fd = 1;
428   } else if (internal_strcmp(fname, "stderr") == 0) {
429     ctx->memprof_fd = 2;
430   } else {
431     InternalScopedString filename;
432     filename.append("%s.%d", fname, (int)internal_getpid());
433     ctx->memprof_fd = OpenFile(filename.data(), WrOnly);
434     if (ctx->memprof_fd == kInvalidFd) {
435       Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
436              filename.data());
437       return false;
438     }
439   }
440   MemoryProfiler(0);
441   return true;
442 }
443 
444 static void *BackgroundThread(void *arg) {
445   // This is a non-initialized non-user thread, nothing to see here.
446   // We don't use ScopedIgnoreInterceptors, because we want ignores to be
447   // enabled even when the thread function exits (e.g. during pthread thread
448   // shutdown code).
449   cur_thread_init()->ignore_interceptors++;
450   const u64 kMs2Ns = 1000 * 1000;
451   const u64 start = NanoTime();
452 
453   u64 last_flush = start;
454   uptr last_rss = 0;
455   while (!atomic_load_relaxed(&ctx->stop_background_thread)) {
456     SleepForMillis(100);
457     u64 now = NanoTime();
458 
459     // Flush memory if requested.
460     if (flags()->flush_memory_ms > 0) {
461       if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
462         VReport(1, "ThreadSanitizer: periodic memory flush\n");
463         FlushShadowMemory();
464         now = last_flush = NanoTime();
465       }
466     }
467     if (flags()->memory_limit_mb > 0) {
468       uptr rss = GetRSS();
469       uptr limit = uptr(flags()->memory_limit_mb) << 20;
470       VReport(1,
471               "ThreadSanitizer: memory flush check"
472               " RSS=%llu LAST=%llu LIMIT=%llu\n",
473               (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
474       if (2 * rss > limit + last_rss) {
475         VReport(1, "ThreadSanitizer: flushing memory due to RSS\n");
476         FlushShadowMemory();
477         rss = GetRSS();
478         now = NanoTime();
479         VReport(1, "ThreadSanitizer: memory flushed RSS=%llu\n",
480                 (u64)rss >> 20);
481       }
482       last_rss = rss;
483     }
484 
485     MemoryProfiler(now - start);
486 
487     // Flush symbolizer cache if requested.
488     if (flags()->flush_symbolizer_ms > 0) {
489       u64 last = atomic_load(&ctx->last_symbolize_time_ns,
490                              memory_order_relaxed);
491       if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
492         Lock l(&ctx->report_mtx);
493         ScopedErrorReportLock l2;
494         SymbolizeFlush();
495         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
496       }
497     }
498   }
499   return nullptr;
500 }
501 
502 static void StartBackgroundThread() {
503   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
504 }
505 
506 #ifndef __mips__
507 static void StopBackgroundThread() {
508   atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
509   internal_join_thread(ctx->background_thread);
510   ctx->background_thread = 0;
511 }
512 #endif
513 #endif
514 
515 void DontNeedShadowFor(uptr addr, uptr size) {
516   ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)),
517                          reinterpret_cast<uptr>(MemToShadow(addr + size)));
518 }
519 
520 #if !SANITIZER_GO
521 // We call UnmapShadow before the actual munmap, at that point we don't yet
522 // know if the provided address/size are sane. We can't call UnmapShadow
523 // after the actual munmap becuase at that point the memory range can
524 // already be reused for something else, so we can't rely on the munmap
525 // return value to understand is the values are sane.
526 // While calling munmap with insane values (non-canonical address, negative
527 // size, etc) is an error, the kernel won't crash. We must also try to not
528 // crash as the failure mode is very confusing (paging fault inside of the
529 // runtime on some derived shadow address).
530 static bool IsValidMmapRange(uptr addr, uptr size) {
531   if (size == 0)
532     return true;
533   if (static_cast<sptr>(size) < 0)
534     return false;
535   if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
536     return false;
537   // Check that if the start of the region belongs to one of app ranges,
538   // end of the region belongs to the same region.
539   const uptr ranges[][2] = {
540       {LoAppMemBeg(), LoAppMemEnd()},
541       {MidAppMemBeg(), MidAppMemEnd()},
542       {HiAppMemBeg(), HiAppMemEnd()},
543   };
544   for (auto range : ranges) {
545     if (addr >= range[0] && addr < range[1])
546       return addr + size <= range[1];
547   }
548   return false;
549 }
550 
551 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
552   if (size == 0 || !IsValidMmapRange(addr, size))
553     return;
554   DontNeedShadowFor(addr, size);
555   ScopedGlobalProcessor sgp;
556   SlotLocker locker(thr, true);
557   ctx->metamap.ResetRange(thr->proc(), addr, size, true);
558 }
559 #endif
560 
561 void MapShadow(uptr addr, uptr size) {
562   // Global data is not 64K aligned, but there are no adjacent mappings,
563   // so we can get away with unaligned mapping.
564   // CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
565   const uptr kPageSize = GetPageSizeCached();
566   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
567   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
568   if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
569                                "shadow"))
570     Die();
571 
572   // Meta shadow is 2:1, so tread carefully.
573   static bool data_mapped = false;
574   static uptr mapped_meta_end = 0;
575   uptr meta_begin = (uptr)MemToMeta(addr);
576   uptr meta_end = (uptr)MemToMeta(addr + size);
577   meta_begin = RoundDownTo(meta_begin, 64 << 10);
578   meta_end = RoundUpTo(meta_end, 64 << 10);
579   if (!data_mapped) {
580     // First call maps data+bss.
581     data_mapped = true;
582     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
583                                  "meta shadow"))
584       Die();
585   } else {
586     // Mapping continuous heap.
587     // Windows wants 64K alignment.
588     meta_begin = RoundDownTo(meta_begin, 64 << 10);
589     meta_end = RoundUpTo(meta_end, 64 << 10);
590     if (meta_end <= mapped_meta_end)
591       return;
592     if (meta_begin < mapped_meta_end)
593       meta_begin = mapped_meta_end;
594     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
595                                  "meta shadow"))
596       Die();
597     mapped_meta_end = meta_end;
598   }
599   VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr,
600           addr + size, meta_begin, meta_end);
601 }
602 
603 #if !SANITIZER_GO
604 static void OnStackUnwind(const SignalContext &sig, const void *,
605                           BufferedStackTrace *stack) {
606   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
607                 common_flags()->fast_unwind_on_fatal);
608 }
609 
610 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
611   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
612 }
613 #endif
614 
615 void CheckUnwind() {
616   // There is high probability that interceptors will check-fail as well,
617   // on the other hand there is no sense in processing interceptors
618   // since we are going to die soon.
619   ScopedIgnoreInterceptors ignore;
620 #if !SANITIZER_GO
621   ThreadState* thr = cur_thread();
622   thr->nomalloc = false;
623   thr->ignore_sync++;
624   thr->ignore_reads_and_writes++;
625   atomic_store_relaxed(&thr->in_signal_handler, 0);
626 #endif
627   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
628 }
629 
630 bool is_initialized;
631 
632 void Initialize(ThreadState *thr) {
633   // Thread safe because done before all threads exist.
634   if (is_initialized)
635     return;
636   is_initialized = true;
637   // We are not ready to handle interceptors yet.
638   ScopedIgnoreInterceptors ignore;
639   SanitizerToolName = "ThreadSanitizer";
640   // Install tool-specific callbacks in sanitizer_common.
641   SetCheckUnwindCallback(CheckUnwind);
642 
643   ctx = new(ctx_placeholder) Context;
644   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
645   const char *options = GetEnv(env_name);
646   CacheBinaryName();
647   CheckASLR();
648   InitializeFlags(&ctx->flags, options, env_name);
649   AvoidCVE_2016_2143();
650   __sanitizer::InitializePlatformEarly();
651   __tsan::InitializePlatformEarly();
652 
653 #if !SANITIZER_GO
654   // Re-exec ourselves if we need to set additional env or command line args.
655   MaybeReexec();
656 
657   InitializeAllocator();
658   ReplaceSystemMalloc();
659 #endif
660   if (common_flags()->detect_deadlocks)
661     ctx->dd = DDetector::Create(flags());
662   Processor *proc = ProcCreate();
663   ProcWire(proc, thr);
664   InitializeInterceptors();
665   InitializePlatform();
666   InitializeDynamicAnnotations();
667 #if !SANITIZER_GO
668   InitializeShadowMemory();
669   InitializeAllocatorLate();
670   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
671 #endif
672   // Setup correct file descriptor for error reports.
673   __sanitizer_set_report_path(common_flags()->log_path);
674   InitializeSuppressions();
675 #if !SANITIZER_GO
676   InitializeLibIgnore();
677   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
678 #endif
679 
680   VPrintf(1, "***** Running under ThreadSanitizer v3 (pid %d) *****\n",
681           (int)internal_getpid());
682 
683   // Initialize thread 0.
684   Tid tid = ThreadCreate(nullptr, 0, 0, true);
685   CHECK_EQ(tid, kMainTid);
686   ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
687 #if TSAN_CONTAINS_UBSAN
688   __ubsan::InitAsPlugin();
689 #endif
690 
691 #if !SANITIZER_GO
692   Symbolizer::LateInitialize();
693   if (InitializeMemoryProfiler() || flags()->force_background_thread)
694     MaybeSpawnBackgroundThread();
695 #endif
696   ctx->initialized = true;
697 
698   if (flags()->stop_on_start) {
699     Printf("ThreadSanitizer is suspended at startup (pid %d)."
700            " Call __tsan_resume().\n",
701            (int)internal_getpid());
702     while (__tsan_resumed == 0) {}
703   }
704 
705   OnInitialize();
706 }
707 
708 void MaybeSpawnBackgroundThread() {
709   // On MIPS, TSan initialization is run before
710   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
711   // new threads.
712 #if !SANITIZER_GO && !defined(__mips__)
713   static atomic_uint32_t bg_thread = {};
714   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
715       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
716     StartBackgroundThread();
717     SetSandboxingCallback(StopBackgroundThread);
718   }
719 #endif
720 }
721 
722 int Finalize(ThreadState *thr) {
723   bool failed = false;
724 
725   if (common_flags()->print_module_map == 1)
726     DumpProcessMap();
727 
728   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
729     internal_usleep(u64(flags()->atexit_sleep_ms) * 1000);
730 
731   {
732     // Wait for pending reports.
733     ScopedErrorReportLock lock;
734   }
735 
736 #if !SANITIZER_GO
737   if (Verbosity()) AllocatorPrintStats();
738 #endif
739 
740   ThreadFinalize(thr);
741 
742   if (ctx->nreported) {
743     failed = true;
744 #if !SANITIZER_GO
745     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
746 #else
747     Printf("Found %d data race(s)\n", ctx->nreported);
748 #endif
749   }
750 
751   if (common_flags()->print_suppressions)
752     PrintMatchedSuppressions();
753 
754   failed = OnFinalize(failed);
755 
756   return failed ? common_flags()->exitcode : 0;
757 }
758 
759 #if !SANITIZER_GO
760 void ForkBefore(ThreadState* thr, uptr pc) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
761   GlobalProcessorLock();
762   // Detaching from the slot makes OnUserFree skip writing to the shadow.
763   // The slot will be locked so any attempts to use it will deadlock anyway.
764   SlotDetach(thr);
765   for (auto& slot : ctx->slots) slot.mtx.Lock();
766   ctx->thread_registry.Lock();
767   ctx->slot_mtx.Lock();
768   ScopedErrorReportLock::Lock();
769   AllocatorLock();
770   // Suppress all reports in the pthread_atfork callbacks.
771   // Reports will deadlock on the report_mtx.
772   // We could ignore sync operations as well,
773   // but so far it's unclear if it will do more good or harm.
774   // Unnecessarily ignoring things can lead to false positives later.
775   thr->suppress_reports++;
776   // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
777   // we'll assert in CheckNoLocks() unless we ignore interceptors.
778   // On OS X libSystem_atfork_prepare/parent/child callbacks are called
779   // after/before our callbacks and they call free.
780   thr->ignore_interceptors++;
781   // Disables memory write in OnUserAlloc/Free.
782   thr->ignore_reads_and_writes++;
783 
784   __tsan_test_only_on_fork();
785 }
786 
787 static void ForkAfter(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
788   thr->suppress_reports--;  // Enabled in ForkBefore.
789   thr->ignore_interceptors--;
790   thr->ignore_reads_and_writes--;
791   AllocatorUnlock();
792   ScopedErrorReportLock::Unlock();
793   ctx->slot_mtx.Unlock();
794   ctx->thread_registry.Unlock();
795   for (auto& slot : ctx->slots) slot.mtx.Unlock();
796   SlotAttachAndLock(thr);
797   SlotUnlock(thr);
798   GlobalProcessorUnlock();
799 }
800 
801 void ForkParentAfter(ThreadState* thr, uptr pc) { ForkAfter(thr); }
802 
803 void ForkChildAfter(ThreadState* thr, uptr pc, bool start_thread) {
804   ForkAfter(thr);
805   u32 nthread = ctx->thread_registry.OnFork(thr->tid);
806   VPrintf(1,
807           "ThreadSanitizer: forked new process with pid %d,"
808           " parent had %d threads\n",
809           (int)internal_getpid(), (int)nthread);
810   if (nthread == 1) {
811     if (start_thread)
812       StartBackgroundThread();
813   } else {
814     // We've just forked a multi-threaded process. We cannot reasonably function
815     // after that (some mutexes may be locked before fork). So just enable
816     // ignores for everything in the hope that we will exec soon.
817     ctx->after_multithreaded_fork = true;
818     thr->ignore_interceptors++;
819     thr->suppress_reports++;
820     ThreadIgnoreBegin(thr, pc);
821     ThreadIgnoreSyncBegin(thr, pc);
822   }
823 }
824 #endif
825 
826 #if SANITIZER_GO
827 NOINLINE
828 void GrowShadowStack(ThreadState *thr) {
829   const int sz = thr->shadow_stack_end - thr->shadow_stack;
830   const int newsz = 2 * sz;
831   auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr));
832   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
833   Free(thr->shadow_stack);
834   thr->shadow_stack = newstack;
835   thr->shadow_stack_pos = newstack + sz;
836   thr->shadow_stack_end = newstack + newsz;
837 }
838 #endif
839 
840 StackID CurrentStackId(ThreadState *thr, uptr pc) {
841 #if !SANITIZER_GO
842   if (!thr->is_inited)  // May happen during bootstrap.
843     return kInvalidStackID;
844 #endif
845   if (pc != 0) {
846 #if !SANITIZER_GO
847     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
848 #else
849     if (thr->shadow_stack_pos == thr->shadow_stack_end)
850       GrowShadowStack(thr);
851 #endif
852     thr->shadow_stack_pos[0] = pc;
853     thr->shadow_stack_pos++;
854   }
855   StackID id = StackDepotPut(
856       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
857   if (pc != 0)
858     thr->shadow_stack_pos--;
859   return id;
860 }
861 
862 static bool TraceSkipGap(ThreadState* thr) {
863   Trace *trace = &thr->tctx->trace;
864   Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
865   DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0);
866   auto *part = trace->parts.Back();
867   DPrintf("#%d: TraceSwitchPart enter trace=%p parts=%p-%p pos=%p\n", thr->tid,
868           trace, trace->parts.Front(), part, pos);
869   if (!part)
870     return false;
871   // We can get here when we still have space in the current trace part.
872   // The fast-path check in TraceAcquire has false positives in the middle of
873   // the part. Check if we are indeed at the end of the current part or not,
874   // and fill any gaps with NopEvent's.
875   Event* end = &part->events[TracePart::kSize];
876   DCHECK_GE(pos, &part->events[0]);
877   DCHECK_LE(pos, end);
878   if (pos + 1 < end) {
879     if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) ==
880         TracePart::kAlignment)
881       *pos++ = NopEvent;
882     *pos++ = NopEvent;
883     DCHECK_LE(pos + 2, end);
884     atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos));
885     return true;
886   }
887   // We are indeed at the end.
888   for (; pos < end; pos++) *pos = NopEvent;
889   return false;
890 }
891 
892 NOINLINE
893 void TraceSwitchPart(ThreadState* thr) {
894   if (TraceSkipGap(thr))
895     return;
896 #if !SANITIZER_GO
897   if (ctx->after_multithreaded_fork) {
898     // We just need to survive till exec.
899     TracePart* part = thr->tctx->trace.parts.Back();
900     if (part) {
901       atomic_store_relaxed(&thr->trace_pos,
902                            reinterpret_cast<uptr>(&part->events[0]));
903       return;
904     }
905   }
906 #endif
907   TraceSwitchPartImpl(thr);
908 }
909 
910 void TraceSwitchPartImpl(ThreadState* thr) {
911   SlotLocker locker(thr, true);
912   Trace* trace = &thr->tctx->trace;
913   TracePart* part = TracePartAlloc(thr);
914   part->trace = trace;
915   thr->trace_prev_pc = 0;
916   TracePart* recycle = nullptr;
917   // Keep roughly half of parts local to the thread
918   // (not queued into the recycle queue).
919   uptr local_parts = (Trace::kMinParts + flags()->history_size + 1) / 2;
920   {
921     Lock lock(&trace->mtx);
922     if (trace->parts.Empty())
923       trace->local_head = part;
924     if (trace->parts.Size() >= local_parts) {
925       recycle = trace->local_head;
926       trace->local_head = trace->parts.Next(recycle);
927     }
928     trace->parts.PushBack(part);
929     atomic_store_relaxed(&thr->trace_pos,
930                          reinterpret_cast<uptr>(&part->events[0]));
931   }
932   // Make this part self-sufficient by restoring the current stack
933   // and mutex set in the beginning of the trace.
934   TraceTime(thr);
935   {
936     // Pathologically large stacks may not fit into the part.
937     // In these cases we log only fixed number of top frames.
938     const uptr kMaxFrames = 1000;
939     // Check that kMaxFrames won't consume the whole part.
940     static_assert(kMaxFrames < TracePart::kSize / 2, "kMaxFrames is too big");
941     uptr* pos = Max(&thr->shadow_stack[0], thr->shadow_stack_pos - kMaxFrames);
942     for (; pos < thr->shadow_stack_pos; pos++) {
943       if (TryTraceFunc(thr, *pos))
944         continue;
945       CHECK(TraceSkipGap(thr));
946       CHECK(TryTraceFunc(thr, *pos));
947     }
948   }
949   for (uptr i = 0; i < thr->mset.Size(); i++) {
950     MutexSet::Desc d = thr->mset.Get(i);
951     for (uptr i = 0; i < d.count; i++)
952       TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0,
953                      d.addr, d.stack_id);
954   }
955   {
956     Lock lock(&ctx->slot_mtx);
957     // There is a small chance that the slot may be not queued at this point.
958     // This can happen if the slot has kEpochLast epoch and another thread
959     // in FindSlotAndLock discovered that it's exhausted and removed it from
960     // the slot queue. kEpochLast can happen in 2 cases: (1) if TraceSwitchPart
961     // was called with the slot locked and epoch already at kEpochLast,
962     // or (2) if we've acquired a new slot in SlotLock in the beginning
963     // of the function and the slot was at kEpochLast - 1, so after increment
964     // in SlotAttachAndLock it become kEpochLast.
965     if (ctx->slot_queue.Queued(thr->slot)) {
966       ctx->slot_queue.Remove(thr->slot);
967       ctx->slot_queue.PushBack(thr->slot);
968     }
969     if (recycle)
970       ctx->trace_part_recycle.PushBack(recycle);
971   }
972   DPrintf("#%d: TraceSwitchPart exit parts=%p-%p pos=0x%zx\n", thr->tid,
973           trace->parts.Front(), trace->parts.Back(),
974           atomic_load_relaxed(&thr->trace_pos));
975 }
976 
977 void ThreadIgnoreBegin(ThreadState* thr, uptr pc) {
978   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
979   thr->ignore_reads_and_writes++;
980   CHECK_GT(thr->ignore_reads_and_writes, 0);
981   thr->fast_state.SetIgnoreBit();
982 #if !SANITIZER_GO
983   if (pc && !ctx->after_multithreaded_fork)
984     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
985 #endif
986 }
987 
988 void ThreadIgnoreEnd(ThreadState *thr) {
989   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
990   CHECK_GT(thr->ignore_reads_and_writes, 0);
991   thr->ignore_reads_and_writes--;
992   if (thr->ignore_reads_and_writes == 0) {
993     thr->fast_state.ClearIgnoreBit();
994 #if !SANITIZER_GO
995     thr->mop_ignore_set.Reset();
996 #endif
997   }
998 }
999 
1000 #if !SANITIZER_GO
1001 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
1002 uptr __tsan_testonly_shadow_stack_current_size() {
1003   ThreadState *thr = cur_thread();
1004   return thr->shadow_stack_pos - thr->shadow_stack;
1005 }
1006 #endif
1007 
1008 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
1009   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1010   thr->ignore_sync++;
1011   CHECK_GT(thr->ignore_sync, 0);
1012 #if !SANITIZER_GO
1013   if (pc && !ctx->after_multithreaded_fork)
1014     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1015 #endif
1016 }
1017 
1018 void ThreadIgnoreSyncEnd(ThreadState *thr) {
1019   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1020   CHECK_GT(thr->ignore_sync, 0);
1021   thr->ignore_sync--;
1022 #if !SANITIZER_GO
1023   if (thr->ignore_sync == 0)
1024     thr->sync_ignore_set.Reset();
1025 #endif
1026 }
1027 
1028 bool MD5Hash::operator==(const MD5Hash &other) const {
1029   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1030 }
1031 
1032 #if SANITIZER_DEBUG
1033 void build_consistency_debug() {}
1034 #else
1035 void build_consistency_release() {}
1036 #endif
1037 }  // namespace __tsan
1038 
1039 #if SANITIZER_CHECK_DEADLOCKS
1040 namespace __sanitizer {
1041 using namespace __tsan;
1042 MutexMeta mutex_meta[] = {
1043     {MutexInvalid, "Invalid", {}},
1044     {MutexThreadRegistry,
1045      "ThreadRegistry",
1046      {MutexTypeSlots, MutexTypeTrace, MutexTypeReport}},
1047     {MutexTypeReport, "Report", {MutexTypeTrace}},
1048     {MutexTypeSyncVar, "SyncVar", {MutexTypeReport, MutexTypeTrace}},
1049     {MutexTypeAnnotations, "Annotations", {}},
1050     {MutexTypeAtExit, "AtExit", {}},
1051     {MutexTypeFired, "Fired", {MutexLeaf}},
1052     {MutexTypeRacy, "Racy", {MutexLeaf}},
1053     {MutexTypeGlobalProc, "GlobalProc", {MutexTypeSlot, MutexTypeSlots}},
1054     {MutexTypeInternalAlloc, "InternalAlloc", {MutexLeaf}},
1055     {MutexTypeTrace, "Trace", {}},
1056     {MutexTypeSlot,
1057      "Slot",
1058      {MutexMulti, MutexTypeTrace, MutexTypeSyncVar, MutexThreadRegistry,
1059       MutexTypeSlots}},
1060     {MutexTypeSlots, "Slots", {MutexTypeTrace, MutexTypeReport}},
1061     {},
1062 };
1063 
1064 void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
1065 
1066 }  // namespace __sanitizer
1067 #endif
1068