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