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