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