tsan_rtl_thread.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //===-- tsan_rtl_thread.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. //===----------------------------------------------------------------------===//
  12. #include "sanitizer_common/sanitizer_placement_new.h"
  13. #include "tsan_rtl.h"
  14. #include "tsan_mman.h"
  15. #include "tsan_platform.h"
  16. #include "tsan_report.h"
  17. #include "tsan_sync.h"
  18. namespace __tsan {
  19. // ThreadContext implementation.
  20. ThreadContext::ThreadContext(Tid tid)
  21. : ThreadContextBase(tid), thr(), sync(), epoch0(), epoch1() {}
  22. #if !SANITIZER_GO
  23. ThreadContext::~ThreadContext() {
  24. }
  25. #endif
  26. void ThreadContext::OnReset() {
  27. CHECK_EQ(sync.size(), 0);
  28. uptr trace_p = GetThreadTrace(tid);
  29. ReleaseMemoryPagesToOS(trace_p, trace_p + TraceSize() * sizeof(Event));
  30. //!!! ReleaseMemoryToOS(GetThreadTraceHeader(tid), sizeof(Trace));
  31. }
  32. #if !SANITIZER_GO
  33. struct ThreadLeak {
  34. ThreadContext *tctx;
  35. int count;
  36. };
  37. static void CollectThreadLeaks(ThreadContextBase *tctx_base, void *arg) {
  38. auto &leaks = *static_cast<Vector<ThreadLeak> *>(arg);
  39. auto *tctx = static_cast<ThreadContext *>(tctx_base);
  40. if (tctx->detached || tctx->status != ThreadStatusFinished)
  41. return;
  42. for (uptr i = 0; i < leaks.Size(); i++) {
  43. if (leaks[i].tctx->creation_stack_id == tctx->creation_stack_id) {
  44. leaks[i].count++;
  45. return;
  46. }
  47. }
  48. leaks.PushBack({tctx, 1});
  49. }
  50. #endif
  51. #if !SANITIZER_GO
  52. static void ReportIgnoresEnabled(ThreadContext *tctx, IgnoreSet *set) {
  53. if (tctx->tid == kMainTid) {
  54. Printf("ThreadSanitizer: main thread finished with ignores enabled\n");
  55. } else {
  56. Printf("ThreadSanitizer: thread T%d %s finished with ignores enabled,"
  57. " created at:\n", tctx->tid, tctx->name);
  58. PrintStack(SymbolizeStackId(tctx->creation_stack_id));
  59. }
  60. Printf(" One of the following ignores was not ended"
  61. " (in order of probability)\n");
  62. for (uptr i = 0; i < set->Size(); i++) {
  63. Printf(" Ignore was enabled at:\n");
  64. PrintStack(SymbolizeStackId(set->At(i)));
  65. }
  66. Die();
  67. }
  68. static void ThreadCheckIgnore(ThreadState *thr) {
  69. if (ctx->after_multithreaded_fork)
  70. return;
  71. if (thr->ignore_reads_and_writes)
  72. ReportIgnoresEnabled(thr->tctx, &thr->mop_ignore_set);
  73. if (thr->ignore_sync)
  74. ReportIgnoresEnabled(thr->tctx, &thr->sync_ignore_set);
  75. }
  76. #else
  77. static void ThreadCheckIgnore(ThreadState *thr) {}
  78. #endif
  79. void ThreadFinalize(ThreadState *thr) {
  80. ThreadCheckIgnore(thr);
  81. #if !SANITIZER_GO
  82. if (!ShouldReport(thr, ReportTypeThreadLeak))
  83. return;
  84. ThreadRegistryLock l(&ctx->thread_registry);
  85. Vector<ThreadLeak> leaks;
  86. ctx->thread_registry.RunCallbackForEachThreadLocked(CollectThreadLeaks,
  87. &leaks);
  88. for (uptr i = 0; i < leaks.Size(); i++) {
  89. ScopedReport rep(ReportTypeThreadLeak);
  90. rep.AddThread(leaks[i].tctx, true);
  91. rep.SetCount(leaks[i].count);
  92. OutputReport(thr, rep);
  93. }
  94. #endif
  95. }
  96. int ThreadCount(ThreadState *thr) {
  97. uptr result;
  98. ctx->thread_registry.GetNumberOfThreads(0, 0, &result);
  99. return (int)result;
  100. }
  101. struct OnCreatedArgs {
  102. ThreadState *thr;
  103. uptr pc;
  104. };
  105. Tid ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
  106. OnCreatedArgs args = { thr, pc };
  107. u32 parent_tid = thr ? thr->tid : kInvalidTid; // No parent for GCD workers.
  108. Tid tid = ctx->thread_registry.CreateThread(uid, detached, parent_tid, &args);
  109. DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", parent_tid, tid, uid);
  110. return tid;
  111. }
  112. void ThreadContext::OnCreated(void *arg) {
  113. thr = 0;
  114. if (tid == kMainTid)
  115. return;
  116. OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
  117. if (!args->thr) // GCD workers don't have a parent thread.
  118. return;
  119. args->thr->fast_state.IncrementEpoch();
  120. // Can't increment epoch w/o writing to the trace as well.
  121. TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);
  122. ReleaseImpl(args->thr, 0, &sync);
  123. creation_stack_id = CurrentStackId(args->thr, args->pc);
  124. }
  125. extern "C" void __tsan_stack_initialization() {}
  126. struct OnStartedArgs {
  127. ThreadState *thr;
  128. uptr stk_addr;
  129. uptr stk_size;
  130. uptr tls_addr;
  131. uptr tls_size;
  132. };
  133. void ThreadStart(ThreadState *thr, Tid tid, tid_t os_id,
  134. ThreadType thread_type) {
  135. uptr stk_addr = 0;
  136. uptr stk_size = 0;
  137. uptr tls_addr = 0;
  138. uptr tls_size = 0;
  139. #if !SANITIZER_GO
  140. if (thread_type != ThreadType::Fiber)
  141. GetThreadStackAndTls(tid == kMainTid, &stk_addr, &stk_size, &tls_addr,
  142. &tls_size);
  143. #endif
  144. ThreadRegistry *tr = &ctx->thread_registry;
  145. OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size };
  146. tr->StartThread(tid, os_id, thread_type, &args);
  147. while (!thr->tctx->trace.parts.Empty()) thr->tctx->trace.parts.PopBack();
  148. #if !SANITIZER_GO
  149. if (ctx->after_multithreaded_fork) {
  150. thr->ignore_interceptors++;
  151. ThreadIgnoreBegin(thr, 0);
  152. ThreadIgnoreSyncBegin(thr, 0);
  153. }
  154. #endif
  155. #if !SANITIZER_GO
  156. // Don't imitate stack/TLS writes for the main thread,
  157. // because its initialization is synchronized with all
  158. // subsequent threads anyway.
  159. if (tid != kMainTid) {
  160. if (stk_addr && stk_size) {
  161. const uptr pc = StackTrace::GetNextInstructionPc(
  162. reinterpret_cast<uptr>(__tsan_stack_initialization));
  163. MemoryRangeImitateWrite(thr, pc, stk_addr, stk_size);
  164. }
  165. if (tls_addr && tls_size)
  166. ImitateTlsWrite(thr, tls_addr, tls_size);
  167. }
  168. #endif
  169. }
  170. void ThreadContext::OnStarted(void *arg) {
  171. OnStartedArgs *args = static_cast<OnStartedArgs *>(arg);
  172. thr = args->thr;
  173. // RoundUp so that one trace part does not contain events
  174. // from different threads.
  175. epoch0 = RoundUp(epoch1 + 1, kTracePartSize);
  176. epoch1 = (u64)-1;
  177. new (thr)
  178. ThreadState(ctx, tid, unique_id, epoch0, reuse_count, args->stk_addr,
  179. args->stk_size, args->tls_addr, args->tls_size);
  180. if (common_flags()->detect_deadlocks)
  181. thr->dd_lt = ctx->dd->CreateLogicalThread(unique_id);
  182. thr->fast_state.SetHistorySize(flags()->history_size);
  183. // Commit switch to the new part of the trace.
  184. // TraceAddEvent will reset stack0/mset0 in the new part for us.
  185. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);
  186. thr->fast_synch_epoch = epoch0;
  187. AcquireImpl(thr, 0, &sync);
  188. sync.Reset(&thr->proc()->clock_cache);
  189. thr->tctx = this;
  190. thr->is_inited = true;
  191. DPrintf(
  192. "#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
  193. "tls_addr=%zx tls_size=%zx\n",
  194. tid, (uptr)epoch0, args->stk_addr, args->stk_size, args->tls_addr,
  195. args->tls_size);
  196. }
  197. void ThreadFinish(ThreadState *thr) {
  198. ThreadCheckIgnore(thr);
  199. if (thr->stk_addr && thr->stk_size)
  200. DontNeedShadowFor(thr->stk_addr, thr->stk_size);
  201. if (thr->tls_addr && thr->tls_size)
  202. DontNeedShadowFor(thr->tls_addr, thr->tls_size);
  203. thr->is_dead = true;
  204. ctx->thread_registry.FinishThread(thr->tid);
  205. }
  206. void ThreadContext::OnFinished() {
  207. #if SANITIZER_GO
  208. Free(thr->shadow_stack);
  209. thr->shadow_stack_pos = nullptr;
  210. thr->shadow_stack_end = nullptr;
  211. #endif
  212. if (!detached) {
  213. thr->fast_state.IncrementEpoch();
  214. // Can't increment epoch w/o writing to the trace as well.
  215. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);
  216. ReleaseImpl(thr, 0, &sync);
  217. }
  218. epoch1 = thr->fast_state.epoch();
  219. if (common_flags()->detect_deadlocks)
  220. ctx->dd->DestroyLogicalThread(thr->dd_lt);
  221. thr->clock.ResetCached(&thr->proc()->clock_cache);
  222. #if !SANITIZER_GO
  223. thr->last_sleep_clock.ResetCached(&thr->proc()->clock_cache);
  224. #endif
  225. #if !SANITIZER_GO
  226. PlatformCleanUpThreadState(thr);
  227. #endif
  228. thr->~ThreadState();
  229. thr = 0;
  230. }
  231. struct ConsumeThreadContext {
  232. uptr uid;
  233. ThreadContextBase *tctx;
  234. };
  235. static bool ConsumeThreadByUid(ThreadContextBase *tctx, void *arg) {
  236. ConsumeThreadContext *findCtx = (ConsumeThreadContext *)arg;
  237. if (tctx->user_id == findCtx->uid && tctx->status != ThreadStatusInvalid) {
  238. if (findCtx->tctx) {
  239. // Ensure that user_id is unique. If it's not the case we are screwed.
  240. // Something went wrong before, but now there is no way to recover.
  241. // Returning a wrong thread is not an option, it may lead to very hard
  242. // to debug false positives (e.g. if we join a wrong thread).
  243. Report("ThreadSanitizer: dup thread with used id 0x%zx\n", findCtx->uid);
  244. Die();
  245. }
  246. findCtx->tctx = tctx;
  247. tctx->user_id = 0;
  248. }
  249. return false;
  250. }
  251. Tid ThreadConsumeTid(ThreadState *thr, uptr pc, uptr uid) {
  252. ConsumeThreadContext findCtx = {uid, nullptr};
  253. ctx->thread_registry.FindThread(ConsumeThreadByUid, &findCtx);
  254. Tid tid = findCtx.tctx ? findCtx.tctx->tid : kInvalidTid;
  255. DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, tid);
  256. return tid;
  257. }
  258. void ThreadJoin(ThreadState *thr, uptr pc, Tid tid) {
  259. CHECK_GT(tid, 0);
  260. CHECK_LT(tid, kMaxTid);
  261. DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid);
  262. ctx->thread_registry.JoinThread(tid, thr);
  263. }
  264. void ThreadContext::OnJoined(void *arg) {
  265. ThreadState *caller_thr = static_cast<ThreadState *>(arg);
  266. AcquireImpl(caller_thr, 0, &sync);
  267. sync.Reset(&caller_thr->proc()->clock_cache);
  268. }
  269. void ThreadContext::OnDead() { CHECK_EQ(sync.size(), 0); }
  270. void ThreadDetach(ThreadState *thr, uptr pc, Tid tid) {
  271. CHECK_GT(tid, 0);
  272. CHECK_LT(tid, kMaxTid);
  273. ctx->thread_registry.DetachThread(tid, thr);
  274. }
  275. void ThreadContext::OnDetached(void *arg) {
  276. ThreadState *thr1 = static_cast<ThreadState *>(arg);
  277. sync.Reset(&thr1->proc()->clock_cache);
  278. }
  279. void ThreadNotJoined(ThreadState *thr, uptr pc, Tid tid, uptr uid) {
  280. CHECK_GT(tid, 0);
  281. CHECK_LT(tid, kMaxTid);
  282. ctx->thread_registry.SetThreadUserId(tid, uid);
  283. }
  284. void ThreadSetName(ThreadState *thr, const char *name) {
  285. ctx->thread_registry.SetThreadName(thr->tid, name);
  286. }
  287. #if !SANITIZER_GO
  288. void FiberSwitchImpl(ThreadState *from, ThreadState *to) {
  289. Processor *proc = from->proc();
  290. ProcUnwire(proc, from);
  291. ProcWire(proc, to);
  292. set_cur_thread(to);
  293. }
  294. ThreadState *FiberCreate(ThreadState *thr, uptr pc, unsigned flags) {
  295. void *mem = Alloc(sizeof(ThreadState));
  296. ThreadState *fiber = static_cast<ThreadState *>(mem);
  297. internal_memset(fiber, 0, sizeof(*fiber));
  298. Tid tid = ThreadCreate(thr, pc, 0, true);
  299. FiberSwitchImpl(thr, fiber);
  300. ThreadStart(fiber, tid, 0, ThreadType::Fiber);
  301. FiberSwitchImpl(fiber, thr);
  302. return fiber;
  303. }
  304. void FiberDestroy(ThreadState *thr, uptr pc, ThreadState *fiber) {
  305. FiberSwitchImpl(thr, fiber);
  306. ThreadFinish(fiber);
  307. FiberSwitchImpl(fiber, thr);
  308. Free(fiber);
  309. }
  310. void FiberSwitch(ThreadState *thr, uptr pc,
  311. ThreadState *fiber, unsigned flags) {
  312. if (!(flags & FiberSwitchFlagNoSync))
  313. Release(thr, pc, (uptr)fiber);
  314. FiberSwitchImpl(thr, fiber);
  315. if (!(flags & FiberSwitchFlagNoSync))
  316. Acquire(fiber, pc, (uptr)fiber);
  317. }
  318. #endif
  319. } // namespace __tsan