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