tsan_rtl.cpp 36 KB

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