tsan_rtl.cpp 34 KB

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