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