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 13 #include "sanitizer_common/sanitizer_placement_new.h" 14 #include "tsan_rtl.h" 15 #include "tsan_mman.h" 16 #include "tsan_platform.h" 17 #include "tsan_report.h" 18 #include "tsan_sync.h" 19 20 namespace __tsan { 21 22 // ThreadContext implementation. 23 24 ThreadContext::ThreadContext(int tid) 25 : ThreadContextBase(tid) 26 , thr() 27 , sync() 28 , epoch0() 29 , epoch1() { 30 } 31 32 #if !SANITIZER_GO 33 ThreadContext::~ThreadContext() { 34 } 35 #endif 36 37 void ThreadContext::OnDead() { 38 CHECK_EQ(sync.size(), 0); 39 } 40 41 void ThreadContext::OnJoined(void *arg) { 42 ThreadState *caller_thr = static_cast<ThreadState *>(arg); 43 AcquireImpl(caller_thr, 0, &sync); 44 sync.Reset(&caller_thr->proc()->clock_cache); 45 } 46 47 struct OnCreatedArgs { 48 ThreadState *thr; 49 uptr pc; 50 }; 51 52 void ThreadContext::OnCreated(void *arg) { 53 thr = 0; 54 if (tid == kMainTid) 55 return; 56 OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg); 57 if (!args->thr) // GCD workers don't have a parent thread. 58 return; 59 args->thr->fast_state.IncrementEpoch(); 60 // Can't increment epoch w/o writing to the trace as well. 61 TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0); 62 ReleaseImpl(args->thr, 0, &sync); 63 creation_stack_id = CurrentStackId(args->thr, args->pc); 64 } 65 66 void ThreadContext::OnReset() { 67 CHECK_EQ(sync.size(), 0); 68 uptr trace_p = GetThreadTrace(tid); 69 ReleaseMemoryPagesToOS(trace_p, trace_p + TraceSize() * sizeof(Event)); 70 //!!! ReleaseMemoryToOS(GetThreadTraceHeader(tid), sizeof(Trace)); 71 } 72 73 void ThreadContext::OnDetached(void *arg) { 74 ThreadState *thr1 = static_cast<ThreadState*>(arg); 75 sync.Reset(&thr1->proc()->clock_cache); 76 } 77 78 struct OnStartedArgs { 79 ThreadState *thr; 80 uptr stk_addr; 81 uptr stk_size; 82 uptr tls_addr; 83 uptr tls_size; 84 }; 85 86 void ThreadContext::OnStarted(void *arg) { 87 OnStartedArgs *args = static_cast<OnStartedArgs*>(arg); 88 thr = args->thr; 89 // RoundUp so that one trace part does not contain events 90 // from different threads. 91 epoch0 = RoundUp(epoch1 + 1, kTracePartSize); 92 epoch1 = (u64)-1; 93 new(thr) ThreadState(ctx, tid, unique_id, epoch0, reuse_count, 94 args->stk_addr, args->stk_size, args->tls_addr, args->tls_size); 95 #if !SANITIZER_GO 96 thr->shadow_stack = &ThreadTrace(thr->tid)->shadow_stack[0]; 97 thr->shadow_stack_pos = thr->shadow_stack; 98 thr->shadow_stack_end = thr->shadow_stack + kShadowStackSize; 99 #else 100 // Setup dynamic shadow stack. 101 const int kInitStackSize = 8; 102 thr->shadow_stack = (uptr *)internal_alloc(kInitStackSize * sizeof(uptr)); 103 thr->shadow_stack_pos = thr->shadow_stack; 104 thr->shadow_stack_end = thr->shadow_stack + kInitStackSize; 105 #endif 106 if (common_flags()->detect_deadlocks) 107 thr->dd_lt = ctx->dd->CreateLogicalThread(unique_id); 108 thr->fast_state.SetHistorySize(flags()->history_size); 109 // Commit switch to the new part of the trace. 110 // TraceAddEvent will reset stack0/mset0 in the new part for us. 111 TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); 112 113 thr->fast_synch_epoch = epoch0; 114 AcquireImpl(thr, 0, &sync); 115 sync.Reset(&thr->proc()->clock_cache); 116 thr->is_inited = true; 117 DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx " 118 "tls_addr=%zx tls_size=%zx\n", 119 tid, (uptr)epoch0, args->stk_addr, args->stk_size, 120 args->tls_addr, args->tls_size); 121 } 122 123 void ThreadContext::OnFinished() { 124 #if SANITIZER_GO 125 internal_free(thr->shadow_stack); 126 thr->shadow_stack = nullptr; 127 thr->shadow_stack_pos = nullptr; 128 thr->shadow_stack_end = nullptr; 129 #endif 130 if (!detached) { 131 thr->fast_state.IncrementEpoch(); 132 // Can't increment epoch w/o writing to the trace as well. 133 TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); 134 ReleaseImpl(thr, 0, &sync); 135 } 136 epoch1 = thr->fast_state.epoch(); 137 138 if (common_flags()->detect_deadlocks) 139 ctx->dd->DestroyLogicalThread(thr->dd_lt); 140 thr->clock.ResetCached(&thr->proc()->clock_cache); 141 #if !SANITIZER_GO 142 thr->last_sleep_clock.ResetCached(&thr->proc()->clock_cache); 143 #endif 144 #if !SANITIZER_GO 145 PlatformCleanUpThreadState(thr); 146 #endif 147 thr->~ThreadState(); 148 thr = 0; 149 } 150 151 #if !SANITIZER_GO 152 struct ThreadLeak { 153 ThreadContext *tctx; 154 int count; 155 }; 156 157 static void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *arg) { 158 Vector<ThreadLeak> &leaks = *(Vector<ThreadLeak>*)arg; 159 ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base); 160 if (tctx->detached || tctx->status != ThreadStatusFinished) 161 return; 162 for (uptr i = 0; i < leaks.Size(); i++) { 163 if (leaks[i].tctx->creation_stack_id == tctx->creation_stack_id) { 164 leaks[i].count++; 165 return; 166 } 167 } 168 ThreadLeak leak = {tctx, 1}; 169 leaks.PushBack(leak); 170 } 171 #endif 172 173 #if !SANITIZER_GO 174 static void ReportIgnoresEnabled(ThreadContext *tctx, IgnoreSet *set) { 175 if (tctx->tid == kMainTid) { 176 Printf("ThreadSanitizer: main thread finished with ignores enabled\n"); 177 } else { 178 Printf("ThreadSanitizer: thread T%d %s finished with ignores enabled," 179 " created at:\n", tctx->tid, tctx->name); 180 PrintStack(SymbolizeStackId(tctx->creation_stack_id)); 181 } 182 Printf(" One of the following ignores was not ended" 183 " (in order of probability)\n"); 184 for (uptr i = 0; i < set->Size(); i++) { 185 Printf(" Ignore was enabled at:\n"); 186 PrintStack(SymbolizeStackId(set->At(i))); 187 } 188 Die(); 189 } 190 191 static void ThreadCheckIgnore(ThreadState *thr) { 192 if (ctx->after_multithreaded_fork) 193 return; 194 if (thr->ignore_reads_and_writes) 195 ReportIgnoresEnabled(thr->tctx, &thr->mop_ignore_set); 196 if (thr->ignore_sync) 197 ReportIgnoresEnabled(thr->tctx, &thr->sync_ignore_set); 198 } 199 #else 200 static void ThreadCheckIgnore(ThreadState *thr) {} 201 #endif 202 203 void ThreadFinalize(ThreadState *thr) { 204 ThreadCheckIgnore(thr); 205 #if !SANITIZER_GO 206 if (!ShouldReport(thr, ReportTypeThreadLeak)) 207 return; 208 ThreadRegistryLock l(&ctx->thread_registry); 209 Vector<ThreadLeak> leaks; 210 ctx->thread_registry.RunCallbackForEachThreadLocked(MaybeReportThreadLeak, 211 &leaks); 212 for (uptr i = 0; i < leaks.Size(); i++) { 213 ScopedReport rep(ReportTypeThreadLeak); 214 rep.AddThread(leaks[i].tctx, true); 215 rep.SetCount(leaks[i].count); 216 OutputReport(thr, rep); 217 } 218 #endif 219 } 220 221 int ThreadCount(ThreadState *thr) { 222 uptr result; 223 ctx->thread_registry.GetNumberOfThreads(0, 0, &result); 224 return (int)result; 225 } 226 227 int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) { 228 OnCreatedArgs args = { thr, pc }; 229 u32 parent_tid = thr ? thr->tid : kInvalidTid; // No parent for GCD workers. 230 int tid = ctx->thread_registry.CreateThread(uid, detached, parent_tid, &args); 231 DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", parent_tid, tid, uid); 232 return tid; 233 } 234 235 void ThreadStart(ThreadState *thr, int tid, tid_t os_id, 236 ThreadType thread_type) { 237 uptr stk_addr = 0; 238 uptr stk_size = 0; 239 uptr tls_addr = 0; 240 uptr tls_size = 0; 241 #if !SANITIZER_GO 242 if (thread_type != ThreadType::Fiber) 243 GetThreadStackAndTls(tid == kMainTid, &stk_addr, &stk_size, &tls_addr, 244 &tls_size); 245 246 if (tid != kMainTid) { 247 if (stk_addr && stk_size) 248 MemoryRangeImitateWrite(thr, /*pc=*/ 1, stk_addr, stk_size); 249 250 if (tls_addr && tls_size) ImitateTlsWrite(thr, tls_addr, tls_size); 251 } 252 #endif 253 254 ThreadRegistry *tr = &ctx->thread_registry; 255 OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size }; 256 tr->StartThread(tid, os_id, thread_type, &args); 257 258 tr->Lock(); 259 thr->tctx = (ThreadContext*)tr->GetThreadLocked(tid); 260 tr->Unlock(); 261 262 #if !SANITIZER_GO 263 if (ctx->after_multithreaded_fork) { 264 thr->ignore_interceptors++; 265 ThreadIgnoreBegin(thr, 0); 266 ThreadIgnoreSyncBegin(thr, 0); 267 } 268 #endif 269 } 270 271 void ThreadFinish(ThreadState *thr) { 272 ThreadCheckIgnore(thr); 273 if (thr->stk_addr && thr->stk_size) 274 DontNeedShadowFor(thr->stk_addr, thr->stk_size); 275 if (thr->tls_addr && thr->tls_size) 276 DontNeedShadowFor(thr->tls_addr, thr->tls_size); 277 thr->is_dead = true; 278 ctx->thread_registry.FinishThread(thr->tid); 279 } 280 281 struct ConsumeThreadContext { 282 uptr uid; 283 ThreadContextBase *tctx; 284 }; 285 286 static bool ConsumeThreadByUid(ThreadContextBase *tctx, void *arg) { 287 ConsumeThreadContext *findCtx = (ConsumeThreadContext *)arg; 288 if (tctx->user_id == findCtx->uid && tctx->status != ThreadStatusInvalid) { 289 if (findCtx->tctx) { 290 // Ensure that user_id is unique. If it's not the case we are screwed. 291 // Something went wrong before, but now there is no way to recover. 292 // Returning a wrong thread is not an option, it may lead to very hard 293 // to debug false positives (e.g. if we join a wrong thread). 294 Report("ThreadSanitizer: dup thread with used id 0x%zx\n", findCtx->uid); 295 Die(); 296 } 297 findCtx->tctx = tctx; 298 tctx->user_id = 0; 299 } 300 return false; 301 } 302 303 int ThreadConsumeTid(ThreadState *thr, uptr pc, uptr uid) { 304 ConsumeThreadContext findCtx = {uid, nullptr}; 305 ctx->thread_registry.FindThread(ConsumeThreadByUid, &findCtx); 306 int tid = findCtx.tctx ? findCtx.tctx->tid : kInvalidTid; 307 DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, tid); 308 return tid; 309 } 310 311 void ThreadJoin(ThreadState *thr, uptr pc, int tid) { 312 CHECK_GT(tid, 0); 313 CHECK_LT(tid, kMaxTid); 314 DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid); 315 ctx->thread_registry.JoinThread(tid, thr); 316 } 317 318 void ThreadDetach(ThreadState *thr, uptr pc, int tid) { 319 CHECK_GT(tid, 0); 320 CHECK_LT(tid, kMaxTid); 321 ctx->thread_registry.DetachThread(tid, thr); 322 } 323 324 void ThreadNotJoined(ThreadState *thr, uptr pc, int tid, uptr uid) { 325 CHECK_GT(tid, 0); 326 CHECK_LT(tid, kMaxTid); 327 ctx->thread_registry.SetThreadUserId(tid, uid); 328 } 329 330 void ThreadSetName(ThreadState *thr, const char *name) { 331 ctx->thread_registry.SetThreadName(thr->tid, name); 332 } 333 334 void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, 335 uptr size, bool is_write) { 336 if (size == 0) 337 return; 338 339 u64 *shadow_mem = (u64*)MemToShadow(addr); 340 DPrintf2("#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\n", 341 thr->tid, (void*)pc, (void*)addr, 342 (int)size, is_write); 343 344 #if SANITIZER_DEBUG 345 if (!IsAppMem(addr)) { 346 Printf("Access to non app mem %zx\n", addr); 347 DCHECK(IsAppMem(addr)); 348 } 349 if (!IsAppMem(addr + size - 1)) { 350 Printf("Access to non app mem %zx\n", addr + size - 1); 351 DCHECK(IsAppMem(addr + size - 1)); 352 } 353 if (!IsShadowMem((uptr)shadow_mem)) { 354 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr); 355 DCHECK(IsShadowMem((uptr)shadow_mem)); 356 } 357 if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))) { 358 Printf("Bad shadow addr %p (%zx)\n", 359 shadow_mem + size * kShadowCnt / 8 - 1, addr + size - 1); 360 DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))); 361 } 362 #endif 363 364 if (*shadow_mem == kShadowRodata) { 365 DCHECK(!is_write); 366 // Access to .rodata section, no races here. 367 // Measurements show that it can be 10-20% of all memory accesses. 368 return; 369 } 370 371 FastState fast_state = thr->fast_state; 372 if (fast_state.GetIgnoreBit()) 373 return; 374 375 fast_state.IncrementEpoch(); 376 thr->fast_state = fast_state; 377 TraceAddEvent(thr, fast_state, EventTypeMop, pc); 378 379 bool unaligned = (addr % kShadowCell) != 0; 380 381 // Handle unaligned beginning, if any. 382 for (; addr % kShadowCell && size; addr++, size--) { 383 int const kAccessSizeLog = 0; 384 Shadow cur(fast_state); 385 cur.SetWrite(is_write); 386 cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog); 387 MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false, 388 shadow_mem, cur); 389 } 390 if (unaligned) 391 shadow_mem += kShadowCnt; 392 // Handle middle part, if any. 393 for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) { 394 int const kAccessSizeLog = 3; 395 Shadow cur(fast_state); 396 cur.SetWrite(is_write); 397 cur.SetAddr0AndSizeLog(0, kAccessSizeLog); 398 MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false, 399 shadow_mem, cur); 400 shadow_mem += kShadowCnt; 401 } 402 // Handle ending, if any. 403 for (; size; addr++, size--) { 404 int const kAccessSizeLog = 0; 405 Shadow cur(fast_state); 406 cur.SetWrite(is_write); 407 cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog); 408 MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false, 409 shadow_mem, cur); 410 } 411 } 412 413 #if !SANITIZER_GO 414 void FiberSwitchImpl(ThreadState *from, ThreadState *to) { 415 Processor *proc = from->proc(); 416 ProcUnwire(proc, from); 417 ProcWire(proc, to); 418 set_cur_thread(to); 419 } 420 421 ThreadState *FiberCreate(ThreadState *thr, uptr pc, unsigned flags) { 422 void *mem = internal_alloc(sizeof(ThreadState)); 423 ThreadState *fiber = static_cast<ThreadState *>(mem); 424 internal_memset(fiber, 0, sizeof(*fiber)); 425 int tid = ThreadCreate(thr, pc, 0, true); 426 FiberSwitchImpl(thr, fiber); 427 ThreadStart(fiber, tid, 0, ThreadType::Fiber); 428 FiberSwitchImpl(fiber, thr); 429 return fiber; 430 } 431 432 void FiberDestroy(ThreadState *thr, uptr pc, ThreadState *fiber) { 433 FiberSwitchImpl(thr, fiber); 434 ThreadFinish(fiber); 435 FiberSwitchImpl(fiber, thr); 436 internal_free(fiber); 437 } 438 439 void FiberSwitch(ThreadState *thr, uptr pc, 440 ThreadState *fiber, unsigned flags) { 441 if (!(flags & FiberSwitchFlagNoSync)) 442 Release(thr, pc, (uptr)fiber); 443 FiberSwitchImpl(thr, fiber); 444 if (!(flags & FiberSwitchFlagNoSync)) 445 Acquire(fiber, pc, (uptr)fiber); 446 } 447 #endif 448 449 } // namespace __tsan 450