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