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 "sanitizer_common/sanitizer_atomic.h"
15 #include "sanitizer_common/sanitizer_common.h"
16 #include "sanitizer_common/sanitizer_file.h"
17 #include "sanitizer_common/sanitizer_libc.h"
18 #include "sanitizer_common/sanitizer_stackdepot.h"
19 #include "sanitizer_common/sanitizer_placement_new.h"
20 #include "sanitizer_common/sanitizer_symbolizer.h"
21 #include "tsan_defs.h"
22 #include "tsan_platform.h"
23 #include "tsan_rtl.h"
24 #include "tsan_mman.h"
25 #include "tsan_suppressions.h"
26 #include "tsan_symbolize.h"
27 #include "ubsan/ubsan_init.h"
28 
29 #ifdef __SSE3__
30 // <emmintrin.h> transitively includes <stdlib.h>,
31 // and it's prohibited to include std headers into tsan runtime.
32 // So we do this dirty trick.
33 #define _MM_MALLOC_H_INCLUDED
34 #define __MM_MALLOC_H
35 #include <emmintrin.h>
36 typedef __m128i m128;
37 #endif
38 
39 volatile int __tsan_resumed = 0;
40 
41 extern "C" void __tsan_resume() {
42   __tsan_resumed = 1;
43 }
44 
45 namespace __tsan {
46 
47 #if !SANITIZER_GO && !SANITIZER_MAC
48 __attribute__((tls_model("initial-exec")))
49 THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
50 #endif
51 static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
52 Context *ctx;
53 
54 // Can be overriden by a front-end.
55 #ifdef TSAN_EXTERNAL_HOOKS
56 bool OnFinalize(bool failed);
57 void OnInitialize();
58 #else
59 SANITIZER_WEAK_CXX_DEFAULT_IMPL
60 bool OnFinalize(bool failed) {
61   return failed;
62 }
63 SANITIZER_WEAK_CXX_DEFAULT_IMPL
64 void OnInitialize() {}
65 #endif
66 
67 static char thread_registry_placeholder[sizeof(ThreadRegistry)];
68 
69 static ThreadContextBase *CreateThreadContext(u32 tid) {
70   // Map thread trace when context is created.
71   char name[50];
72   internal_snprintf(name, sizeof(name), "trace %u", tid);
73   MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
74   const uptr hdr = GetThreadTraceHeader(tid);
75   internal_snprintf(name, sizeof(name), "trace header %u", tid);
76   MapThreadTrace(hdr, sizeof(Trace), name);
77   new((void*)hdr) Trace();
78   // We are going to use only a small part of the trace with the default
79   // value of history_size. However, the constructor writes to the whole trace.
80   // Unmap the unused part.
81   uptr hdr_end = hdr + sizeof(Trace);
82   hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
83   hdr_end = RoundUp(hdr_end, GetPageSizeCached());
84   if (hdr_end < hdr + sizeof(Trace))
85     UnmapOrDie((void*)hdr_end, hdr + sizeof(Trace) - hdr_end);
86   void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
87   return new(mem) ThreadContext(tid);
88 }
89 
90 #if !SANITIZER_GO
91 static const u32 kThreadQuarantineSize = 16;
92 #else
93 static const u32 kThreadQuarantineSize = 64;
94 #endif
95 
96 Context::Context()
97   : initialized()
98   , report_mtx(MutexTypeReport, StatMtxReport)
99   , nreported()
100   , nmissed_expected()
101   , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
102       CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
103   , racy_mtx(MutexTypeRacy, StatMtxRacy)
104   , racy_stacks()
105   , racy_addresses()
106   , fired_suppressions_mtx(MutexTypeFired, StatMtxFired)
107   , clock_alloc("clock allocator") {
108   fired_suppressions.reserve(8);
109 }
110 
111 // The objects are allocated in TLS, so one may rely on zero-initialization.
112 ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
113                          unsigned reuse_count,
114                          uptr stk_addr, uptr stk_size,
115                          uptr tls_addr, uptr tls_size)
116   : fast_state(tid, epoch)
117   // Do not touch these, rely on zero initialization,
118   // they may be accessed before the ctor.
119   // , ignore_reads_and_writes()
120   // , ignore_interceptors()
121   , clock(tid, reuse_count)
122 #if !SANITIZER_GO
123   , jmp_bufs()
124 #endif
125   , tid(tid)
126   , unique_id(unique_id)
127   , stk_addr(stk_addr)
128   , stk_size(stk_size)
129   , tls_addr(tls_addr)
130   , tls_size(tls_size)
131 #if !SANITIZER_GO
132   , last_sleep_clock(tid)
133 #endif
134 {
135 }
136 
137 #if !SANITIZER_GO
138 static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
139   uptr n_threads;
140   uptr n_running_threads;
141   ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
142   InternalMmapVector<char> buf(4096);
143   WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
144   WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
145 }
146 
147 static void *BackgroundThread(void *arg) {
148   // This is a non-initialized non-user thread, nothing to see here.
149   // We don't use ScopedIgnoreInterceptors, because we want ignores to be
150   // enabled even when the thread function exits (e.g. during pthread thread
151   // shutdown code).
152   cur_thread_init();
153   cur_thread()->ignore_interceptors++;
154   const u64 kMs2Ns = 1000 * 1000;
155 
156   fd_t mprof_fd = kInvalidFd;
157   if (flags()->profile_memory && flags()->profile_memory[0]) {
158     if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
159       mprof_fd = 1;
160     } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
161       mprof_fd = 2;
162     } else {
163       InternalScopedString filename(kMaxPathLength);
164       filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
165       fd_t fd = OpenFile(filename.data(), WrOnly);
166       if (fd == kInvalidFd) {
167         Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
168             &filename[0]);
169       } else {
170         mprof_fd = fd;
171       }
172     }
173   }
174 
175   u64 last_flush = NanoTime();
176   uptr last_rss = 0;
177   for (int i = 0;
178       atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
179       i++) {
180     SleepForMillis(100);
181     u64 now = NanoTime();
182 
183     // Flush memory if requested.
184     if (flags()->flush_memory_ms > 0) {
185       if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
186         VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
187         FlushShadowMemory();
188         last_flush = NanoTime();
189       }
190     }
191     // GetRSS can be expensive on huge programs, so don't do it every 100ms.
192     if (flags()->memory_limit_mb > 0) {
193       uptr rss = GetRSS();
194       uptr limit = uptr(flags()->memory_limit_mb) << 20;
195       VPrintf(1, "ThreadSanitizer: memory flush check"
196                  " RSS=%llu LAST=%llu LIMIT=%llu\n",
197               (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
198       if (2 * rss > limit + last_rss) {
199         VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
200         FlushShadowMemory();
201         rss = GetRSS();
202         VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
203       }
204       last_rss = rss;
205     }
206 
207     // Write memory profile if requested.
208     if (mprof_fd != kInvalidFd)
209       MemoryProfiler(ctx, mprof_fd, i);
210 
211     // Flush symbolizer cache if requested.
212     if (flags()->flush_symbolizer_ms > 0) {
213       u64 last = atomic_load(&ctx->last_symbolize_time_ns,
214                              memory_order_relaxed);
215       if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
216         Lock l(&ctx->report_mtx);
217         ScopedErrorReportLock l2;
218         SymbolizeFlush();
219         atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
220       }
221     }
222   }
223   return nullptr;
224 }
225 
226 static void StartBackgroundThread() {
227   ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
228 }
229 
230 #ifndef __mips__
231 static void StopBackgroundThread() {
232   atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
233   internal_join_thread(ctx->background_thread);
234   ctx->background_thread = 0;
235 }
236 #endif
237 #endif
238 
239 void DontNeedShadowFor(uptr addr, uptr size) {
240   ReleaseMemoryPagesToOS(MemToShadow(addr), MemToShadow(addr + size));
241 }
242 
243 #if !SANITIZER_GO
244 void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
245   if (size == 0) return;
246   DontNeedShadowFor(addr, size);
247   ScopedGlobalProcessor sgp;
248   ctx->metamap.ResetRange(thr->proc(), addr, size);
249 }
250 #endif
251 
252 void MapShadow(uptr addr, uptr size) {
253   // Global data is not 64K aligned, but there are no adjacent mappings,
254   // so we can get away with unaligned mapping.
255   // CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
256   const uptr kPageSize = GetPageSizeCached();
257   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
258   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
259   if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
260                                "shadow"))
261     Die();
262 
263   // Meta shadow is 2:1, so tread carefully.
264   static bool data_mapped = false;
265   static uptr mapped_meta_end = 0;
266   uptr meta_begin = (uptr)MemToMeta(addr);
267   uptr meta_end = (uptr)MemToMeta(addr + size);
268   meta_begin = RoundDownTo(meta_begin, 64 << 10);
269   meta_end = RoundUpTo(meta_end, 64 << 10);
270   if (!data_mapped) {
271     // First call maps data+bss.
272     data_mapped = true;
273     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
274                                  "meta shadow"))
275       Die();
276   } else {
277     // Mapping continous heap.
278     // Windows wants 64K alignment.
279     meta_begin = RoundDownTo(meta_begin, 64 << 10);
280     meta_end = RoundUpTo(meta_end, 64 << 10);
281     if (meta_end <= mapped_meta_end)
282       return;
283     if (meta_begin < mapped_meta_end)
284       meta_begin = mapped_meta_end;
285     if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
286                                  "meta shadow"))
287       Die();
288     mapped_meta_end = meta_end;
289   }
290   VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n",
291       addr, addr+size, meta_begin, meta_end);
292 }
293 
294 void MapThreadTrace(uptr addr, uptr size, const char *name) {
295   DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
296   CHECK_GE(addr, TraceMemBeg());
297   CHECK_LE(addr + size, TraceMemEnd());
298   CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
299   if (!MmapFixedSuperNoReserve(addr, size, name)) {
300     Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p)\n",
301         addr, size);
302     Die();
303   }
304 }
305 
306 static void CheckShadowMapping() {
307   uptr beg, end;
308   for (int i = 0; GetUserRegion(i, &beg, &end); i++) {
309     // Skip cases for empty regions (heap definition for architectures that
310     // do not use 64-bit allocator).
311     if (beg == end)
312       continue;
313     VPrintf(3, "checking shadow region %p-%p\n", beg, end);
314     uptr prev = 0;
315     for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) {
316       for (int x = -(int)kShadowCell; x <= (int)kShadowCell; x += kShadowCell) {
317         const uptr p = RoundDown(p0 + x, kShadowCell);
318         if (p < beg || p >= end)
319           continue;
320         const uptr s = MemToShadow(p);
321         const uptr m = (uptr)MemToMeta(p);
322         VPrintf(3, "  checking pointer %p: shadow=%p meta=%p\n", p, s, m);
323         CHECK(IsAppMem(p));
324         CHECK(IsShadowMem(s));
325         CHECK_EQ(p, ShadowToMem(s));
326         CHECK(IsMetaMem(m));
327         if (prev) {
328           // Ensure that shadow and meta mappings are linear within a single
329           // user range. Lots of code that processes memory ranges assumes it.
330           const uptr prev_s = MemToShadow(prev);
331           const uptr prev_m = (uptr)MemToMeta(prev);
332           CHECK_EQ(s - prev_s, (p - prev) * kShadowMultiplier);
333           CHECK_EQ((m - prev_m) / kMetaShadowSize,
334                    (p - prev) / kMetaShadowCell);
335         }
336         prev = p;
337       }
338     }
339   }
340 }
341 
342 #if !SANITIZER_GO
343 static void OnStackUnwind(const SignalContext &sig, const void *,
344                           BufferedStackTrace *stack) {
345   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
346                 common_flags()->fast_unwind_on_fatal);
347 }
348 
349 static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
350   HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
351 }
352 #endif
353 
354 void Initialize(ThreadState *thr) {
355   // Thread safe because done before all threads exist.
356   static bool is_initialized = false;
357   if (is_initialized)
358     return;
359   is_initialized = true;
360   // We are not ready to handle interceptors yet.
361   ScopedIgnoreInterceptors ignore;
362   SanitizerToolName = "ThreadSanitizer";
363   // Install tool-specific callbacks in sanitizer_common.
364   SetCheckFailedCallback(TsanCheckFailed);
365 
366   ctx = new(ctx_placeholder) Context;
367   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
368   const char *options = GetEnv(env_name);
369   CacheBinaryName();
370   CheckASLR();
371   InitializeFlags(&ctx->flags, options, env_name);
372   AvoidCVE_2016_2143();
373   __sanitizer::InitializePlatformEarly();
374   __tsan::InitializePlatformEarly();
375 
376 #if !SANITIZER_GO
377   // Re-exec ourselves if we need to set additional env or command line args.
378   MaybeReexec();
379 
380   InitializeAllocator();
381   ReplaceSystemMalloc();
382 #endif
383   if (common_flags()->detect_deadlocks)
384     ctx->dd = DDetector::Create(flags());
385   Processor *proc = ProcCreate();
386   ProcWire(proc, thr);
387   InitializeInterceptors();
388   CheckShadowMapping();
389   InitializePlatform();
390   InitializeMutex();
391   InitializeDynamicAnnotations();
392 #if !SANITIZER_GO
393   InitializeShadowMemory();
394   InitializeAllocatorLate();
395   InstallDeadlySignalHandlers(TsanOnDeadlySignal);
396 #endif
397   // Setup correct file descriptor for error reports.
398   __sanitizer_set_report_path(common_flags()->log_path);
399   InitializeSuppressions();
400 #if !SANITIZER_GO
401   InitializeLibIgnore();
402   Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
403 #endif
404 
405   VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
406           (int)internal_getpid());
407 
408   // Initialize thread 0.
409   int tid = ThreadCreate(thr, 0, 0, true);
410   CHECK_EQ(tid, 0);
411   ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
412 #if TSAN_CONTAINS_UBSAN
413   __ubsan::InitAsPlugin();
414 #endif
415   ctx->initialized = true;
416 
417 #if !SANITIZER_GO
418   Symbolizer::LateInitialize();
419 #endif
420 
421   if (flags()->stop_on_start) {
422     Printf("ThreadSanitizer is suspended at startup (pid %d)."
423            " Call __tsan_resume().\n",
424            (int)internal_getpid());
425     while (__tsan_resumed == 0) {}
426   }
427 
428   OnInitialize();
429 }
430 
431 void MaybeSpawnBackgroundThread() {
432   // On MIPS, TSan initialization is run before
433   // __pthread_initialize_minimal_internal() is finished, so we can not spawn
434   // new threads.
435 #if !SANITIZER_GO && !defined(__mips__)
436   static atomic_uint32_t bg_thread = {};
437   if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
438       atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
439     StartBackgroundThread();
440     SetSandboxingCallback(StopBackgroundThread);
441   }
442 #endif
443 }
444 
445 
446 int Finalize(ThreadState *thr) {
447   bool failed = false;
448 
449   if (common_flags()->print_module_map == 1) PrintModuleMap();
450 
451   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
452     SleepForMillis(flags()->atexit_sleep_ms);
453 
454   // Wait for pending reports.
455   ctx->report_mtx.Lock();
456   { ScopedErrorReportLock l; }
457   ctx->report_mtx.Unlock();
458 
459 #if !SANITIZER_GO
460   if (Verbosity()) AllocatorPrintStats();
461 #endif
462 
463   ThreadFinalize(thr);
464 
465   if (ctx->nreported) {
466     failed = true;
467 #if !SANITIZER_GO
468     Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
469 #else
470     Printf("Found %d data race(s)\n", ctx->nreported);
471 #endif
472   }
473 
474   if (ctx->nmissed_expected) {
475     failed = true;
476     Printf("ThreadSanitizer: missed %d expected races\n",
477         ctx->nmissed_expected);
478   }
479 
480   if (common_flags()->print_suppressions)
481     PrintMatchedSuppressions();
482 #if !SANITIZER_GO
483   if (flags()->print_benign)
484     PrintMatchedBenignRaces();
485 #endif
486 
487   failed = OnFinalize(failed);
488 
489 #if TSAN_COLLECT_STATS
490   StatAggregate(ctx->stat, thr->stat);
491   StatOutput(ctx->stat);
492 #endif
493 
494   return failed ? common_flags()->exitcode : 0;
495 }
496 
497 #if !SANITIZER_GO
498 void ForkBefore(ThreadState *thr, uptr pc) {
499   ctx->thread_registry->Lock();
500   ctx->report_mtx.Lock();
501   // Ignore memory accesses in the pthread_atfork callbacks.
502   // If any of them triggers a data race we will deadlock
503   // on the report_mtx.
504   // We could ignore interceptors and sync operations as well,
505   // but so far it's unclear if it will do more good or harm.
506   // Unnecessarily ignoring things can lead to false positives later.
507   ThreadIgnoreBegin(thr, pc);
508 }
509 
510 void ForkParentAfter(ThreadState *thr, uptr pc) {
511   ThreadIgnoreEnd(thr, pc);  // Begin is in ForkBefore.
512   ctx->report_mtx.Unlock();
513   ctx->thread_registry->Unlock();
514 }
515 
516 void ForkChildAfter(ThreadState *thr, uptr pc) {
517   ThreadIgnoreEnd(thr, pc);  // Begin is in ForkBefore.
518   ctx->report_mtx.Unlock();
519   ctx->thread_registry->Unlock();
520 
521   uptr nthread = 0;
522   ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */);
523   VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
524       " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
525   if (nthread == 1) {
526     StartBackgroundThread();
527   } else {
528     // We've just forked a multi-threaded process. We cannot reasonably function
529     // after that (some mutexes may be locked before fork). So just enable
530     // ignores for everything in the hope that we will exec soon.
531     ctx->after_multithreaded_fork = true;
532     thr->ignore_interceptors++;
533     ThreadIgnoreBegin(thr, pc);
534     ThreadIgnoreSyncBegin(thr, pc);
535   }
536 }
537 #endif
538 
539 #if SANITIZER_GO
540 NOINLINE
541 void GrowShadowStack(ThreadState *thr) {
542   const int sz = thr->shadow_stack_end - thr->shadow_stack;
543   const int newsz = 2 * sz;
544   uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
545       newsz * sizeof(uptr));
546   internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
547   internal_free(thr->shadow_stack);
548   thr->shadow_stack = newstack;
549   thr->shadow_stack_pos = newstack + sz;
550   thr->shadow_stack_end = newstack + newsz;
551 }
552 #endif
553 
554 u32 CurrentStackId(ThreadState *thr, uptr pc) {
555   if (!thr->is_inited)  // May happen during bootstrap.
556     return 0;
557   if (pc != 0) {
558 #if !SANITIZER_GO
559     DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
560 #else
561     if (thr->shadow_stack_pos == thr->shadow_stack_end)
562       GrowShadowStack(thr);
563 #endif
564     thr->shadow_stack_pos[0] = pc;
565     thr->shadow_stack_pos++;
566   }
567   u32 id = StackDepotPut(
568       StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
569   if (pc != 0)
570     thr->shadow_stack_pos--;
571   return id;
572 }
573 
574 void TraceSwitch(ThreadState *thr) {
575 #if !SANITIZER_GO
576   if (ctx->after_multithreaded_fork)
577     return;
578 #endif
579   thr->nomalloc++;
580   Trace *thr_trace = ThreadTrace(thr->tid);
581   Lock l(&thr_trace->mtx);
582   unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
583   TraceHeader *hdr = &thr_trace->headers[trace];
584   hdr->epoch0 = thr->fast_state.epoch();
585   ObtainCurrentStack(thr, 0, &hdr->stack0);
586   hdr->mset0 = thr->mset;
587   thr->nomalloc--;
588 }
589 
590 Trace *ThreadTrace(int tid) {
591   return (Trace*)GetThreadTraceHeader(tid);
592 }
593 
594 uptr TraceTopPC(ThreadState *thr) {
595   Event *events = (Event*)GetThreadTrace(thr->tid);
596   uptr pc = events[thr->fast_state.GetTracePos()];
597   return pc;
598 }
599 
600 uptr TraceSize() {
601   return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
602 }
603 
604 uptr TraceParts() {
605   return TraceSize() / kTracePartSize;
606 }
607 
608 #if !SANITIZER_GO
609 extern "C" void __tsan_trace_switch() {
610   TraceSwitch(cur_thread());
611 }
612 
613 extern "C" void __tsan_report_race() {
614   ReportRace(cur_thread());
615 }
616 #endif
617 
618 ALWAYS_INLINE
619 Shadow LoadShadow(u64 *p) {
620   u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
621   return Shadow(raw);
622 }
623 
624 ALWAYS_INLINE
625 void StoreShadow(u64 *sp, u64 s) {
626   atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
627 }
628 
629 ALWAYS_INLINE
630 void StoreIfNotYetStored(u64 *sp, u64 *s) {
631   StoreShadow(sp, *s);
632   *s = 0;
633 }
634 
635 ALWAYS_INLINE
636 void HandleRace(ThreadState *thr, u64 *shadow_mem,
637                               Shadow cur, Shadow old) {
638   thr->racy_state[0] = cur.raw();
639   thr->racy_state[1] = old.raw();
640   thr->racy_shadow_addr = shadow_mem;
641 #if !SANITIZER_GO
642   HACKY_CALL(__tsan_report_race);
643 #else
644   ReportRace(thr);
645 #endif
646 }
647 
648 static inline bool HappensBefore(Shadow old, ThreadState *thr) {
649   return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
650 }
651 
652 ALWAYS_INLINE
653 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
654     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
655     u64 *shadow_mem, Shadow cur) {
656   StatInc(thr, StatMop);
657   StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
658   StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
659 
660   // This potentially can live in an MMX/SSE scratch register.
661   // The required intrinsics are:
662   // __m128i _mm_move_epi64(__m128i*);
663   // _mm_storel_epi64(u64*, __m128i);
664   u64 store_word = cur.raw();
665   bool stored = false;
666 
667   // scan all the shadow values and dispatch to 4 categories:
668   // same, replace, candidate and race (see comments below).
669   // we consider only 3 cases regarding access sizes:
670   // equal, intersect and not intersect. initially I considered
671   // larger and smaller as well, it allowed to replace some
672   // 'candidates' with 'same' or 'replace', but I think
673   // it's just not worth it (performance- and complexity-wise).
674 
675   Shadow old(0);
676 
677   // It release mode we manually unroll the loop,
678   // because empirically gcc generates better code this way.
679   // However, we can't afford unrolling in debug mode, because the function
680   // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
681   // threads, which is not enough for the unrolled loop.
682 #if SANITIZER_DEBUG
683   for (int idx = 0; idx < 4; idx++) {
684 #include "tsan_update_shadow_word_inl.h"
685   }
686 #else
687   int idx = 0;
688 #include "tsan_update_shadow_word_inl.h"
689   idx = 1;
690   if (stored) {
691 #include "tsan_update_shadow_word_inl.h"
692   } else {
693 #include "tsan_update_shadow_word_inl.h"
694   }
695   idx = 2;
696   if (stored) {
697 #include "tsan_update_shadow_word_inl.h"
698   } else {
699 #include "tsan_update_shadow_word_inl.h"
700   }
701   idx = 3;
702   if (stored) {
703 #include "tsan_update_shadow_word_inl.h"
704   } else {
705 #include "tsan_update_shadow_word_inl.h"
706   }
707 #endif
708 
709   // we did not find any races and had already stored
710   // the current access info, so we are done
711   if (LIKELY(stored))
712     return;
713   // choose a random candidate slot and replace it
714   StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
715   StatInc(thr, StatShadowReplace);
716   return;
717  RACE:
718   HandleRace(thr, shadow_mem, cur, old);
719   return;
720 }
721 
722 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
723     int size, bool kAccessIsWrite, bool kIsAtomic) {
724   while (size) {
725     int size1 = 1;
726     int kAccessSizeLog = kSizeLog1;
727     if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
728       size1 = 8;
729       kAccessSizeLog = kSizeLog8;
730     } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
731       size1 = 4;
732       kAccessSizeLog = kSizeLog4;
733     } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
734       size1 = 2;
735       kAccessSizeLog = kSizeLog2;
736     }
737     MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
738     addr += size1;
739     size -= size1;
740   }
741 }
742 
743 ALWAYS_INLINE
744 bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
745   Shadow cur(a);
746   for (uptr i = 0; i < kShadowCnt; i++) {
747     Shadow old(LoadShadow(&s[i]));
748     if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
749         old.TidWithIgnore() == cur.TidWithIgnore() &&
750         old.epoch() > sync_epoch &&
751         old.IsAtomic() == cur.IsAtomic() &&
752         old.IsRead() <= cur.IsRead())
753       return true;
754   }
755   return false;
756 }
757 
758 #if defined(__SSE3__)
759 #define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \
760     _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \
761     (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
762 ALWAYS_INLINE
763 bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
764   // This is an optimized version of ContainsSameAccessSlow.
765   // load current access into access[0:63]
766   const m128 access     = _mm_cvtsi64_si128(a);
767   // duplicate high part of access in addr0:
768   // addr0[0:31]        = access[32:63]
769   // addr0[32:63]       = access[32:63]
770   // addr0[64:95]       = access[32:63]
771   // addr0[96:127]      = access[32:63]
772   const m128 addr0      = SHUF(access, access, 1, 1, 1, 1);
773   // load 4 shadow slots
774   const m128 shadow0    = _mm_load_si128((__m128i*)s);
775   const m128 shadow1    = _mm_load_si128((__m128i*)s + 1);
776   // load high parts of 4 shadow slots into addr_vect:
777   // addr_vect[0:31]    = shadow0[32:63]
778   // addr_vect[32:63]   = shadow0[96:127]
779   // addr_vect[64:95]   = shadow1[32:63]
780   // addr_vect[96:127]  = shadow1[96:127]
781   m128 addr_vect        = SHUF(shadow0, shadow1, 1, 3, 1, 3);
782   if (!is_write) {
783     // set IsRead bit in addr_vect
784     const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
785     const m128 rw_mask  = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
786     addr_vect           = _mm_or_si128(addr_vect, rw_mask);
787   }
788   // addr0 == addr_vect?
789   const m128 addr_res   = _mm_cmpeq_epi32(addr0, addr_vect);
790   // epoch1[0:63]       = sync_epoch
791   const m128 epoch1     = _mm_cvtsi64_si128(sync_epoch);
792   // epoch[0:31]        = sync_epoch[0:31]
793   // epoch[32:63]       = sync_epoch[0:31]
794   // epoch[64:95]       = sync_epoch[0:31]
795   // epoch[96:127]      = sync_epoch[0:31]
796   const m128 epoch      = SHUF(epoch1, epoch1, 0, 0, 0, 0);
797   // load low parts of shadow cell epochs into epoch_vect:
798   // epoch_vect[0:31]   = shadow0[0:31]
799   // epoch_vect[32:63]  = shadow0[64:95]
800   // epoch_vect[64:95]  = shadow1[0:31]
801   // epoch_vect[96:127] = shadow1[64:95]
802   const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
803   // epoch_vect >= sync_epoch?
804   const m128 epoch_res  = _mm_cmpgt_epi32(epoch_vect, epoch);
805   // addr_res & epoch_res
806   const m128 res        = _mm_and_si128(addr_res, epoch_res);
807   // mask[0] = res[7]
808   // mask[1] = res[15]
809   // ...
810   // mask[15] = res[127]
811   const int mask        = _mm_movemask_epi8(res);
812   return mask != 0;
813 }
814 #endif
815 
816 ALWAYS_INLINE
817 bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
818 #if defined(__SSE3__)
819   bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
820   // NOTE: this check can fail if the shadow is concurrently mutated
821   // by other threads. But it still can be useful if you modify
822   // ContainsSameAccessFast and want to ensure that it's not completely broken.
823   // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
824   return res;
825 #else
826   return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
827 #endif
828 }
829 
830 ALWAYS_INLINE USED
831 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
832     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
833   u64 *shadow_mem = (u64*)MemToShadow(addr);
834   DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
835       " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
836       (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
837       (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
838       (uptr)shadow_mem[0], (uptr)shadow_mem[1],
839       (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
840 #if SANITIZER_DEBUG
841   if (!IsAppMem(addr)) {
842     Printf("Access to non app mem %zx\n", addr);
843     DCHECK(IsAppMem(addr));
844   }
845   if (!IsShadowMem((uptr)shadow_mem)) {
846     Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
847     DCHECK(IsShadowMem((uptr)shadow_mem));
848   }
849 #endif
850 
851   if (!SANITIZER_GO && !kAccessIsWrite && *shadow_mem == kShadowRodata) {
852     // Access to .rodata section, no races here.
853     // Measurements show that it can be 10-20% of all memory accesses.
854     StatInc(thr, StatMop);
855     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
856     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
857     StatInc(thr, StatMopRodata);
858     return;
859   }
860 
861   FastState fast_state = thr->fast_state;
862   if (UNLIKELY(fast_state.GetIgnoreBit())) {
863     StatInc(thr, StatMop);
864     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
865     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
866     StatInc(thr, StatMopIgnored);
867     return;
868   }
869 
870   Shadow cur(fast_state);
871   cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
872   cur.SetWrite(kAccessIsWrite);
873   cur.SetAtomic(kIsAtomic);
874 
875   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
876       thr->fast_synch_epoch, kAccessIsWrite))) {
877     StatInc(thr, StatMop);
878     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
879     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
880     StatInc(thr, StatMopSame);
881     return;
882   }
883 
884   if (kCollectHistory) {
885     fast_state.IncrementEpoch();
886     thr->fast_state = fast_state;
887     TraceAddEvent(thr, fast_state, EventTypeMop, pc);
888     cur.IncrementEpoch();
889   }
890 
891   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
892       shadow_mem, cur);
893 }
894 
895 // Called by MemoryAccessRange in tsan_rtl_thread.cpp
896 ALWAYS_INLINE USED
897 void MemoryAccessImpl(ThreadState *thr, uptr addr,
898     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
899     u64 *shadow_mem, Shadow cur) {
900   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
901       thr->fast_synch_epoch, kAccessIsWrite))) {
902     StatInc(thr, StatMop);
903     StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
904     StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
905     StatInc(thr, StatMopSame);
906     return;
907   }
908 
909   MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
910       shadow_mem, cur);
911 }
912 
913 static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
914                            u64 val) {
915   (void)thr;
916   (void)pc;
917   if (size == 0)
918     return;
919   // FIXME: fix me.
920   uptr offset = addr % kShadowCell;
921   if (offset) {
922     offset = kShadowCell - offset;
923     if (size <= offset)
924       return;
925     addr += offset;
926     size -= offset;
927   }
928   DCHECK_EQ(addr % 8, 0);
929   // If a user passes some insane arguments (memset(0)),
930   // let it just crash as usual.
931   if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
932     return;
933   // Don't want to touch lots of shadow memory.
934   // If a program maps 10MB stack, there is no need reset the whole range.
935   size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
936   // UnmapOrDie/MmapFixedNoReserve does not work on Windows.
937   if (SANITIZER_WINDOWS || size < common_flags()->clear_shadow_mmap_threshold) {
938     u64 *p = (u64*)MemToShadow(addr);
939     CHECK(IsShadowMem((uptr)p));
940     CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
941     // FIXME: may overwrite a part outside the region
942     for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
943       p[i++] = val;
944       for (uptr j = 1; j < kShadowCnt; j++)
945         p[i++] = 0;
946     }
947   } else {
948     // The region is big, reset only beginning and end.
949     const uptr kPageSize = GetPageSizeCached();
950     u64 *begin = (u64*)MemToShadow(addr);
951     u64 *end = begin + size / kShadowCell * kShadowCnt;
952     u64 *p = begin;
953     // Set at least first kPageSize/2 to page boundary.
954     while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
955       *p++ = val;
956       for (uptr j = 1; j < kShadowCnt; j++)
957         *p++ = 0;
958     }
959     // Reset middle part.
960     u64 *p1 = p;
961     p = RoundDown(end, kPageSize);
962     UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
963     if (!MmapFixedSuperNoReserve((uptr)p1, (uptr)p - (uptr)p1))
964       Die();
965     // Set the ending.
966     while (p < end) {
967       *p++ = val;
968       for (uptr j = 1; j < kShadowCnt; j++)
969         *p++ = 0;
970     }
971   }
972 }
973 
974 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
975   MemoryRangeSet(thr, pc, addr, size, 0);
976 }
977 
978 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
979   // Processing more than 1k (4k of shadow) is expensive,
980   // can cause excessive memory consumption (user does not necessary touch
981   // the whole range) and most likely unnecessary.
982   if (size > 1024)
983     size = 1024;
984   CHECK_EQ(thr->is_freeing, false);
985   thr->is_freeing = true;
986   MemoryAccessRange(thr, pc, addr, size, true);
987   thr->is_freeing = false;
988   if (kCollectHistory) {
989     thr->fast_state.IncrementEpoch();
990     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
991   }
992   Shadow s(thr->fast_state);
993   s.ClearIgnoreBit();
994   s.MarkAsFreed();
995   s.SetWrite(true);
996   s.SetAddr0AndSizeLog(0, 3);
997   MemoryRangeSet(thr, pc, addr, size, s.raw());
998 }
999 
1000 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1001   if (kCollectHistory) {
1002     thr->fast_state.IncrementEpoch();
1003     TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
1004   }
1005   Shadow s(thr->fast_state);
1006   s.ClearIgnoreBit();
1007   s.SetWrite(true);
1008   s.SetAddr0AndSizeLog(0, 3);
1009   MemoryRangeSet(thr, pc, addr, size, s.raw());
1010 }
1011 
1012 void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
1013                                          uptr size) {
1014   if (thr->ignore_reads_and_writes == 0)
1015     MemoryRangeImitateWrite(thr, pc, addr, size);
1016   else
1017     MemoryResetRange(thr, pc, addr, size);
1018 }
1019 
1020 ALWAYS_INLINE USED
1021 void FuncEntry(ThreadState *thr, uptr pc) {
1022   StatInc(thr, StatFuncEnter);
1023   DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
1024   if (kCollectHistory) {
1025     thr->fast_state.IncrementEpoch();
1026     TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
1027   }
1028 
1029   // Shadow stack maintenance can be replaced with
1030   // stack unwinding during trace switch (which presumably must be faster).
1031   DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
1032 #if !SANITIZER_GO
1033   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1034 #else
1035   if (thr->shadow_stack_pos == thr->shadow_stack_end)
1036     GrowShadowStack(thr);
1037 #endif
1038   thr->shadow_stack_pos[0] = pc;
1039   thr->shadow_stack_pos++;
1040 }
1041 
1042 ALWAYS_INLINE USED
1043 void FuncExit(ThreadState *thr) {
1044   StatInc(thr, StatFuncExit);
1045   DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
1046   if (kCollectHistory) {
1047     thr->fast_state.IncrementEpoch();
1048     TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
1049   }
1050 
1051   DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
1052 #if !SANITIZER_GO
1053   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1054 #endif
1055   thr->shadow_stack_pos--;
1056 }
1057 
1058 void ThreadIgnoreBegin(ThreadState *thr, uptr pc, bool save_stack) {
1059   DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
1060   thr->ignore_reads_and_writes++;
1061   CHECK_GT(thr->ignore_reads_and_writes, 0);
1062   thr->fast_state.SetIgnoreBit();
1063 #if !SANITIZER_GO
1064   if (save_stack && !ctx->after_multithreaded_fork)
1065     thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
1066 #endif
1067 }
1068 
1069 void ThreadIgnoreEnd(ThreadState *thr, uptr pc) {
1070   DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
1071   CHECK_GT(thr->ignore_reads_and_writes, 0);
1072   thr->ignore_reads_and_writes--;
1073   if (thr->ignore_reads_and_writes == 0) {
1074     thr->fast_state.ClearIgnoreBit();
1075 #if !SANITIZER_GO
1076     thr->mop_ignore_set.Reset();
1077 #endif
1078   }
1079 }
1080 
1081 #if !SANITIZER_GO
1082 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
1083 uptr __tsan_testonly_shadow_stack_current_size() {
1084   ThreadState *thr = cur_thread();
1085   return thr->shadow_stack_pos - thr->shadow_stack;
1086 }
1087 #endif
1088 
1089 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc, bool save_stack) {
1090   DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1091   thr->ignore_sync++;
1092   CHECK_GT(thr->ignore_sync, 0);
1093 #if !SANITIZER_GO
1094   if (save_stack && !ctx->after_multithreaded_fork)
1095     thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1096 #endif
1097 }
1098 
1099 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) {
1100   DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1101   CHECK_GT(thr->ignore_sync, 0);
1102   thr->ignore_sync--;
1103 #if !SANITIZER_GO
1104   if (thr->ignore_sync == 0)
1105     thr->sync_ignore_set.Reset();
1106 #endif
1107 }
1108 
1109 bool MD5Hash::operator==(const MD5Hash &other) const {
1110   return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1111 }
1112 
1113 #if SANITIZER_DEBUG
1114 void build_consistency_debug() {}
1115 #else
1116 void build_consistency_release() {}
1117 #endif
1118 
1119 #if TSAN_COLLECT_STATS
1120 void build_consistency_stats() {}
1121 #else
1122 void build_consistency_nostats() {}
1123 #endif
1124 
1125 }  // namespace __tsan
1126 
1127 #if !SANITIZER_GO
1128 // Must be included in this file to make sure everything is inlined.
1129 #include "tsan_interface_inl.h"
1130 #endif
1131