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