xref: /freebsd-src/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
168d75effSDimitry Andric //===-- tsan_rtl.cpp ------------------------------------------------------===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric //
968d75effSDimitry Andric // This file is a part of ThreadSanitizer (TSan), a race detector.
1068d75effSDimitry Andric //
1168d75effSDimitry Andric // Main file (entry points) for the TSan run-time.
1268d75effSDimitry Andric //===----------------------------------------------------------------------===//
1368d75effSDimitry Andric 
14fe6060f1SDimitry Andric #include "tsan_rtl.h"
15fe6060f1SDimitry Andric 
1668d75effSDimitry Andric #include "sanitizer_common/sanitizer_atomic.h"
1768d75effSDimitry Andric #include "sanitizer_common/sanitizer_common.h"
1868d75effSDimitry Andric #include "sanitizer_common/sanitizer_file.h"
1981ad6265SDimitry Andric #include "sanitizer_common/sanitizer_interface_internal.h"
2068d75effSDimitry Andric #include "sanitizer_common/sanitizer_libc.h"
2168d75effSDimitry Andric #include "sanitizer_common/sanitizer_placement_new.h"
22fe6060f1SDimitry Andric #include "sanitizer_common/sanitizer_stackdepot.h"
2368d75effSDimitry Andric #include "sanitizer_common/sanitizer_symbolizer.h"
2468d75effSDimitry Andric #include "tsan_defs.h"
25fe6060f1SDimitry Andric #include "tsan_interface.h"
2668d75effSDimitry Andric #include "tsan_mman.h"
27fe6060f1SDimitry Andric #include "tsan_platform.h"
2868d75effSDimitry Andric #include "tsan_suppressions.h"
2968d75effSDimitry Andric #include "tsan_symbolize.h"
3068d75effSDimitry Andric #include "ubsan/ubsan_init.h"
3168d75effSDimitry Andric 
3268d75effSDimitry Andric volatile int __tsan_resumed = 0;
3368d75effSDimitry Andric 
3468d75effSDimitry Andric extern "C" void __tsan_resume() {
3568d75effSDimitry Andric   __tsan_resumed = 1;
3668d75effSDimitry Andric }
3768d75effSDimitry Andric 
384824e7fdSDimitry Andric SANITIZER_WEAK_DEFAULT_IMPL
394824e7fdSDimitry Andric void __tsan_test_only_on_fork() {}
404824e7fdSDimitry Andric 
4168d75effSDimitry Andric namespace __tsan {
4268d75effSDimitry Andric 
43349cc55cSDimitry Andric #if !SANITIZER_GO
44349cc55cSDimitry Andric void (*on_initialize)(void);
45349cc55cSDimitry Andric int (*on_finalize)(int);
46349cc55cSDimitry Andric #endif
47349cc55cSDimitry Andric 
4881ad6265SDimitry Andric #if !SANITIZER_GO && !SANITIZER_APPLE
4968d75effSDimitry Andric __attribute__((tls_model("initial-exec")))
50349cc55cSDimitry Andric THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(
51349cc55cSDimitry Andric     SANITIZER_CACHE_LINE_SIZE);
5268d75effSDimitry Andric #endif
53349cc55cSDimitry Andric static char ctx_placeholder[sizeof(Context)] ALIGNED(SANITIZER_CACHE_LINE_SIZE);
5468d75effSDimitry Andric Context *ctx;
5568d75effSDimitry Andric 
5668d75effSDimitry Andric // Can be overriden by a front-end.
5768d75effSDimitry Andric #ifdef TSAN_EXTERNAL_HOOKS
5868d75effSDimitry Andric bool OnFinalize(bool failed);
5968d75effSDimitry Andric void OnInitialize();
6068d75effSDimitry Andric #else
6168d75effSDimitry Andric SANITIZER_WEAK_CXX_DEFAULT_IMPL
6268d75effSDimitry Andric bool OnFinalize(bool failed) {
63fe6060f1SDimitry Andric #  if !SANITIZER_GO
64349cc55cSDimitry Andric   if (on_finalize)
65349cc55cSDimitry Andric     return on_finalize(failed);
66fe6060f1SDimitry Andric #  endif
6768d75effSDimitry Andric   return failed;
6868d75effSDimitry Andric }
690eae32dcSDimitry Andric 
7068d75effSDimitry Andric SANITIZER_WEAK_CXX_DEFAULT_IMPL
71fe6060f1SDimitry Andric void OnInitialize() {
72fe6060f1SDimitry Andric #  if !SANITIZER_GO
73349cc55cSDimitry Andric   if (on_initialize)
74349cc55cSDimitry Andric     on_initialize();
75fe6060f1SDimitry Andric #  endif
76fe6060f1SDimitry Andric }
7768d75effSDimitry Andric #endif
7868d75effSDimitry Andric 
790eae32dcSDimitry Andric static TracePart* TracePartAlloc(ThreadState* thr) {
800eae32dcSDimitry Andric   TracePart* part = nullptr;
810eae32dcSDimitry Andric   {
820eae32dcSDimitry Andric     Lock lock(&ctx->slot_mtx);
830eae32dcSDimitry Andric     uptr max_parts = Trace::kMinParts + flags()->history_size;
840eae32dcSDimitry Andric     Trace* trace = &thr->tctx->trace;
850eae32dcSDimitry Andric     if (trace->parts_allocated == max_parts ||
860eae32dcSDimitry Andric         ctx->trace_part_finished_excess) {
870eae32dcSDimitry Andric       part = ctx->trace_part_recycle.PopFront();
880eae32dcSDimitry Andric       DPrintf("#%d: TracePartAlloc: part=%p\n", thr->tid, part);
890eae32dcSDimitry Andric       if (part && part->trace) {
900eae32dcSDimitry Andric         Trace* trace1 = part->trace;
910eae32dcSDimitry Andric         Lock trace_lock(&trace1->mtx);
920eae32dcSDimitry Andric         part->trace = nullptr;
930eae32dcSDimitry Andric         TracePart* part1 = trace1->parts.PopFront();
940eae32dcSDimitry Andric         CHECK_EQ(part, part1);
950eae32dcSDimitry Andric         if (trace1->parts_allocated > trace1->parts.Size()) {
960eae32dcSDimitry Andric           ctx->trace_part_finished_excess +=
970eae32dcSDimitry Andric               trace1->parts_allocated - trace1->parts.Size();
980eae32dcSDimitry Andric           trace1->parts_allocated = trace1->parts.Size();
99fe6060f1SDimitry Andric         }
100fe6060f1SDimitry Andric       }
1010eae32dcSDimitry Andric     }
1020eae32dcSDimitry Andric     if (trace->parts_allocated < max_parts) {
1030eae32dcSDimitry Andric       trace->parts_allocated++;
1040eae32dcSDimitry Andric       if (ctx->trace_part_finished_excess)
1050eae32dcSDimitry Andric         ctx->trace_part_finished_excess--;
1060eae32dcSDimitry Andric     }
1070eae32dcSDimitry Andric     if (!part)
1080eae32dcSDimitry Andric       ctx->trace_part_total_allocated++;
1090eae32dcSDimitry Andric     else if (ctx->trace_part_recycle_finished)
1100eae32dcSDimitry Andric       ctx->trace_part_recycle_finished--;
1110eae32dcSDimitry Andric   }
1120eae32dcSDimitry Andric   if (!part)
1130eae32dcSDimitry Andric     part = new (MmapOrDie(sizeof(*part), "TracePart")) TracePart();
1140eae32dcSDimitry Andric   return part;
11568d75effSDimitry Andric }
11668d75effSDimitry Andric 
11704eeddc0SDimitry Andric static void TracePartFree(TracePart* part) SANITIZER_REQUIRES(ctx->slot_mtx) {
1180eae32dcSDimitry Andric   DCHECK(part->trace);
1190eae32dcSDimitry Andric   part->trace = nullptr;
1200eae32dcSDimitry Andric   ctx->trace_part_recycle.PushFront(part);
1210eae32dcSDimitry Andric }
1220eae32dcSDimitry Andric 
1230eae32dcSDimitry Andric void TraceResetForTesting() {
1240eae32dcSDimitry Andric   Lock lock(&ctx->slot_mtx);
1250eae32dcSDimitry Andric   while (auto* part = ctx->trace_part_recycle.PopFront()) {
1260eae32dcSDimitry Andric     if (auto trace = part->trace)
1270eae32dcSDimitry Andric       CHECK_EQ(trace->parts.PopFront(), part);
1280eae32dcSDimitry Andric     UnmapOrDie(part, sizeof(*part));
1290eae32dcSDimitry Andric   }
1300eae32dcSDimitry Andric   ctx->trace_part_total_allocated = 0;
1310eae32dcSDimitry Andric   ctx->trace_part_recycle_finished = 0;
1320eae32dcSDimitry Andric   ctx->trace_part_finished_excess = 0;
1330eae32dcSDimitry Andric }
1340eae32dcSDimitry Andric 
1350eae32dcSDimitry Andric static void DoResetImpl(uptr epoch) {
1360eae32dcSDimitry Andric   ThreadRegistryLock lock0(&ctx->thread_registry);
1370eae32dcSDimitry Andric   Lock lock1(&ctx->slot_mtx);
1380eae32dcSDimitry Andric   CHECK_EQ(ctx->global_epoch, epoch);
1390eae32dcSDimitry Andric   ctx->global_epoch++;
1400eae32dcSDimitry Andric   CHECK(!ctx->resetting);
1410eae32dcSDimitry Andric   ctx->resetting = true;
1420eae32dcSDimitry Andric   for (u32 i = ctx->thread_registry.NumThreadsLocked(); i--;) {
1430eae32dcSDimitry Andric     ThreadContext* tctx = (ThreadContext*)ctx->thread_registry.GetThreadLocked(
1440eae32dcSDimitry Andric         static_cast<Tid>(i));
1450eae32dcSDimitry Andric     // Potentially we could purge all ThreadStatusDead threads from the
1460eae32dcSDimitry Andric     // registry. Since we reset all shadow, they can't race with anything
1470eae32dcSDimitry Andric     // anymore. However, their tid's can still be stored in some aux places
1480eae32dcSDimitry Andric     // (e.g. tid of thread that created something).
1490eae32dcSDimitry Andric     auto trace = &tctx->trace;
1500eae32dcSDimitry Andric     Lock lock(&trace->mtx);
1510eae32dcSDimitry Andric     bool attached = tctx->thr && tctx->thr->slot;
1520eae32dcSDimitry Andric     auto parts = &trace->parts;
1530eae32dcSDimitry Andric     bool local = false;
1540eae32dcSDimitry Andric     while (!parts->Empty()) {
1550eae32dcSDimitry Andric       auto part = parts->Front();
1560eae32dcSDimitry Andric       local = local || part == trace->local_head;
1570eae32dcSDimitry Andric       if (local)
1580eae32dcSDimitry Andric         CHECK(!ctx->trace_part_recycle.Queued(part));
1590eae32dcSDimitry Andric       else
1600eae32dcSDimitry Andric         ctx->trace_part_recycle.Remove(part);
1610eae32dcSDimitry Andric       if (attached && parts->Size() == 1) {
1620eae32dcSDimitry Andric         // The thread is running and this is the last/current part.
1630eae32dcSDimitry Andric         // Set the trace position to the end of the current part
1640eae32dcSDimitry Andric         // to force the thread to call SwitchTracePart and re-attach
1650eae32dcSDimitry Andric         // to a new slot and allocate a new trace part.
1660eae32dcSDimitry Andric         // Note: the thread is concurrently modifying the position as well,
1670eae32dcSDimitry Andric         // so this is only best-effort. The thread can only modify position
1680eae32dcSDimitry Andric         // within this part, because switching parts is protected by
1690eae32dcSDimitry Andric         // slot/trace mutexes that we hold here.
1700eae32dcSDimitry Andric         atomic_store_relaxed(
1710eae32dcSDimitry Andric             &tctx->thr->trace_pos,
1720eae32dcSDimitry Andric             reinterpret_cast<uptr>(&part->events[TracePart::kSize]));
1730eae32dcSDimitry Andric         break;
1740eae32dcSDimitry Andric       }
1750eae32dcSDimitry Andric       parts->Remove(part);
1760eae32dcSDimitry Andric       TracePartFree(part);
1770eae32dcSDimitry Andric     }
1780eae32dcSDimitry Andric     CHECK_LE(parts->Size(), 1);
1790eae32dcSDimitry Andric     trace->local_head = parts->Front();
1800eae32dcSDimitry Andric     if (tctx->thr && !tctx->thr->slot) {
1810eae32dcSDimitry Andric       atomic_store_relaxed(&tctx->thr->trace_pos, 0);
1820eae32dcSDimitry Andric       tctx->thr->trace_prev_pc = 0;
1830eae32dcSDimitry Andric     }
1840eae32dcSDimitry Andric     if (trace->parts_allocated > trace->parts.Size()) {
1850eae32dcSDimitry Andric       ctx->trace_part_finished_excess +=
1860eae32dcSDimitry Andric           trace->parts_allocated - trace->parts.Size();
1870eae32dcSDimitry Andric       trace->parts_allocated = trace->parts.Size();
1880eae32dcSDimitry Andric     }
1890eae32dcSDimitry Andric   }
1900eae32dcSDimitry Andric   while (ctx->slot_queue.PopFront()) {
1910eae32dcSDimitry Andric   }
1920eae32dcSDimitry Andric   for (auto& slot : ctx->slots) {
1930eae32dcSDimitry Andric     slot.SetEpoch(kEpochZero);
1940eae32dcSDimitry Andric     slot.journal.Reset();
1950eae32dcSDimitry Andric     slot.thr = nullptr;
1960eae32dcSDimitry Andric     ctx->slot_queue.PushBack(&slot);
1970eae32dcSDimitry Andric   }
1980eae32dcSDimitry Andric 
1990eae32dcSDimitry Andric   DPrintf("Resetting shadow...\n");
200*972a253aSDimitry Andric   auto shadow_begin = ShadowBeg();
201*972a253aSDimitry Andric   auto shadow_end = ShadowEnd();
202*972a253aSDimitry Andric #if SANITIZER_GO
203*972a253aSDimitry Andric   CHECK_NE(0, ctx->mapped_shadow_begin);
204*972a253aSDimitry Andric   shadow_begin = ctx->mapped_shadow_begin;
205*972a253aSDimitry Andric   shadow_end = ctx->mapped_shadow_end;
206*972a253aSDimitry Andric   VPrintf(2, "shadow_begin-shadow_end: (0x%zx-0x%zx)\n",
207*972a253aSDimitry Andric           shadow_begin, shadow_end);
208*972a253aSDimitry Andric #endif
209*972a253aSDimitry Andric 
210*972a253aSDimitry Andric #if SANITIZER_WINDOWS
211*972a253aSDimitry Andric   auto resetFailed =
212*972a253aSDimitry Andric       !ZeroMmapFixedRegion(shadow_begin, shadow_end - shadow_begin);
213*972a253aSDimitry Andric #else
214*972a253aSDimitry Andric   auto resetFailed =
215*972a253aSDimitry Andric       !MmapFixedSuperNoReserve(shadow_begin, shadow_end-shadow_begin, "shadow");
216*972a253aSDimitry Andric #endif
217*972a253aSDimitry Andric   if (resetFailed) {
2180eae32dcSDimitry Andric     Printf("failed to reset shadow memory\n");
2190eae32dcSDimitry Andric     Die();
2200eae32dcSDimitry Andric   }
2210eae32dcSDimitry Andric   DPrintf("Resetting meta shadow...\n");
2220eae32dcSDimitry Andric   ctx->metamap.ResetClocks();
223*972a253aSDimitry Andric   StoreShadow(&ctx->last_spurious_race, Shadow::kEmpty);
2240eae32dcSDimitry Andric   ctx->resetting = false;
2250eae32dcSDimitry Andric }
2260eae32dcSDimitry Andric 
2270eae32dcSDimitry Andric // Clang does not understand locking all slots in the loop:
2280eae32dcSDimitry Andric // error: expecting mutex 'slot.mtx' to be held at start of each loop
22904eeddc0SDimitry Andric void DoReset(ThreadState* thr, uptr epoch) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
2300eae32dcSDimitry Andric   for (auto& slot : ctx->slots) {
2310eae32dcSDimitry Andric     slot.mtx.Lock();
2320eae32dcSDimitry Andric     if (UNLIKELY(epoch == 0))
2330eae32dcSDimitry Andric       epoch = ctx->global_epoch;
2340eae32dcSDimitry Andric     if (UNLIKELY(epoch != ctx->global_epoch)) {
2350eae32dcSDimitry Andric       // Epoch can't change once we've locked the first slot.
2360eae32dcSDimitry Andric       CHECK_EQ(slot.sid, 0);
2370eae32dcSDimitry Andric       slot.mtx.Unlock();
2380eae32dcSDimitry Andric       return;
2390eae32dcSDimitry Andric     }
2400eae32dcSDimitry Andric   }
2410eae32dcSDimitry Andric   DPrintf("#%d: DoReset epoch=%lu\n", thr ? thr->tid : -1, epoch);
2420eae32dcSDimitry Andric   DoResetImpl(epoch);
2430eae32dcSDimitry Andric   for (auto& slot : ctx->slots) slot.mtx.Unlock();
2440eae32dcSDimitry Andric }
2450eae32dcSDimitry Andric 
2460eae32dcSDimitry Andric void FlushShadowMemory() { DoReset(nullptr, 0); }
2470eae32dcSDimitry Andric 
2480eae32dcSDimitry Andric static TidSlot* FindSlotAndLock(ThreadState* thr)
24904eeddc0SDimitry Andric     SANITIZER_ACQUIRE(thr->slot->mtx) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
2500eae32dcSDimitry Andric   CHECK(!thr->slot);
2510eae32dcSDimitry Andric   TidSlot* slot = nullptr;
2520eae32dcSDimitry Andric   for (;;) {
2530eae32dcSDimitry Andric     uptr epoch;
2540eae32dcSDimitry Andric     {
2550eae32dcSDimitry Andric       Lock lock(&ctx->slot_mtx);
2560eae32dcSDimitry Andric       epoch = ctx->global_epoch;
2570eae32dcSDimitry Andric       if (slot) {
2580eae32dcSDimitry Andric         // This is an exhausted slot from the previous iteration.
2590eae32dcSDimitry Andric         if (ctx->slot_queue.Queued(slot))
2600eae32dcSDimitry Andric           ctx->slot_queue.Remove(slot);
2610eae32dcSDimitry Andric         thr->slot_locked = false;
2620eae32dcSDimitry Andric         slot->mtx.Unlock();
2630eae32dcSDimitry Andric       }
2640eae32dcSDimitry Andric       for (;;) {
2650eae32dcSDimitry Andric         slot = ctx->slot_queue.PopFront();
2660eae32dcSDimitry Andric         if (!slot)
2670eae32dcSDimitry Andric           break;
2680eae32dcSDimitry Andric         if (slot->epoch() != kEpochLast) {
2690eae32dcSDimitry Andric           ctx->slot_queue.PushBack(slot);
2700eae32dcSDimitry Andric           break;
2710eae32dcSDimitry Andric         }
2720eae32dcSDimitry Andric       }
2730eae32dcSDimitry Andric     }
2740eae32dcSDimitry Andric     if (!slot) {
2750eae32dcSDimitry Andric       DoReset(thr, epoch);
2760eae32dcSDimitry Andric       continue;
2770eae32dcSDimitry Andric     }
2780eae32dcSDimitry Andric     slot->mtx.Lock();
2790eae32dcSDimitry Andric     CHECK(!thr->slot_locked);
2800eae32dcSDimitry Andric     thr->slot_locked = true;
2810eae32dcSDimitry Andric     if (slot->thr) {
2820eae32dcSDimitry Andric       DPrintf("#%d: preempting sid=%d tid=%d\n", thr->tid, (u32)slot->sid,
2830eae32dcSDimitry Andric               slot->thr->tid);
2840eae32dcSDimitry Andric       slot->SetEpoch(slot->thr->fast_state.epoch());
2850eae32dcSDimitry Andric       slot->thr = nullptr;
2860eae32dcSDimitry Andric     }
2870eae32dcSDimitry Andric     if (slot->epoch() != kEpochLast)
2880eae32dcSDimitry Andric       return slot;
2890eae32dcSDimitry Andric   }
2900eae32dcSDimitry Andric }
2910eae32dcSDimitry Andric 
2920eae32dcSDimitry Andric void SlotAttachAndLock(ThreadState* thr) {
2930eae32dcSDimitry Andric   TidSlot* slot = FindSlotAndLock(thr);
2940eae32dcSDimitry Andric   DPrintf("#%d: SlotAttach: slot=%u\n", thr->tid, static_cast<int>(slot->sid));
2950eae32dcSDimitry Andric   CHECK(!slot->thr);
2960eae32dcSDimitry Andric   CHECK(!thr->slot);
2970eae32dcSDimitry Andric   slot->thr = thr;
2980eae32dcSDimitry Andric   thr->slot = slot;
2990eae32dcSDimitry Andric   Epoch epoch = EpochInc(slot->epoch());
3000eae32dcSDimitry Andric   CHECK(!EpochOverflow(epoch));
3010eae32dcSDimitry Andric   slot->SetEpoch(epoch);
3020eae32dcSDimitry Andric   thr->fast_state.SetSid(slot->sid);
3030eae32dcSDimitry Andric   thr->fast_state.SetEpoch(epoch);
3040eae32dcSDimitry Andric   if (thr->slot_epoch != ctx->global_epoch) {
3050eae32dcSDimitry Andric     thr->slot_epoch = ctx->global_epoch;
3060eae32dcSDimitry Andric     thr->clock.Reset();
30768d75effSDimitry Andric #if !SANITIZER_GO
3080eae32dcSDimitry Andric     thr->last_sleep_stack_id = kInvalidStackID;
3090eae32dcSDimitry Andric     thr->last_sleep_clock.Reset();
31068d75effSDimitry Andric #endif
3110eae32dcSDimitry Andric   }
3120eae32dcSDimitry Andric   thr->clock.Set(slot->sid, epoch);
3130eae32dcSDimitry Andric   slot->journal.PushBack({thr->tid, epoch});
3140eae32dcSDimitry Andric }
3150eae32dcSDimitry Andric 
3160eae32dcSDimitry Andric static void SlotDetachImpl(ThreadState* thr, bool exiting) {
3170eae32dcSDimitry Andric   TidSlot* slot = thr->slot;
3180eae32dcSDimitry Andric   thr->slot = nullptr;
3190eae32dcSDimitry Andric   if (thr != slot->thr) {
3200eae32dcSDimitry Andric     slot = nullptr;  // we don't own the slot anymore
3210eae32dcSDimitry Andric     if (thr->slot_epoch != ctx->global_epoch) {
3220eae32dcSDimitry Andric       TracePart* part = nullptr;
3230eae32dcSDimitry Andric       auto* trace = &thr->tctx->trace;
3240eae32dcSDimitry Andric       {
3250eae32dcSDimitry Andric         Lock l(&trace->mtx);
3260eae32dcSDimitry Andric         auto* parts = &trace->parts;
3270eae32dcSDimitry Andric         // The trace can be completely empty in an unlikely event
3280eae32dcSDimitry Andric         // the thread is preempted right after it acquired the slot
3290eae32dcSDimitry Andric         // in ThreadStart and did not trace any events yet.
3300eae32dcSDimitry Andric         CHECK_LE(parts->Size(), 1);
3310eae32dcSDimitry Andric         part = parts->PopFront();
3320eae32dcSDimitry Andric         thr->tctx->trace.local_head = nullptr;
3330eae32dcSDimitry Andric         atomic_store_relaxed(&thr->trace_pos, 0);
3340eae32dcSDimitry Andric         thr->trace_prev_pc = 0;
3350eae32dcSDimitry Andric       }
3360eae32dcSDimitry Andric       if (part) {
3370eae32dcSDimitry Andric         Lock l(&ctx->slot_mtx);
3380eae32dcSDimitry Andric         TracePartFree(part);
3390eae32dcSDimitry Andric       }
3400eae32dcSDimitry Andric     }
3410eae32dcSDimitry Andric     return;
3420eae32dcSDimitry Andric   }
3430eae32dcSDimitry Andric   CHECK(exiting || thr->fast_state.epoch() == kEpochLast);
3440eae32dcSDimitry Andric   slot->SetEpoch(thr->fast_state.epoch());
3450eae32dcSDimitry Andric   slot->thr = nullptr;
3460eae32dcSDimitry Andric }
3470eae32dcSDimitry Andric 
3480eae32dcSDimitry Andric void SlotDetach(ThreadState* thr) {
3490eae32dcSDimitry Andric   Lock lock(&thr->slot->mtx);
3500eae32dcSDimitry Andric   SlotDetachImpl(thr, true);
3510eae32dcSDimitry Andric }
3520eae32dcSDimitry Andric 
35304eeddc0SDimitry Andric void SlotLock(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
3540eae32dcSDimitry Andric   DCHECK(!thr->slot_locked);
3550eae32dcSDimitry Andric #if SANITIZER_DEBUG
3560eae32dcSDimitry Andric   // Check these mutexes are not locked.
3570eae32dcSDimitry Andric   // We can call DoReset from SlotAttachAndLock, which will lock
3580eae32dcSDimitry Andric   // these mutexes, but it happens only every once in a while.
3590eae32dcSDimitry Andric   { ThreadRegistryLock lock(&ctx->thread_registry); }
3600eae32dcSDimitry Andric   { Lock lock(&ctx->slot_mtx); }
3610eae32dcSDimitry Andric #endif
3620eae32dcSDimitry Andric   TidSlot* slot = thr->slot;
3630eae32dcSDimitry Andric   slot->mtx.Lock();
3640eae32dcSDimitry Andric   thr->slot_locked = true;
3650eae32dcSDimitry Andric   if (LIKELY(thr == slot->thr && thr->fast_state.epoch() != kEpochLast))
3660eae32dcSDimitry Andric     return;
3670eae32dcSDimitry Andric   SlotDetachImpl(thr, false);
3680eae32dcSDimitry Andric   thr->slot_locked = false;
3690eae32dcSDimitry Andric   slot->mtx.Unlock();
3700eae32dcSDimitry Andric   SlotAttachAndLock(thr);
3710eae32dcSDimitry Andric }
3720eae32dcSDimitry Andric 
3730eae32dcSDimitry Andric void SlotUnlock(ThreadState* thr) {
3740eae32dcSDimitry Andric   DCHECK(thr->slot_locked);
3750eae32dcSDimitry Andric   thr->slot_locked = false;
3760eae32dcSDimitry Andric   thr->slot->mtx.Unlock();
3770eae32dcSDimitry Andric }
37868d75effSDimitry Andric 
37968d75effSDimitry Andric Context::Context()
380fe6060f1SDimitry Andric     : initialized(),
381fe6060f1SDimitry Andric       report_mtx(MutexTypeReport),
382fe6060f1SDimitry Andric       nreported(),
3830eae32dcSDimitry Andric       thread_registry([](Tid tid) -> ThreadContextBase* {
3840eae32dcSDimitry Andric         return new (Alloc(sizeof(ThreadContext))) ThreadContext(tid);
3850eae32dcSDimitry Andric       }),
386fe6060f1SDimitry Andric       racy_mtx(MutexTypeRacy),
387fe6060f1SDimitry Andric       racy_stacks(),
388fe6060f1SDimitry Andric       fired_suppressions_mtx(MutexTypeFired),
3890eae32dcSDimitry Andric       slot_mtx(MutexTypeSlots),
3900eae32dcSDimitry Andric       resetting() {
39168d75effSDimitry Andric   fired_suppressions.reserve(8);
3920eae32dcSDimitry Andric   for (uptr i = 0; i < ARRAY_SIZE(slots); i++) {
3930eae32dcSDimitry Andric     TidSlot* slot = &slots[i];
3940eae32dcSDimitry Andric     slot->sid = static_cast<Sid>(i);
3950eae32dcSDimitry Andric     slot_queue.PushBack(slot);
3960eae32dcSDimitry Andric   }
3970eae32dcSDimitry Andric   global_epoch = 1;
39868d75effSDimitry Andric }
39968d75effSDimitry Andric 
4000eae32dcSDimitry Andric TidSlot::TidSlot() : mtx(MutexTypeSlot) {}
4010eae32dcSDimitry Andric 
40268d75effSDimitry Andric // The objects are allocated in TLS, so one may rely on zero-initialization.
4030eae32dcSDimitry Andric ThreadState::ThreadState(Tid tid)
40468d75effSDimitry Andric     // Do not touch these, rely on zero initialization,
40568d75effSDimitry Andric     // they may be accessed before the ctor.
4060eae32dcSDimitry Andric     // ignore_reads_and_writes()
4070eae32dcSDimitry Andric     // ignore_interceptors()
4080eae32dcSDimitry Andric     : tid(tid) {
409349cc55cSDimitry Andric   CHECK_EQ(reinterpret_cast<uptr>(this) % SANITIZER_CACHE_LINE_SIZE, 0);
410349cc55cSDimitry Andric #if !SANITIZER_GO
411349cc55cSDimitry Andric   // C/C++ uses fixed size shadow stack.
412349cc55cSDimitry Andric   const int kInitStackSize = kShadowStackSize;
413349cc55cSDimitry Andric   shadow_stack = static_cast<uptr*>(
414349cc55cSDimitry Andric       MmapNoReserveOrDie(kInitStackSize * sizeof(uptr), "shadow stack"));
415349cc55cSDimitry Andric   SetShadowRegionHugePageMode(reinterpret_cast<uptr>(shadow_stack),
416349cc55cSDimitry Andric                               kInitStackSize * sizeof(uptr));
417349cc55cSDimitry Andric #else
418349cc55cSDimitry Andric   // Go uses malloc-allocated shadow stack with dynamic size.
419349cc55cSDimitry Andric   const int kInitStackSize = 8;
420349cc55cSDimitry Andric   shadow_stack = static_cast<uptr*>(Alloc(kInitStackSize * sizeof(uptr)));
421349cc55cSDimitry Andric #endif
422349cc55cSDimitry Andric   shadow_stack_pos = shadow_stack;
423349cc55cSDimitry Andric   shadow_stack_end = shadow_stack + kInitStackSize;
42468d75effSDimitry Andric }
42568d75effSDimitry Andric 
42668d75effSDimitry Andric #if !SANITIZER_GO
427349cc55cSDimitry Andric void MemoryProfiler(u64 uptime) {
428349cc55cSDimitry Andric   if (ctx->memprof_fd == kInvalidFd)
429349cc55cSDimitry Andric     return;
43068d75effSDimitry Andric   InternalMmapVector<char> buf(4096);
431349cc55cSDimitry Andric   WriteMemoryProfile(buf.data(), buf.size(), uptime);
432349cc55cSDimitry Andric   WriteToFile(ctx->memprof_fd, buf.data(), internal_strlen(buf.data()));
433349cc55cSDimitry Andric }
434349cc55cSDimitry Andric 
4350eae32dcSDimitry Andric static bool InitializeMemoryProfiler() {
436349cc55cSDimitry Andric   ctx->memprof_fd = kInvalidFd;
437349cc55cSDimitry Andric   const char *fname = flags()->profile_memory;
438349cc55cSDimitry Andric   if (!fname || !fname[0])
4390eae32dcSDimitry Andric     return false;
440349cc55cSDimitry Andric   if (internal_strcmp(fname, "stdout") == 0) {
441349cc55cSDimitry Andric     ctx->memprof_fd = 1;
442349cc55cSDimitry Andric   } else if (internal_strcmp(fname, "stderr") == 0) {
443349cc55cSDimitry Andric     ctx->memprof_fd = 2;
444349cc55cSDimitry Andric   } else {
445349cc55cSDimitry Andric     InternalScopedString filename;
446349cc55cSDimitry Andric     filename.append("%s.%d", fname, (int)internal_getpid());
447349cc55cSDimitry Andric     ctx->memprof_fd = OpenFile(filename.data(), WrOnly);
448349cc55cSDimitry Andric     if (ctx->memprof_fd == kInvalidFd) {
449349cc55cSDimitry Andric       Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
450349cc55cSDimitry Andric              filename.data());
4510eae32dcSDimitry Andric       return false;
452349cc55cSDimitry Andric     }
453349cc55cSDimitry Andric   }
454349cc55cSDimitry Andric   MemoryProfiler(0);
4550eae32dcSDimitry Andric   return true;
45668d75effSDimitry Andric }
45768d75effSDimitry Andric 
4585ffd83dbSDimitry Andric static void *BackgroundThread(void *arg) {
45968d75effSDimitry Andric   // This is a non-initialized non-user thread, nothing to see here.
46068d75effSDimitry Andric   // We don't use ScopedIgnoreInterceptors, because we want ignores to be
46168d75effSDimitry Andric   // enabled even when the thread function exits (e.g. during pthread thread
46268d75effSDimitry Andric   // shutdown code).
463349cc55cSDimitry Andric   cur_thread_init()->ignore_interceptors++;
46468d75effSDimitry Andric   const u64 kMs2Ns = 1000 * 1000;
465349cc55cSDimitry Andric   const u64 start = NanoTime();
46668d75effSDimitry Andric 
4670eae32dcSDimitry Andric   u64 last_flush = start;
46868d75effSDimitry Andric   uptr last_rss = 0;
4690eae32dcSDimitry Andric   while (!atomic_load_relaxed(&ctx->stop_background_thread)) {
47068d75effSDimitry Andric     SleepForMillis(100);
47168d75effSDimitry Andric     u64 now = NanoTime();
47268d75effSDimitry Andric 
47368d75effSDimitry Andric     // Flush memory if requested.
47468d75effSDimitry Andric     if (flags()->flush_memory_ms > 0) {
47568d75effSDimitry Andric       if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
4760eae32dcSDimitry Andric         VReport(1, "ThreadSanitizer: periodic memory flush\n");
47768d75effSDimitry Andric         FlushShadowMemory();
4780eae32dcSDimitry Andric         now = last_flush = NanoTime();
47968d75effSDimitry Andric       }
48068d75effSDimitry Andric     }
48168d75effSDimitry Andric     if (flags()->memory_limit_mb > 0) {
48268d75effSDimitry Andric       uptr rss = GetRSS();
48368d75effSDimitry Andric       uptr limit = uptr(flags()->memory_limit_mb) << 20;
4840eae32dcSDimitry Andric       VReport(1,
4850eae32dcSDimitry Andric               "ThreadSanitizer: memory flush check"
48668d75effSDimitry Andric               " RSS=%llu LAST=%llu LIMIT=%llu\n",
48768d75effSDimitry Andric               (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
48868d75effSDimitry Andric       if (2 * rss > limit + last_rss) {
4890eae32dcSDimitry Andric         VReport(1, "ThreadSanitizer: flushing memory due to RSS\n");
49068d75effSDimitry Andric         FlushShadowMemory();
49168d75effSDimitry Andric         rss = GetRSS();
4920eae32dcSDimitry Andric         now = NanoTime();
4930eae32dcSDimitry Andric         VReport(1, "ThreadSanitizer: memory flushed RSS=%llu\n",
4940eae32dcSDimitry Andric                 (u64)rss >> 20);
49568d75effSDimitry Andric       }
49668d75effSDimitry Andric       last_rss = rss;
49768d75effSDimitry Andric     }
49868d75effSDimitry Andric 
499349cc55cSDimitry Andric     MemoryProfiler(now - start);
50068d75effSDimitry Andric 
50168d75effSDimitry Andric     // Flush symbolizer cache if requested.
50268d75effSDimitry Andric     if (flags()->flush_symbolizer_ms > 0) {
50368d75effSDimitry Andric       u64 last = atomic_load(&ctx->last_symbolize_time_ns,
50468d75effSDimitry Andric                              memory_order_relaxed);
50568d75effSDimitry Andric       if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
50668d75effSDimitry Andric         Lock l(&ctx->report_mtx);
50768d75effSDimitry Andric         ScopedErrorReportLock l2;
50868d75effSDimitry Andric         SymbolizeFlush();
50968d75effSDimitry Andric         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
51068d75effSDimitry Andric       }
51168d75effSDimitry Andric     }
51268d75effSDimitry Andric   }
5135ffd83dbSDimitry Andric   return nullptr;
51468d75effSDimitry Andric }
51568d75effSDimitry Andric 
51668d75effSDimitry Andric static void StartBackgroundThread() {
51768d75effSDimitry Andric   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
51868d75effSDimitry Andric }
51968d75effSDimitry Andric 
52068d75effSDimitry Andric #ifndef __mips__
52168d75effSDimitry Andric static void StopBackgroundThread() {
52268d75effSDimitry Andric   atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
52368d75effSDimitry Andric   internal_join_thread(ctx->background_thread);
52468d75effSDimitry Andric   ctx->background_thread = 0;
52568d75effSDimitry Andric }
52668d75effSDimitry Andric #endif
52768d75effSDimitry Andric #endif
52868d75effSDimitry Andric 
52968d75effSDimitry Andric void DontNeedShadowFor(uptr addr, uptr size) {
530349cc55cSDimitry Andric   ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)),
531349cc55cSDimitry Andric                          reinterpret_cast<uptr>(MemToShadow(addr + size)));
53268d75effSDimitry Andric }
53368d75effSDimitry Andric 
53468d75effSDimitry Andric #if !SANITIZER_GO
5354824e7fdSDimitry Andric // We call UnmapShadow before the actual munmap, at that point we don't yet
5364824e7fdSDimitry Andric // know if the provided address/size are sane. We can't call UnmapShadow
5374824e7fdSDimitry Andric // after the actual munmap becuase at that point the memory range can
5384824e7fdSDimitry Andric // already be reused for something else, so we can't rely on the munmap
5394824e7fdSDimitry Andric // return value to understand is the values are sane.
5404824e7fdSDimitry Andric // While calling munmap with insane values (non-canonical address, negative
5414824e7fdSDimitry Andric // size, etc) is an error, the kernel won't crash. We must also try to not
5424824e7fdSDimitry Andric // crash as the failure mode is very confusing (paging fault inside of the
5434824e7fdSDimitry Andric // runtime on some derived shadow address).
5444824e7fdSDimitry Andric static bool IsValidMmapRange(uptr addr, uptr size) {
5454824e7fdSDimitry Andric   if (size == 0)
5464824e7fdSDimitry Andric     return true;
5474824e7fdSDimitry Andric   if (static_cast<sptr>(size) < 0)
5484824e7fdSDimitry Andric     return false;
5494824e7fdSDimitry Andric   if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
5504824e7fdSDimitry Andric     return false;
5514824e7fdSDimitry Andric   // Check that if the start of the region belongs to one of app ranges,
5524824e7fdSDimitry Andric   // end of the region belongs to the same region.
5534824e7fdSDimitry Andric   const uptr ranges[][2] = {
5544824e7fdSDimitry Andric       {LoAppMemBeg(), LoAppMemEnd()},
5554824e7fdSDimitry Andric       {MidAppMemBeg(), MidAppMemEnd()},
5564824e7fdSDimitry Andric       {HiAppMemBeg(), HiAppMemEnd()},
5574824e7fdSDimitry Andric   };
5584824e7fdSDimitry Andric   for (auto range : ranges) {
5594824e7fdSDimitry Andric     if (addr >= range[0] && addr < range[1])
5604824e7fdSDimitry Andric       return addr + size <= range[1];
5614824e7fdSDimitry Andric   }
5624824e7fdSDimitry Andric   return false;
5634824e7fdSDimitry Andric }
5644824e7fdSDimitry Andric 
56568d75effSDimitry Andric void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
5664824e7fdSDimitry Andric   if (size == 0 || !IsValidMmapRange(addr, size))
5674824e7fdSDimitry Andric     return;
56868d75effSDimitry Andric   DontNeedShadowFor(addr, size);
56968d75effSDimitry Andric   ScopedGlobalProcessor sgp;
5700eae32dcSDimitry Andric   SlotLocker locker(thr, true);
5710eae32dcSDimitry Andric   ctx->metamap.ResetRange(thr->proc(), addr, size, true);
57268d75effSDimitry Andric }
57368d75effSDimitry Andric #endif
57468d75effSDimitry Andric 
57568d75effSDimitry Andric void MapShadow(uptr addr, uptr size) {
576*972a253aSDimitry Andric   // Ensure thead registry lock held, so as to synchronize
577*972a253aSDimitry Andric   // with DoReset, which also access the mapped_shadow_* ctxt fields.
578*972a253aSDimitry Andric   ThreadRegistryLock lock0(&ctx->thread_registry);
579*972a253aSDimitry Andric   static bool data_mapped = false;
580*972a253aSDimitry Andric 
581*972a253aSDimitry Andric #if !SANITIZER_GO
58268d75effSDimitry Andric   // Global data is not 64K aligned, but there are no adjacent mappings,
58368d75effSDimitry Andric   // so we can get away with unaligned mapping.
58468d75effSDimitry Andric   // CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
58568d75effSDimitry Andric   const uptr kPageSize = GetPageSizeCached();
58668d75effSDimitry Andric   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
58768d75effSDimitry Andric   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
588*972a253aSDimitry Andric   if (!MmapFixedNoReserve(shadow_begin, shadow_end - shadow_begin, "shadow"))
589*972a253aSDimitry Andric     Die();
590*972a253aSDimitry Andric #else
591*972a253aSDimitry Andric   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), (64 << 10));
592*972a253aSDimitry Andric   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), (64 << 10));
593*972a253aSDimitry Andric   VPrintf(2, "MapShadow for (0x%zx-0x%zx), begin/end: (0x%zx-0x%zx)\n",
594*972a253aSDimitry Andric           addr, addr + size, shadow_begin, shadow_end);
595*972a253aSDimitry Andric 
596*972a253aSDimitry Andric   if (!data_mapped) {
597*972a253aSDimitry Andric     // First call maps data+bss.
598*972a253aSDimitry Andric     if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin, "shadow"))
599*972a253aSDimitry Andric       Die();
600*972a253aSDimitry Andric   } else {
601*972a253aSDimitry Andric     VPrintf(2, "ctx->mapped_shadow_{begin,end} = (0x%zx-0x%zx)\n",
602*972a253aSDimitry Andric             ctx->mapped_shadow_begin, ctx->mapped_shadow_end);
603*972a253aSDimitry Andric     // Second and subsequent calls map heap.
604*972a253aSDimitry Andric     if (shadow_end <= ctx->mapped_shadow_end)
605*972a253aSDimitry Andric       return;
606*972a253aSDimitry Andric     if (ctx->mapped_shadow_begin < shadow_begin)
607*972a253aSDimitry Andric       ctx->mapped_shadow_begin = shadow_begin;
608*972a253aSDimitry Andric     if (shadow_begin < ctx->mapped_shadow_end)
609*972a253aSDimitry Andric       shadow_begin = ctx->mapped_shadow_end;
610*972a253aSDimitry Andric     VPrintf(2, "MapShadow begin/end = (0x%zx-0x%zx)\n",
611*972a253aSDimitry Andric             shadow_begin, shadow_end);
612e8d8bef9SDimitry Andric     if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
613e8d8bef9SDimitry Andric                                  "shadow"))
61468d75effSDimitry Andric       Die();
615*972a253aSDimitry Andric     ctx->mapped_shadow_end = shadow_end;
616*972a253aSDimitry Andric   }
617*972a253aSDimitry Andric #endif
61868d75effSDimitry Andric 
61968d75effSDimitry Andric   // Meta shadow is 2:1, so tread carefully.
62068d75effSDimitry Andric   static uptr mapped_meta_end = 0;
62168d75effSDimitry Andric   uptr meta_begin = (uptr)MemToMeta(addr);
62268d75effSDimitry Andric   uptr meta_end = (uptr)MemToMeta(addr + size);
62368d75effSDimitry Andric   meta_begin = RoundDownTo(meta_begin, 64 << 10);
62468d75effSDimitry Andric   meta_end = RoundUpTo(meta_end, 64 << 10);
62568d75effSDimitry Andric   if (!data_mapped) {
62668d75effSDimitry Andric     // First call maps data+bss.
62768d75effSDimitry Andric     data_mapped = true;
628e8d8bef9SDimitry Andric     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
629e8d8bef9SDimitry Andric                                  "meta shadow"))
63068d75effSDimitry Andric       Die();
63168d75effSDimitry Andric   } else {
632349cc55cSDimitry Andric     // Mapping continuous heap.
63368d75effSDimitry Andric     // Windows wants 64K alignment.
63468d75effSDimitry Andric     meta_begin = RoundDownTo(meta_begin, 64 << 10);
63568d75effSDimitry Andric     meta_end = RoundUpTo(meta_end, 64 << 10);
636*972a253aSDimitry Andric     CHECK_GT(meta_end, mapped_meta_end);
63768d75effSDimitry Andric     if (meta_begin < mapped_meta_end)
63868d75effSDimitry Andric       meta_begin = mapped_meta_end;
639e8d8bef9SDimitry Andric     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
640e8d8bef9SDimitry Andric                                  "meta shadow"))
64168d75effSDimitry Andric       Die();
64268d75effSDimitry Andric     mapped_meta_end = meta_end;
64368d75effSDimitry Andric   }
644349cc55cSDimitry Andric   VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr,
645349cc55cSDimitry Andric           addr + size, meta_begin, meta_end);
64668d75effSDimitry Andric }
64768d75effSDimitry Andric 
64868d75effSDimitry Andric #if !SANITIZER_GO
64968d75effSDimitry Andric static void OnStackUnwind(const SignalContext &sig, const void *,
65068d75effSDimitry Andric                           BufferedStackTrace *stack) {
65168d75effSDimitry Andric   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
65268d75effSDimitry Andric                 common_flags()->fast_unwind_on_fatal);
65368d75effSDimitry Andric }
65468d75effSDimitry Andric 
65568d75effSDimitry Andric static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
65668d75effSDimitry Andric   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
65768d75effSDimitry Andric }
65868d75effSDimitry Andric #endif
65968d75effSDimitry Andric 
660fe6060f1SDimitry Andric void CheckUnwind() {
661fe6060f1SDimitry Andric   // There is high probability that interceptors will check-fail as well,
662fe6060f1SDimitry Andric   // on the other hand there is no sense in processing interceptors
663fe6060f1SDimitry Andric   // since we are going to die soon.
664fe6060f1SDimitry Andric   ScopedIgnoreInterceptors ignore;
665fe6060f1SDimitry Andric #if !SANITIZER_GO
6660eae32dcSDimitry Andric   ThreadState* thr = cur_thread();
6670eae32dcSDimitry Andric   thr->nomalloc = false;
6680eae32dcSDimitry Andric   thr->ignore_sync++;
6690eae32dcSDimitry Andric   thr->ignore_reads_and_writes++;
6700eae32dcSDimitry Andric   atomic_store_relaxed(&thr->in_signal_handler, 0);
671fe6060f1SDimitry Andric #endif
672fe6060f1SDimitry Andric   PrintCurrentStackSlow(StackTrace::GetCurrentPc());
673fe6060f1SDimitry Andric }
674fe6060f1SDimitry Andric 
675349cc55cSDimitry Andric bool is_initialized;
676349cc55cSDimitry Andric 
67768d75effSDimitry Andric void Initialize(ThreadState *thr) {
67868d75effSDimitry Andric   // Thread safe because done before all threads exist.
67968d75effSDimitry Andric   if (is_initialized)
68068d75effSDimitry Andric     return;
68168d75effSDimitry Andric   is_initialized = true;
68268d75effSDimitry Andric   // We are not ready to handle interceptors yet.
68368d75effSDimitry Andric   ScopedIgnoreInterceptors ignore;
68468d75effSDimitry Andric   SanitizerToolName = "ThreadSanitizer";
68568d75effSDimitry Andric   // Install tool-specific callbacks in sanitizer_common.
686fe6060f1SDimitry Andric   SetCheckUnwindCallback(CheckUnwind);
68768d75effSDimitry Andric 
68868d75effSDimitry Andric   ctx = new(ctx_placeholder) Context;
68968d75effSDimitry Andric   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
69068d75effSDimitry Andric   const char *options = GetEnv(env_name);
69168d75effSDimitry Andric   CacheBinaryName();
69268d75effSDimitry Andric   CheckASLR();
69368d75effSDimitry Andric   InitializeFlags(&ctx->flags, options, env_name);
69468d75effSDimitry Andric   AvoidCVE_2016_2143();
69568d75effSDimitry Andric   __sanitizer::InitializePlatformEarly();
69668d75effSDimitry Andric   __tsan::InitializePlatformEarly();
69768d75effSDimitry Andric 
69868d75effSDimitry Andric #if !SANITIZER_GO
69968d75effSDimitry Andric   InitializeAllocator();
70068d75effSDimitry Andric   ReplaceSystemMalloc();
70168d75effSDimitry Andric #endif
70268d75effSDimitry Andric   if (common_flags()->detect_deadlocks)
70368d75effSDimitry Andric     ctx->dd = DDetector::Create(flags());
70468d75effSDimitry Andric   Processor *proc = ProcCreate();
70568d75effSDimitry Andric   ProcWire(proc, thr);
70668d75effSDimitry Andric   InitializeInterceptors();
70768d75effSDimitry Andric   InitializePlatform();
70868d75effSDimitry Andric   InitializeDynamicAnnotations();
70968d75effSDimitry Andric #if !SANITIZER_GO
71068d75effSDimitry Andric   InitializeShadowMemory();
71168d75effSDimitry Andric   InitializeAllocatorLate();
71268d75effSDimitry Andric   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
71368d75effSDimitry Andric #endif
71468d75effSDimitry Andric   // Setup correct file descriptor for error reports.
71568d75effSDimitry Andric   __sanitizer_set_report_path(common_flags()->log_path);
71668d75effSDimitry Andric   InitializeSuppressions();
71768d75effSDimitry Andric #if !SANITIZER_GO
71868d75effSDimitry Andric   InitializeLibIgnore();
71968d75effSDimitry Andric   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
72068d75effSDimitry Andric #endif
72168d75effSDimitry Andric 
7220eae32dcSDimitry Andric   VPrintf(1, "***** Running under ThreadSanitizer v3 (pid %d) *****\n",
72368d75effSDimitry Andric           (int)internal_getpid());
72468d75effSDimitry Andric 
72568d75effSDimitry Andric   // Initialize thread 0.
7260eae32dcSDimitry Andric   Tid tid = ThreadCreate(nullptr, 0, 0, true);
727349cc55cSDimitry Andric   CHECK_EQ(tid, kMainTid);
72868d75effSDimitry Andric   ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
72968d75effSDimitry Andric #if TSAN_CONTAINS_UBSAN
73068d75effSDimitry Andric   __ubsan::InitAsPlugin();
73168d75effSDimitry Andric #endif
73268d75effSDimitry Andric 
73368d75effSDimitry Andric #if !SANITIZER_GO
73468d75effSDimitry Andric   Symbolizer::LateInitialize();
7350eae32dcSDimitry Andric   if (InitializeMemoryProfiler() || flags()->force_background_thread)
7360eae32dcSDimitry Andric     MaybeSpawnBackgroundThread();
73768d75effSDimitry Andric #endif
7380eae32dcSDimitry Andric   ctx->initialized = true;
73968d75effSDimitry Andric 
74068d75effSDimitry Andric   if (flags()->stop_on_start) {
74168d75effSDimitry Andric     Printf("ThreadSanitizer is suspended at startup (pid %d)."
74268d75effSDimitry Andric            " Call __tsan_resume().\n",
74368d75effSDimitry Andric            (int)internal_getpid());
74468d75effSDimitry Andric     while (__tsan_resumed == 0) {}
74568d75effSDimitry Andric   }
74668d75effSDimitry Andric 
74768d75effSDimitry Andric   OnInitialize();
74868d75effSDimitry Andric }
74968d75effSDimitry Andric 
75068d75effSDimitry Andric void MaybeSpawnBackgroundThread() {
75168d75effSDimitry Andric   // On MIPS, TSan initialization is run before
75268d75effSDimitry Andric   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
75368d75effSDimitry Andric   // new threads.
75468d75effSDimitry Andric #if !SANITIZER_GO && !defined(__mips__)
75568d75effSDimitry Andric   static atomic_uint32_t bg_thread = {};
75668d75effSDimitry Andric   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
75768d75effSDimitry Andric       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
75868d75effSDimitry Andric     StartBackgroundThread();
75968d75effSDimitry Andric     SetSandboxingCallback(StopBackgroundThread);
76068d75effSDimitry Andric   }
76168d75effSDimitry Andric #endif
76268d75effSDimitry Andric }
76368d75effSDimitry Andric 
76468d75effSDimitry Andric int Finalize(ThreadState *thr) {
76568d75effSDimitry Andric   bool failed = false;
76668d75effSDimitry Andric 
76781ad6265SDimitry Andric #if !SANITIZER_GO
768e8d8bef9SDimitry Andric   if (common_flags()->print_module_map == 1)
769e8d8bef9SDimitry Andric     DumpProcessMap();
77081ad6265SDimitry Andric #endif
77168d75effSDimitry Andric 
77268d75effSDimitry Andric   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
7730eae32dcSDimitry Andric     internal_usleep(u64(flags()->atexit_sleep_ms) * 1000);
77468d75effSDimitry Andric 
7750eae32dcSDimitry Andric   {
77668d75effSDimitry Andric     // Wait for pending reports.
7770eae32dcSDimitry Andric     ScopedErrorReportLock lock;
7780eae32dcSDimitry Andric   }
77968d75effSDimitry Andric 
78068d75effSDimitry Andric #if !SANITIZER_GO
78168d75effSDimitry Andric   if (Verbosity()) AllocatorPrintStats();
78268d75effSDimitry Andric #endif
78368d75effSDimitry Andric 
78468d75effSDimitry Andric   ThreadFinalize(thr);
78568d75effSDimitry Andric 
78668d75effSDimitry Andric   if (ctx->nreported) {
78768d75effSDimitry Andric     failed = true;
78868d75effSDimitry Andric #if !SANITIZER_GO
78968d75effSDimitry Andric     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
79068d75effSDimitry Andric #else
79168d75effSDimitry Andric     Printf("Found %d data race(s)\n", ctx->nreported);
79268d75effSDimitry Andric #endif
79368d75effSDimitry Andric   }
79468d75effSDimitry Andric 
79568d75effSDimitry Andric   if (common_flags()->print_suppressions)
79668d75effSDimitry Andric     PrintMatchedSuppressions();
79768d75effSDimitry Andric 
79868d75effSDimitry Andric   failed = OnFinalize(failed);
79968d75effSDimitry Andric 
80068d75effSDimitry Andric   return failed ? common_flags()->exitcode : 0;
80168d75effSDimitry Andric }
80268d75effSDimitry Andric 
80368d75effSDimitry Andric #if !SANITIZER_GO
80404eeddc0SDimitry Andric void ForkBefore(ThreadState* thr, uptr pc) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
8050eae32dcSDimitry Andric   GlobalProcessorLock();
8060eae32dcSDimitry Andric   // Detaching from the slot makes OnUserFree skip writing to the shadow.
8070eae32dcSDimitry Andric   // The slot will be locked so any attempts to use it will deadlock anyway.
8080eae32dcSDimitry Andric   SlotDetach(thr);
8090eae32dcSDimitry Andric   for (auto& slot : ctx->slots) slot.mtx.Lock();
810349cc55cSDimitry Andric   ctx->thread_registry.Lock();
8110eae32dcSDimitry Andric   ctx->slot_mtx.Lock();
812fe6060f1SDimitry Andric   ScopedErrorReportLock::Lock();
8134824e7fdSDimitry Andric   AllocatorLock();
814fe6060f1SDimitry Andric   // Suppress all reports in the pthread_atfork callbacks.
815fe6060f1SDimitry Andric   // Reports will deadlock on the report_mtx.
816fe6060f1SDimitry Andric   // We could ignore sync operations as well,
8175ffd83dbSDimitry Andric   // but so far it's unclear if it will do more good or harm.
8185ffd83dbSDimitry Andric   // Unnecessarily ignoring things can lead to false positives later.
819fe6060f1SDimitry Andric   thr->suppress_reports++;
820fe6060f1SDimitry Andric   // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
821fe6060f1SDimitry Andric   // we'll assert in CheckNoLocks() unless we ignore interceptors.
8224824e7fdSDimitry Andric   // On OS X libSystem_atfork_prepare/parent/child callbacks are called
8234824e7fdSDimitry Andric   // after/before our callbacks and they call free.
824fe6060f1SDimitry Andric   thr->ignore_interceptors++;
8254824e7fdSDimitry Andric   // Disables memory write in OnUserAlloc/Free.
8264824e7fdSDimitry Andric   thr->ignore_reads_and_writes++;
8274824e7fdSDimitry Andric 
8284824e7fdSDimitry Andric   __tsan_test_only_on_fork();
82968d75effSDimitry Andric }
83068d75effSDimitry Andric 
83104eeddc0SDimitry Andric static void ForkAfter(ThreadState* thr) SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
832fe6060f1SDimitry Andric   thr->suppress_reports--;  // Enabled in ForkBefore.
833fe6060f1SDimitry Andric   thr->ignore_interceptors--;
8344824e7fdSDimitry Andric   thr->ignore_reads_and_writes--;
8354824e7fdSDimitry Andric   AllocatorUnlock();
836fe6060f1SDimitry Andric   ScopedErrorReportLock::Unlock();
8370eae32dcSDimitry Andric   ctx->slot_mtx.Unlock();
838349cc55cSDimitry Andric   ctx->thread_registry.Unlock();
8390eae32dcSDimitry Andric   for (auto& slot : ctx->slots) slot.mtx.Unlock();
8400eae32dcSDimitry Andric   SlotAttachAndLock(thr);
8410eae32dcSDimitry Andric   SlotUnlock(thr);
8420eae32dcSDimitry Andric   GlobalProcessorUnlock();
84368d75effSDimitry Andric }
84468d75effSDimitry Andric 
8450eae32dcSDimitry Andric void ForkParentAfter(ThreadState* thr, uptr pc) { ForkAfter(thr); }
84668d75effSDimitry Andric 
8470eae32dcSDimitry Andric void ForkChildAfter(ThreadState* thr, uptr pc, bool start_thread) {
8480eae32dcSDimitry Andric   ForkAfter(thr);
8490eae32dcSDimitry Andric   u32 nthread = ctx->thread_registry.OnFork(thr->tid);
8500eae32dcSDimitry Andric   VPrintf(1,
8510eae32dcSDimitry Andric           "ThreadSanitizer: forked new process with pid %d,"
8520eae32dcSDimitry Andric           " parent had %d threads\n",
8530eae32dcSDimitry Andric           (int)internal_getpid(), (int)nthread);
85468d75effSDimitry Andric   if (nthread == 1) {
855349cc55cSDimitry Andric     if (start_thread)
85668d75effSDimitry Andric       StartBackgroundThread();
85768d75effSDimitry Andric   } else {
85868d75effSDimitry Andric     // We've just forked a multi-threaded process. We cannot reasonably function
85968d75effSDimitry Andric     // after that (some mutexes may be locked before fork). So just enable
86068d75effSDimitry Andric     // ignores for everything in the hope that we will exec soon.
86168d75effSDimitry Andric     ctx->after_multithreaded_fork = true;
86268d75effSDimitry Andric     thr->ignore_interceptors++;
8630eae32dcSDimitry Andric     thr->suppress_reports++;
86468d75effSDimitry Andric     ThreadIgnoreBegin(thr, pc);
86568d75effSDimitry Andric     ThreadIgnoreSyncBegin(thr, pc);
86668d75effSDimitry Andric   }
86768d75effSDimitry Andric }
86868d75effSDimitry Andric #endif
86968d75effSDimitry Andric 
87068d75effSDimitry Andric #if SANITIZER_GO
87168d75effSDimitry Andric NOINLINE
87268d75effSDimitry Andric void GrowShadowStack(ThreadState *thr) {
87368d75effSDimitry Andric   const int sz = thr->shadow_stack_end - thr->shadow_stack;
87468d75effSDimitry Andric   const int newsz = 2 * sz;
875349cc55cSDimitry Andric   auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr));
87668d75effSDimitry Andric   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
877349cc55cSDimitry Andric   Free(thr->shadow_stack);
87868d75effSDimitry Andric   thr->shadow_stack = newstack;
87968d75effSDimitry Andric   thr->shadow_stack_pos = newstack + sz;
88068d75effSDimitry Andric   thr->shadow_stack_end = newstack + newsz;
88168d75effSDimitry Andric }
88268d75effSDimitry Andric #endif
88368d75effSDimitry Andric 
884349cc55cSDimitry Andric StackID CurrentStackId(ThreadState *thr, uptr pc) {
8850eae32dcSDimitry Andric #if !SANITIZER_GO
88668d75effSDimitry Andric   if (!thr->is_inited)  // May happen during bootstrap.
887349cc55cSDimitry Andric     return kInvalidStackID;
8880eae32dcSDimitry Andric #endif
88968d75effSDimitry Andric   if (pc != 0) {
89068d75effSDimitry Andric #if !SANITIZER_GO
89168d75effSDimitry Andric     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
89268d75effSDimitry Andric #else
89368d75effSDimitry Andric     if (thr->shadow_stack_pos == thr->shadow_stack_end)
89468d75effSDimitry Andric       GrowShadowStack(thr);
89568d75effSDimitry Andric #endif
89668d75effSDimitry Andric     thr->shadow_stack_pos[0] = pc;
89768d75effSDimitry Andric     thr->shadow_stack_pos++;
89868d75effSDimitry Andric   }
899349cc55cSDimitry Andric   StackID id = StackDepotPut(
90068d75effSDimitry Andric       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
90168d75effSDimitry Andric   if (pc != 0)
90268d75effSDimitry Andric     thr->shadow_stack_pos--;
90368d75effSDimitry Andric   return id;
90468d75effSDimitry Andric }
90568d75effSDimitry Andric 
9060eae32dcSDimitry Andric static bool TraceSkipGap(ThreadState* thr) {
907349cc55cSDimitry Andric   Trace *trace = &thr->tctx->trace;
908349cc55cSDimitry Andric   Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
909349cc55cSDimitry Andric   DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0);
910349cc55cSDimitry Andric   auto *part = trace->parts.Back();
9110eae32dcSDimitry Andric   DPrintf("#%d: TraceSwitchPart enter trace=%p parts=%p-%p pos=%p\n", thr->tid,
9120eae32dcSDimitry Andric           trace, trace->parts.Front(), part, pos);
9130eae32dcSDimitry Andric   if (!part)
9140eae32dcSDimitry Andric     return false;
915349cc55cSDimitry Andric   // We can get here when we still have space in the current trace part.
916349cc55cSDimitry Andric   // The fast-path check in TraceAcquire has false positives in the middle of
917349cc55cSDimitry Andric   // the part. Check if we are indeed at the end of the current part or not,
918349cc55cSDimitry Andric   // and fill any gaps with NopEvent's.
919349cc55cSDimitry Andric   Event* end = &part->events[TracePart::kSize];
920349cc55cSDimitry Andric   DCHECK_GE(pos, &part->events[0]);
921349cc55cSDimitry Andric   DCHECK_LE(pos, end);
922349cc55cSDimitry Andric   if (pos + 1 < end) {
923349cc55cSDimitry Andric     if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) ==
924349cc55cSDimitry Andric         TracePart::kAlignment)
925349cc55cSDimitry Andric       *pos++ = NopEvent;
926349cc55cSDimitry Andric     *pos++ = NopEvent;
927349cc55cSDimitry Andric     DCHECK_LE(pos + 2, end);
928349cc55cSDimitry Andric     atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos));
9290eae32dcSDimitry Andric     return true;
930349cc55cSDimitry Andric   }
931349cc55cSDimitry Andric   // We are indeed at the end.
932349cc55cSDimitry Andric   for (; pos < end; pos++) *pos = NopEvent;
9330eae32dcSDimitry Andric   return false;
934349cc55cSDimitry Andric }
9350eae32dcSDimitry Andric 
9360eae32dcSDimitry Andric NOINLINE
9370eae32dcSDimitry Andric void TraceSwitchPart(ThreadState* thr) {
9380eae32dcSDimitry Andric   if (TraceSkipGap(thr))
9390eae32dcSDimitry Andric     return;
940349cc55cSDimitry Andric #if !SANITIZER_GO
941349cc55cSDimitry Andric   if (ctx->after_multithreaded_fork) {
942349cc55cSDimitry Andric     // We just need to survive till exec.
9430eae32dcSDimitry Andric     TracePart* part = thr->tctx->trace.parts.Back();
9440eae32dcSDimitry Andric     if (part) {
945349cc55cSDimitry Andric       atomic_store_relaxed(&thr->trace_pos,
946349cc55cSDimitry Andric                            reinterpret_cast<uptr>(&part->events[0]));
947349cc55cSDimitry Andric       return;
948349cc55cSDimitry Andric     }
9490eae32dcSDimitry Andric   }
950349cc55cSDimitry Andric #endif
9510eae32dcSDimitry Andric   TraceSwitchPartImpl(thr);
9520eae32dcSDimitry Andric }
9530eae32dcSDimitry Andric 
9540eae32dcSDimitry Andric void TraceSwitchPartImpl(ThreadState* thr) {
9550eae32dcSDimitry Andric   SlotLocker locker(thr, true);
9560eae32dcSDimitry Andric   Trace* trace = &thr->tctx->trace;
9570eae32dcSDimitry Andric   TracePart* part = TracePartAlloc(thr);
958349cc55cSDimitry Andric   part->trace = trace;
959349cc55cSDimitry Andric   thr->trace_prev_pc = 0;
9600eae32dcSDimitry Andric   TracePart* recycle = nullptr;
9610eae32dcSDimitry Andric   // Keep roughly half of parts local to the thread
9620eae32dcSDimitry Andric   // (not queued into the recycle queue).
9630eae32dcSDimitry Andric   uptr local_parts = (Trace::kMinParts + flags()->history_size + 1) / 2;
964349cc55cSDimitry Andric   {
965349cc55cSDimitry Andric     Lock lock(&trace->mtx);
9660eae32dcSDimitry Andric     if (trace->parts.Empty())
9670eae32dcSDimitry Andric       trace->local_head = part;
9680eae32dcSDimitry Andric     if (trace->parts.Size() >= local_parts) {
9690eae32dcSDimitry Andric       recycle = trace->local_head;
9700eae32dcSDimitry Andric       trace->local_head = trace->parts.Next(recycle);
9710eae32dcSDimitry Andric     }
972349cc55cSDimitry Andric     trace->parts.PushBack(part);
973349cc55cSDimitry Andric     atomic_store_relaxed(&thr->trace_pos,
974349cc55cSDimitry Andric                          reinterpret_cast<uptr>(&part->events[0]));
975349cc55cSDimitry Andric   }
976349cc55cSDimitry Andric   // Make this part self-sufficient by restoring the current stack
977349cc55cSDimitry Andric   // and mutex set in the beginning of the trace.
978349cc55cSDimitry Andric   TraceTime(thr);
9790eae32dcSDimitry Andric   {
9800eae32dcSDimitry Andric     // Pathologically large stacks may not fit into the part.
9810eae32dcSDimitry Andric     // In these cases we log only fixed number of top frames.
9820eae32dcSDimitry Andric     const uptr kMaxFrames = 1000;
98381ad6265SDimitry Andric     // Check that kMaxFrames won't consume the whole part.
9840eae32dcSDimitry Andric     static_assert(kMaxFrames < TracePart::kSize / 2, "kMaxFrames is too big");
9850eae32dcSDimitry Andric     uptr* pos = Max(&thr->shadow_stack[0], thr->shadow_stack_pos - kMaxFrames);
9860eae32dcSDimitry Andric     for (; pos < thr->shadow_stack_pos; pos++) {
9870eae32dcSDimitry Andric       if (TryTraceFunc(thr, *pos))
9880eae32dcSDimitry Andric         continue;
9890eae32dcSDimitry Andric       CHECK(TraceSkipGap(thr));
990349cc55cSDimitry Andric       CHECK(TryTraceFunc(thr, *pos));
9910eae32dcSDimitry Andric     }
9920eae32dcSDimitry Andric   }
993349cc55cSDimitry Andric   for (uptr i = 0; i < thr->mset.Size(); i++) {
994349cc55cSDimitry Andric     MutexSet::Desc d = thr->mset.Get(i);
9950eae32dcSDimitry Andric     for (uptr i = 0; i < d.count; i++)
996349cc55cSDimitry Andric       TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0,
997349cc55cSDimitry Andric                      d.addr, d.stack_id);
998349cc55cSDimitry Andric   }
999fcaf7f86SDimitry Andric   // Callers of TraceSwitchPart expect that TraceAcquire will always succeed
1000fcaf7f86SDimitry Andric   // after the call. It's possible that TryTraceFunc/TraceMutexLock above
1001fcaf7f86SDimitry Andric   // filled the trace part exactly up to the TracePart::kAlignment gap
1002fcaf7f86SDimitry Andric   // and the next TraceAcquire won't succeed. Skip the gap to avoid that.
1003fcaf7f86SDimitry Andric   EventFunc *ev;
1004fcaf7f86SDimitry Andric   if (!TraceAcquire(thr, &ev)) {
1005fcaf7f86SDimitry Andric     CHECK(TraceSkipGap(thr));
1006fcaf7f86SDimitry Andric     CHECK(TraceAcquire(thr, &ev));
1007fcaf7f86SDimitry Andric   }
10080eae32dcSDimitry Andric   {
10090eae32dcSDimitry Andric     Lock lock(&ctx->slot_mtx);
10100eae32dcSDimitry Andric     // There is a small chance that the slot may be not queued at this point.
10110eae32dcSDimitry Andric     // This can happen if the slot has kEpochLast epoch and another thread
10120eae32dcSDimitry Andric     // in FindSlotAndLock discovered that it's exhausted and removed it from
10130eae32dcSDimitry Andric     // the slot queue. kEpochLast can happen in 2 cases: (1) if TraceSwitchPart
10140eae32dcSDimitry Andric     // was called with the slot locked and epoch already at kEpochLast,
10150eae32dcSDimitry Andric     // or (2) if we've acquired a new slot in SlotLock in the beginning
10160eae32dcSDimitry Andric     // of the function and the slot was at kEpochLast - 1, so after increment
10170eae32dcSDimitry Andric     // in SlotAttachAndLock it become kEpochLast.
10180eae32dcSDimitry Andric     if (ctx->slot_queue.Queued(thr->slot)) {
10190eae32dcSDimitry Andric       ctx->slot_queue.Remove(thr->slot);
10200eae32dcSDimitry Andric       ctx->slot_queue.PushBack(thr->slot);
1021349cc55cSDimitry Andric     }
10220eae32dcSDimitry Andric     if (recycle)
10230eae32dcSDimitry Andric       ctx->trace_part_recycle.PushBack(recycle);
102468d75effSDimitry Andric   }
10250eae32dcSDimitry Andric   DPrintf("#%d: TraceSwitchPart exit parts=%p-%p pos=0x%zx\n", thr->tid,
10260eae32dcSDimitry Andric           trace->parts.Front(), trace->parts.Back(),
10270eae32dcSDimitry Andric           atomic_load_relaxed(&thr->trace_pos));
102868d75effSDimitry Andric }
102968d75effSDimitry Andric 
1030349cc55cSDimitry Andric void ThreadIgnoreBegin(ThreadState* thr, uptr pc) {
103168d75effSDimitry Andric   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
103268d75effSDimitry Andric   thr->ignore_reads_and_writes++;
103368d75effSDimitry Andric   CHECK_GT(thr->ignore_reads_and_writes, 0);
103468d75effSDimitry Andric   thr->fast_state.SetIgnoreBit();
103568d75effSDimitry Andric #if !SANITIZER_GO
1036349cc55cSDimitry Andric   if (pc && !ctx->after_multithreaded_fork)
103768d75effSDimitry Andric     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
103868d75effSDimitry Andric #endif
103968d75effSDimitry Andric }
104068d75effSDimitry Andric 
1041349cc55cSDimitry Andric void ThreadIgnoreEnd(ThreadState *thr) {
104268d75effSDimitry Andric   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
104368d75effSDimitry Andric   CHECK_GT(thr->ignore_reads_and_writes, 0);
104468d75effSDimitry Andric   thr->ignore_reads_and_writes--;
104568d75effSDimitry Andric   if (thr->ignore_reads_and_writes == 0) {
104668d75effSDimitry Andric     thr->fast_state.ClearIgnoreBit();
104768d75effSDimitry Andric #if !SANITIZER_GO
104868d75effSDimitry Andric     thr->mop_ignore_set.Reset();
104968d75effSDimitry Andric #endif
105068d75effSDimitry Andric   }
105168d75effSDimitry Andric }
105268d75effSDimitry Andric 
105368d75effSDimitry Andric #if !SANITIZER_GO
105468d75effSDimitry Andric extern "C" SANITIZER_INTERFACE_ATTRIBUTE
105568d75effSDimitry Andric uptr __tsan_testonly_shadow_stack_current_size() {
105668d75effSDimitry Andric   ThreadState *thr = cur_thread();
105768d75effSDimitry Andric   return thr->shadow_stack_pos - thr->shadow_stack;
105868d75effSDimitry Andric }
105968d75effSDimitry Andric #endif
106068d75effSDimitry Andric 
1061349cc55cSDimitry Andric void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
106268d75effSDimitry Andric   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
106368d75effSDimitry Andric   thr->ignore_sync++;
106468d75effSDimitry Andric   CHECK_GT(thr->ignore_sync, 0);
106568d75effSDimitry Andric #if !SANITIZER_GO
1066349cc55cSDimitry Andric   if (pc && !ctx->after_multithreaded_fork)
106768d75effSDimitry Andric     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
106868d75effSDimitry Andric #endif
106968d75effSDimitry Andric }
107068d75effSDimitry Andric 
1071349cc55cSDimitry Andric void ThreadIgnoreSyncEnd(ThreadState *thr) {
107268d75effSDimitry Andric   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
107368d75effSDimitry Andric   CHECK_GT(thr->ignore_sync, 0);
107468d75effSDimitry Andric   thr->ignore_sync--;
107568d75effSDimitry Andric #if !SANITIZER_GO
107668d75effSDimitry Andric   if (thr->ignore_sync == 0)
107768d75effSDimitry Andric     thr->sync_ignore_set.Reset();
107868d75effSDimitry Andric #endif
107968d75effSDimitry Andric }
108068d75effSDimitry Andric 
108168d75effSDimitry Andric bool MD5Hash::operator==(const MD5Hash &other) const {
108268d75effSDimitry Andric   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
108368d75effSDimitry Andric }
108468d75effSDimitry Andric 
108568d75effSDimitry Andric #if SANITIZER_DEBUG
108668d75effSDimitry Andric void build_consistency_debug() {}
108768d75effSDimitry Andric #else
108868d75effSDimitry Andric void build_consistency_release() {}
108968d75effSDimitry Andric #endif
109068d75effSDimitry Andric }  // namespace __tsan
109168d75effSDimitry Andric 
1092fe6060f1SDimitry Andric #if SANITIZER_CHECK_DEADLOCKS
1093fe6060f1SDimitry Andric namespace __sanitizer {
1094fe6060f1SDimitry Andric using namespace __tsan;
1095fe6060f1SDimitry Andric MutexMeta mutex_meta[] = {
1096fe6060f1SDimitry Andric     {MutexInvalid, "Invalid", {}},
10970eae32dcSDimitry Andric     {MutexThreadRegistry,
10980eae32dcSDimitry Andric      "ThreadRegistry",
10990eae32dcSDimitry Andric      {MutexTypeSlots, MutexTypeTrace, MutexTypeReport}},
11000eae32dcSDimitry Andric     {MutexTypeReport, "Report", {MutexTypeTrace}},
11010eae32dcSDimitry Andric     {MutexTypeSyncVar, "SyncVar", {MutexTypeReport, MutexTypeTrace}},
1102fe6060f1SDimitry Andric     {MutexTypeAnnotations, "Annotations", {}},
11030eae32dcSDimitry Andric     {MutexTypeAtExit, "AtExit", {}},
1104fe6060f1SDimitry Andric     {MutexTypeFired, "Fired", {MutexLeaf}},
1105fe6060f1SDimitry Andric     {MutexTypeRacy, "Racy", {MutexLeaf}},
11060eae32dcSDimitry Andric     {MutexTypeGlobalProc, "GlobalProc", {MutexTypeSlot, MutexTypeSlots}},
11074824e7fdSDimitry Andric     {MutexTypeInternalAlloc, "InternalAlloc", {MutexLeaf}},
11080eae32dcSDimitry Andric     {MutexTypeTrace, "Trace", {}},
11090eae32dcSDimitry Andric     {MutexTypeSlot,
11100eae32dcSDimitry Andric      "Slot",
11110eae32dcSDimitry Andric      {MutexMulti, MutexTypeTrace, MutexTypeSyncVar, MutexThreadRegistry,
11120eae32dcSDimitry Andric       MutexTypeSlots}},
11130eae32dcSDimitry Andric     {MutexTypeSlots, "Slots", {MutexTypeTrace, MutexTypeReport}},
1114fe6060f1SDimitry Andric     {},
1115fe6060f1SDimitry Andric };
1116fe6060f1SDimitry Andric 
1117fe6060f1SDimitry Andric void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
11180eae32dcSDimitry Andric 
1119fe6060f1SDimitry Andric }  // namespace __sanitizer
1120fe6060f1SDimitry Andric #endif
1121