blob: 63c356b228a4ca005757dc57caab4de5bdb4720a [file] [log] [blame]
Alexey Samsonov603c4be2012-06-04 13:55:19 +00001//===-- tsan_rtl.cc -------------------------------------------------------===//
Kostya Serebryany7ac41482012-05-10 13:48:04 +00002//
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
Dmitry Vyukovfce5bd42012-06-29 16:58:33 +000015#include "sanitizer_common/sanitizer_atomic.h"
Alexey Samsonov0969bcf2012-06-18 08:44:30 +000016#include "sanitizer_common/sanitizer_common.h"
Kostya Serebryany16e00752012-05-31 13:42:53 +000017#include "sanitizer_common/sanitizer_libc.h"
Dmitry Vyukov84853112012-08-31 17:27:49 +000018#include "sanitizer_common/sanitizer_stackdepot.h"
Alexey Samsonov47b16342012-06-07 09:50:16 +000019#include "sanitizer_common/sanitizer_placement_new.h"
Alexey Samsonov8cc1f812012-09-06 08:48:43 +000020#include "sanitizer_common/sanitizer_symbolizer.h"
Kostya Serebryany7ac41482012-05-10 13:48:04 +000021#include "tsan_defs.h"
22#include "tsan_platform.h"
23#include "tsan_rtl.h"
Kostya Serebryany7ac41482012-05-10 13:48:04 +000024#include "tsan_mman.h"
Kostya Serebryany7ac41482012-05-10 13:48:04 +000025#include "tsan_suppressions.h"
Dmitry Vyukova38e40f2013-03-21 07:02:36 +000026#include "tsan_symbolize.h"
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070027#include "ubsan/ubsan_init.h"
Kostya Serebryany7ac41482012-05-10 13:48:04 +000028
Stephen Hines6a211c52014-07-21 00:49:56 -070029#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>
36typedef __m128i m128;
37#endif
38
Dmitry Vyukovadfb6502012-05-22 18:07:45 +000039volatile int __tsan_resumed = 0;
Kostya Serebryany7ac41482012-05-10 13:48:04 +000040
41extern "C" void __tsan_resume() {
Dmitry Vyukovadfb6502012-05-22 18:07:45 +000042 __tsan_resumed = 1;
Kostya Serebryany7ac41482012-05-10 13:48:04 +000043}
44
45namespace __tsan {
46
Stephen Hines86277eb2015-03-23 12:06:32 -070047#ifndef SANITIZER_GO
Alexey Samsonov0a4c9062012-06-05 13:50:57 +000048THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
Dmitry Vyukovb78caa62012-07-05 16:18:28 +000049#endif
Alexey Samsonov0a4c9062012-06-05 13:50:57 +000050static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070051Context *ctx;
Kostya Serebryany7ac41482012-05-10 13:48:04 +000052
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000053// Can be overriden by a front-end.
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000054#ifdef TSAN_EXTERNAL_HOOKS
55bool OnFinalize(bool failed);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070056void OnInitialize();
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000057#else
Stephen Hines2d1fdb22014-05-28 23:58:16 -070058SANITIZER_INTERFACE_ATTRIBUTE
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000059bool WEAK OnFinalize(bool failed) {
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000060 return failed;
61}
Stephen Hines2d1fdb22014-05-28 23:58:16 -070062SANITIZER_INTERFACE_ATTRIBUTE
63void WEAK OnInitialize() {}
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000064#endif
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000065
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000066static char thread_registry_placeholder[sizeof(ThreadRegistry)];
67
68static ThreadContextBase *CreateThreadContext(u32 tid) {
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000069 // Map thread trace when context is created.
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070070 char name[50];
71 internal_snprintf(name, sizeof(name), "trace %u", tid);
72 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
Stephen Hines86277eb2015-03-23 12:06:32 -070073 const uptr hdr = GetThreadTraceHeader(tid);
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070074 internal_snprintf(name, sizeof(name), "trace header %u", tid);
75 MapThreadTrace(hdr, sizeof(Trace), name);
Stephen Hines86277eb2015-03-23 12:06:32 -070076 new((void*)hdr) Trace();
77 // We are going to use only a small part of the trace with the default
78 // value of history_size. However, the constructor writes to the whole trace.
79 // Unmap the unused part.
80 uptr hdr_end = hdr + sizeof(Trace);
81 hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
82 hdr_end = RoundUp(hdr_end, GetPageSizeCached());
83 if (hdr_end < hdr + sizeof(Trace))
84 UnmapOrDie((void*)hdr_end, hdr + sizeof(Trace) - hdr_end);
Dmitry Vyukov9743d742013-03-20 10:31:53 +000085 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000086 return new(mem) ThreadContext(tid);
87}
88
Stephen Hines86277eb2015-03-23 12:06:32 -070089#ifndef SANITIZER_GO
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000090static const u32 kThreadQuarantineSize = 16;
91#else
92static const u32 kThreadQuarantineSize = 64;
93#endif
94
Kostya Serebryany7ac41482012-05-10 13:48:04 +000095Context::Context()
96 : initialized()
97 , report_mtx(MutexTypeReport, StatMtxReport)
98 , nreported()
99 , nmissed_expected()
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +0000100 , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700101 CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000102 , racy_stacks(MBlockRacyStacks)
Dmitry Vyukov158c6ac2012-10-05 15:51:32 +0000103 , racy_addresses(MBlockRacyAddresses)
Alexey Samsonov0a05e5f2013-06-14 11:18:58 +0000104 , fired_suppressions(8) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000105}
106
107// The objects are allocated in TLS, so one may rely on zero-initialization.
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +0000108ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700109 unsigned reuse_count,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000110 uptr stk_addr, uptr stk_size,
111 uptr tls_addr, uptr tls_size)
112 : fast_state(tid, epoch)
113 // Do not touch these, rely on zero initialization,
114 // they may be accessed before the ctor.
Dmitry Vyukovdc563c02013-05-21 08:12:35 +0000115 // , ignore_reads_and_writes()
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700116 // , ignore_interceptors()
117 , clock(tid, reuse_count)
Stephen Hines86277eb2015-03-23 12:06:32 -0700118#ifndef SANITIZER_GO
Dmitry Vyukov8b30c252013-03-25 10:10:44 +0000119 , jmp_bufs(MBlockJmpBuf)
120#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000121 , tid(tid)
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +0000122 , unique_id(unique_id)
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000123 , stk_addr(stk_addr)
124 , stk_size(stk_size)
125 , tls_addr(tls_addr)
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700126 , tls_size(tls_size)
Stephen Hines86277eb2015-03-23 12:06:32 -0700127#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700128 , last_sleep_clock(tid)
129#endif
130{
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000131}
132
Stephen Hines86277eb2015-03-23 12:06:32 -0700133#ifndef SANITIZER_GO
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000134static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000135 uptr n_threads;
136 uptr n_running_threads;
137 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000138 InternalScopedBuffer<char> buf(4096);
Stephen Hines6a211c52014-07-21 00:49:56 -0700139 WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -0700140 WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
Dmitry Vyukov26127732012-05-22 11:33:03 +0000141}
142
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000143static void BackgroundThread(void *arg) {
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700144 // This is a non-initialized non-user thread, nothing to see here.
145 // We don't use ScopedIgnoreInterceptors, because we want ignores to be
146 // enabled even when the thread function exits (e.g. during pthread thread
147 // shutdown code).
148 cur_thread()->ignore_interceptors++;
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000149 const u64 kMs2Ns = 1000 * 1000;
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000150
151 fd_t mprof_fd = kInvalidFd;
152 if (flags()->profile_memory && flags()->profile_memory[0]) {
Stephen Hines6a211c52014-07-21 00:49:56 -0700153 if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
154 mprof_fd = 1;
155 } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
156 mprof_fd = 2;
Peter Collingbourne9578a3e2013-05-08 14:43:49 +0000157 } else {
Stephen Hines86277eb2015-03-23 12:06:32 -0700158 InternalScopedString filename(kMaxPathLength);
159 filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -0700160 fd_t fd = OpenFile(filename.data(), WrOnly);
161 if (fd == kInvalidFd) {
Stephen Hines6a211c52014-07-21 00:49:56 -0700162 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
163 &filename[0]);
164 } else {
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -0700165 mprof_fd = fd;
Stephen Hines6a211c52014-07-21 00:49:56 -0700166 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000167 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000168 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000169
170 u64 last_flush = NanoTime();
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000171 uptr last_rss = 0;
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700172 for (int i = 0;
173 atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
174 i++) {
175 SleepForMillis(100);
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000176 u64 now = NanoTime();
177
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000178 // Flush memory if requested.
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000179 if (flags()->flush_memory_ms > 0) {
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000180 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
Stephen Hines6d186232014-11-26 17:56:19 -0800181 VPrintf(1, "ThreadSanitizer: periodic memory flush\n");
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000182 FlushShadowMemory();
183 last_flush = NanoTime();
184 }
185 }
Stephen Hines6a211c52014-07-21 00:49:56 -0700186 // GetRSS can be expensive on huge programs, so don't do it every 100ms.
Stephen Hines6d186232014-11-26 17:56:19 -0800187 if (flags()->memory_limit_mb > 0) {
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000188 uptr rss = GetRSS();
189 uptr limit = uptr(flags()->memory_limit_mb) << 20;
Stephen Hines6d186232014-11-26 17:56:19 -0800190 VPrintf(1, "ThreadSanitizer: memory flush check"
191 " RSS=%llu LAST=%llu LIMIT=%llu\n",
192 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20);
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000193 if (2 * rss > limit + last_rss) {
Stephen Hines6d186232014-11-26 17:56:19 -0800194 VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n");
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000195 FlushShadowMemory();
196 rss = GetRSS();
Stephen Hines6d186232014-11-26 17:56:19 -0800197 VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000198 }
199 last_rss = rss;
200 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000201
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000202 // Write memory profile if requested.
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000203 if (mprof_fd != kInvalidFd)
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000204 MemoryProfiler(ctx, mprof_fd, i);
205
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000206 // Flush symbolizer cache if requested.
207 if (flags()->flush_symbolizer_ms > 0) {
208 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
209 memory_order_relaxed);
210 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
211 Lock l(&ctx->report_mtx);
Alexey Samsonov7ed46ff2013-04-05 07:30:29 +0000212 SpinMutexLock l2(&CommonSanitizerReportMutex);
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000213 SymbolizeFlush();
214 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
215 }
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000216 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000217 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000218}
219
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700220static void StartBackgroundThread() {
221 ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
222}
223
Stephen Hines86277eb2015-03-23 12:06:32 -0700224#ifndef __mips__
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700225static void StopBackgroundThread() {
226 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
227 internal_join_thread(ctx->background_thread);
228 ctx->background_thread = 0;
229}
230#endif
Stephen Hines86277eb2015-03-23 12:06:32 -0700231#endif
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700232
Dmitry Vyukov7ac33ac2013-03-18 15:49:07 +0000233void DontNeedShadowFor(uptr addr, uptr size) {
234 uptr shadow_beg = MemToShadow(addr);
235 uptr shadow_end = MemToShadow(addr + size);
236 FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
237}
238
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000239void MapShadow(uptr addr, uptr size) {
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700240 // Global data is not 64K aligned, but there are no adjacent mappings,
241 // so we can get away with unaligned mapping.
242 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700243 MmapFixedNoReserve(MemToShadow(addr), size * kShadowMultiplier, "shadow");
Stephen Hines6a211c52014-07-21 00:49:56 -0700244
245 // Meta shadow is 2:1, so tread carefully.
246 static bool data_mapped = false;
247 static uptr mapped_meta_end = 0;
248 uptr meta_begin = (uptr)MemToMeta(addr);
249 uptr meta_end = (uptr)MemToMeta(addr + size);
250 meta_begin = RoundDownTo(meta_begin, 64 << 10);
251 meta_end = RoundUpTo(meta_end, 64 << 10);
252 if (!data_mapped) {
253 // First call maps data+bss.
254 data_mapped = true;
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700255 MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
Stephen Hines6a211c52014-07-21 00:49:56 -0700256 } else {
257 // Mapping continous heap.
258 // Windows wants 64K alignment.
259 meta_begin = RoundDownTo(meta_begin, 64 << 10);
260 meta_end = RoundUpTo(meta_end, 64 << 10);
261 if (meta_end <= mapped_meta_end)
262 return;
263 if (meta_begin < mapped_meta_end)
264 meta_begin = mapped_meta_end;
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700265 MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow");
Stephen Hines6a211c52014-07-21 00:49:56 -0700266 mapped_meta_end = meta_end;
267 }
268 VPrintf(2, "mapped meta shadow for (%p-%p) at (%p-%p)\n",
269 addr, addr+size, meta_begin, meta_end);
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000270}
271
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700272void MapThreadTrace(uptr addr, uptr size, const char *name) {
Dmitry Vyukovdae12512012-12-21 12:30:52 +0000273 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
Stephen Hines6d186232014-11-26 17:56:19 -0800274 CHECK_GE(addr, kTraceMemBeg);
275 CHECK_LE(addr + size, kTraceMemEnd);
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700276 CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700277 uptr addr1 = (uptr)MmapFixedNoReserve(addr, size, name);
Dmitry Vyukov01a7ce82013-10-16 15:35:12 +0000278 if (addr1 != addr) {
279 Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p->%p)\n",
280 addr, size, addr1);
Dmitry Vyukov6535c312012-12-13 08:14:02 +0000281 Die();
282 }
283}
284
Stephen Hines6d186232014-11-26 17:56:19 -0800285static void CheckShadowMapping() {
286 for (uptr i = 0; i < ARRAY_SIZE(UserRegions); i += 2) {
287 const uptr beg = UserRegions[i];
288 const uptr end = UserRegions[i + 1];
289 VPrintf(3, "checking shadow region %p-%p\n", beg, end);
290 for (uptr p0 = beg; p0 <= end; p0 += (end - beg) / 4) {
291 for (int x = -1; x <= 1; x++) {
292 const uptr p = p0 + x;
293 if (p < beg || p >= end)
294 continue;
295 const uptr s = MemToShadow(p);
Stephen Hines86277eb2015-03-23 12:06:32 -0700296 const uptr m = (uptr)MemToMeta(p);
297 VPrintf(3, " checking pointer %p: shadow=%p meta=%p\n", p, s, m);
Stephen Hines6d186232014-11-26 17:56:19 -0800298 CHECK(IsAppMem(p));
299 CHECK(IsShadowMem(s));
300 CHECK_EQ(p & ~(kShadowCell - 1), ShadowToMem(s));
Stephen Hines6d186232014-11-26 17:56:19 -0800301 CHECK(IsMetaMem(m));
302 }
303 }
304 }
305}
306
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000307void Initialize(ThreadState *thr) {
308 // Thread safe because done before all threads exist.
309 static bool is_initialized = false;
310 if (is_initialized)
311 return;
312 is_initialized = true;
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700313 // We are not ready to handle interceptors yet.
314 ScopedIgnoreInterceptors ignore;
Kostya Serebryany859778a2013-01-31 14:11:21 +0000315 SanitizerToolName = "ThreadSanitizer";
Alexey Samsonov591616d2012-09-11 09:44:48 +0000316 // Install tool-specific callbacks in sanitizer_common.
317 SetCheckFailedCallback(TsanCheckFailed);
318
Stephen Hines6d186232014-11-26 17:56:19 -0800319 ctx = new(ctx_placeholder) Context;
320 const char *options = GetEnv(kTsanOptionsEnv);
321 InitializeFlags(&ctx->flags, options);
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700322 CacheBinaryName();
Stephen Hines86277eb2015-03-23 12:06:32 -0700323#ifndef SANITIZER_GO
Dmitry Vyukov2e870512012-08-15 15:35:15 +0000324 InitializeAllocator();
Dmitry Vyukovbbbb20b2012-08-16 19:36:45 +0000325#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000326 InitializeInterceptors();
Stephen Hines6d186232014-11-26 17:56:19 -0800327 CheckShadowMapping();
328 InitializePlatform();
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000329 InitializeMutex();
330 InitializeDynamicAnnotations();
Stephen Hines86277eb2015-03-23 12:06:32 -0700331#ifndef SANITIZER_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000332 InitializeShadowMemory();
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000333#endif
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000334 // Setup correct file descriptor for error reports.
Stephen Hines6d186232014-11-26 17:56:19 -0800335 __sanitizer_set_report_path(common_flags()->log_path);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000336 InitializeSuppressions();
Stephen Hines86277eb2015-03-23 12:06:32 -0700337#ifndef SANITIZER_GO
Dmitry Vyukov4af0f212013-10-03 13:37:17 +0000338 InitializeLibIgnore();
Stephen Hines6d186232014-11-26 17:56:19 -0800339 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
Stephen Hines86277eb2015-03-23 12:06:32 -0700340 // On MIPS, TSan initialization is run before
341 // __pthread_initialize_minimal_internal() is finished, so we can not spawn
342 // new threads.
343#ifndef __mips__
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700344 StartBackgroundThread();
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700345 SetSandboxingCallback(StopBackgroundThread);
346#endif
Stephen Hines86277eb2015-03-23 12:06:32 -0700347#endif
Stephen Hines6d186232014-11-26 17:56:19 -0800348 if (common_flags()->detect_deadlocks)
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700349 ctx->dd = DDetector::Create(flags());
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000350
Stephen Hines6d186232014-11-26 17:56:19 -0800351 VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",
352 (int)internal_getpid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000353
354 // Initialize thread 0.
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000355 int tid = ThreadCreate(thr, 0, 0, true);
356 CHECK_EQ(tid, 0);
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000357 ThreadStart(thr, tid, internal_getpid());
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700358#if TSAN_CONTAINS_UBSAN
359 __ubsan::InitAsPlugin();
360#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000361 ctx->initialized = true;
362
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000363 if (flags()->stop_on_start) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000364 Printf("ThreadSanitizer is suspended at startup (pid %d)."
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000365 " Call __tsan_resume().\n",
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000366 (int)internal_getpid());
Alexey Samsonovba5e9962013-01-30 07:45:58 +0000367 while (__tsan_resumed == 0) {}
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000368 }
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700369
370 OnInitialize();
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000371}
372
373int Finalize(ThreadState *thr) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000374 bool failed = false;
375
Dmitry Vyukov54e0a9a2012-11-07 16:41:57 +0000376 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
377 SleepForMillis(flags()->atexit_sleep_ms);
378
Dmitry Vyukovd0a51c02012-10-02 12:07:16 +0000379 // Wait for pending reports.
380 ctx->report_mtx.Lock();
Alexey Samsonov7ed46ff2013-04-05 07:30:29 +0000381 CommonSanitizerReportMutex.Lock();
382 CommonSanitizerReportMutex.Unlock();
Dmitry Vyukovd0a51c02012-10-02 12:07:16 +0000383 ctx->report_mtx.Unlock();
384
Stephen Hines86277eb2015-03-23 12:06:32 -0700385#ifndef SANITIZER_GO
386 if (Verbosity()) AllocatorPrintStats();
Dmitry Vyukovbdd844c2013-01-24 09:08:03 +0000387#endif
388
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000389 ThreadFinalize(thr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000390
391 if (ctx->nreported) {
392 failed = true;
Stephen Hines86277eb2015-03-23 12:06:32 -0700393#ifndef SANITIZER_GO
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000394 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000395#else
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000396 Printf("Found %d data race(s)\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000397#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000398 }
399
400 if (ctx->nmissed_expected) {
401 failed = true;
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000402 Printf("ThreadSanitizer: missed %d expected races\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000403 ctx->nmissed_expected);
404 }
405
Stephen Hines6d186232014-11-26 17:56:19 -0800406 if (common_flags()->print_suppressions)
Dmitry Vyukovf754eb52013-03-27 17:59:57 +0000407 PrintMatchedSuppressions();
Stephen Hines86277eb2015-03-23 12:06:32 -0700408#ifndef SANITIZER_GO
Dmitry Vyukov0fd908c2013-03-28 16:21:19 +0000409 if (flags()->print_benign)
410 PrintMatchedBenignRaces();
411#endif
Dmitry Vyukovf754eb52013-03-27 17:59:57 +0000412
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000413 failed = OnFinalize(failed);
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000414
Stephen Hines86277eb2015-03-23 12:06:32 -0700415#if TSAN_COLLECT_STATS
Dmitry Vyukov08adb182012-11-13 13:53:43 +0000416 StatAggregate(ctx->stat, thr->stat);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000417 StatOutput(ctx->stat);
Stephen Hines86277eb2015-03-23 12:06:32 -0700418#endif
419
Dmitry Vyukovb7b6b1c2012-05-17 15:00:27 +0000420 return failed ? flags()->exitcode : 0;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000421}
422
Stephen Hines86277eb2015-03-23 12:06:32 -0700423#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700424void ForkBefore(ThreadState *thr, uptr pc) {
425 ctx->thread_registry->Lock();
426 ctx->report_mtx.Lock();
427}
428
429void ForkParentAfter(ThreadState *thr, uptr pc) {
430 ctx->report_mtx.Unlock();
431 ctx->thread_registry->Unlock();
432}
433
434void ForkChildAfter(ThreadState *thr, uptr pc) {
435 ctx->report_mtx.Unlock();
436 ctx->thread_registry->Unlock();
437
438 uptr nthread = 0;
439 ctx->thread_registry->GetNumberOfThreads(0, 0, &nthread /* alive threads */);
440 VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"
441 " parent had %d threads\n", (int)internal_getpid(), (int)nthread);
442 if (nthread == 1) {
Stephen Hines86277eb2015-03-23 12:06:32 -0700443 StartBackgroundThread();
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700444 } else {
445 // We've just forked a multi-threaded process. We cannot reasonably function
446 // after that (some mutexes may be locked before fork). So just enable
447 // ignores for everything in the hope that we will exec soon.
448 ctx->after_multithreaded_fork = true;
449 thr->ignore_interceptors++;
450 ThreadIgnoreBegin(thr, pc);
451 ThreadIgnoreSyncBegin(thr, pc);
452 }
453}
454#endif
455
Stephen Hines86277eb2015-03-23 12:06:32 -0700456#ifdef SANITIZER_GO
Stephen Hines6a211c52014-07-21 00:49:56 -0700457NOINLINE
458void GrowShadowStack(ThreadState *thr) {
459 const int sz = thr->shadow_stack_end - thr->shadow_stack;
460 const int newsz = 2 * sz;
461 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
462 newsz * sizeof(uptr));
463 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
464 internal_free(thr->shadow_stack);
465 thr->shadow_stack = newstack;
466 thr->shadow_stack_pos = newstack + sz;
467 thr->shadow_stack_end = newstack + newsz;
468}
469#endif
470
Dmitry Vyukov84853112012-08-31 17:27:49 +0000471u32 CurrentStackId(ThreadState *thr, uptr pc) {
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -0700472 if (!thr->is_inited) // May happen during bootstrap.
Dmitry Vyukov84853112012-08-31 17:27:49 +0000473 return 0;
Stephen Hines6a211c52014-07-21 00:49:56 -0700474 if (pc != 0) {
Stephen Hines86277eb2015-03-23 12:06:32 -0700475#ifndef SANITIZER_GO
Stephen Hines6a211c52014-07-21 00:49:56 -0700476 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
477#else
478 if (thr->shadow_stack_pos == thr->shadow_stack_end)
479 GrowShadowStack(thr);
480#endif
Dmitry Vyukov84853112012-08-31 17:27:49 +0000481 thr->shadow_stack_pos[0] = pc;
482 thr->shadow_stack_pos++;
483 }
Stephen Hines6d186232014-11-26 17:56:19 -0800484 u32 id = StackDepotPut(
485 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
Stephen Hines6a211c52014-07-21 00:49:56 -0700486 if (pc != 0)
Dmitry Vyukov84853112012-08-31 17:27:49 +0000487 thr->shadow_stack_pos--;
488 return id;
489}
490
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000491void TraceSwitch(ThreadState *thr) {
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000492 thr->nomalloc++;
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000493 Trace *thr_trace = ThreadTrace(thr->tid);
494 Lock l(&thr_trace->mtx);
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000495 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000496 TraceHeader *hdr = &thr_trace->headers[trace];
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000497 hdr->epoch0 = thr->fast_state.epoch();
Stephen Hines6d186232014-11-26 17:56:19 -0800498 ObtainCurrentStack(thr, 0, &hdr->stack0);
Dmitry Vyukovad9da372012-12-06 12:16:15 +0000499 hdr->mset0 = thr->mset;
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000500 thr->nomalloc--;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000501}
502
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000503Trace *ThreadTrace(int tid) {
504 return (Trace*)GetThreadTraceHeader(tid);
505}
506
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000507uptr TraceTopPC(ThreadState *thr) {
508 Event *events = (Event*)GetThreadTrace(thr->tid);
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000509 uptr pc = events[thr->fast_state.GetTracePos()];
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000510 return pc;
511}
512
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000513uptr TraceSize() {
514 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
515}
516
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000517uptr TraceParts() {
518 return TraceSize() / kTracePartSize;
519}
520
Stephen Hines86277eb2015-03-23 12:06:32 -0700521#ifndef SANITIZER_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000522extern "C" void __tsan_trace_switch() {
523 TraceSwitch(cur_thread());
524}
525
526extern "C" void __tsan_report_race() {
527 ReportRace(cur_thread());
528}
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000529#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000530
531ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000532Shadow LoadShadow(u64 *p) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000533 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
534 return Shadow(raw);
535}
536
537ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000538void StoreShadow(u64 *sp, u64 s) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000539 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
540}
541
542ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000543void StoreIfNotYetStored(u64 *sp, u64 *s) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000544 StoreShadow(sp, *s);
545 *s = 0;
546}
547
Stephen Hines6a211c52014-07-21 00:49:56 -0700548ALWAYS_INLINE
549void HandleRace(ThreadState *thr, u64 *shadow_mem,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000550 Shadow cur, Shadow old) {
551 thr->racy_state[0] = cur.raw();
552 thr->racy_state[1] = old.raw();
553 thr->racy_shadow_addr = shadow_mem;
Stephen Hines86277eb2015-03-23 12:06:32 -0700554#ifndef SANITIZER_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000555 HACKY_CALL(__tsan_report_race);
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000556#else
557 ReportRace(thr);
558#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000559}
560
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000561static inline bool HappensBefore(Shadow old, ThreadState *thr) {
Dmitry Vyukovc8f0a002012-11-30 20:02:11 +0000562 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000563}
564
Stephen Hines6a211c52014-07-21 00:49:56 -0700565ALWAYS_INLINE
566void MemoryAccessImpl1(ThreadState *thr, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000567 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000568 u64 *shadow_mem, Shadow cur) {
569 StatInc(thr, StatMop);
570 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
571 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
572
573 // This potentially can live in an MMX/SSE scratch register.
574 // The required intrinsics are:
575 // __m128i _mm_move_epi64(__m128i*);
576 // _mm_storel_epi64(u64*, __m128i);
577 u64 store_word = cur.raw();
578
579 // scan all the shadow values and dispatch to 4 categories:
580 // same, replace, candidate and race (see comments below).
581 // we consider only 3 cases regarding access sizes:
582 // equal, intersect and not intersect. initially I considered
583 // larger and smaller as well, it allowed to replace some
584 // 'candidates' with 'same' or 'replace', but I think
585 // it's just not worth it (performance- and complexity-wise).
586
Dmitry Vyukov286c9142013-03-20 11:22:03 +0000587 Shadow old(0);
Stephen Hines86277eb2015-03-23 12:06:32 -0700588
589 // It release mode we manually unroll the loop,
590 // because empirically gcc generates better code this way.
591 // However, we can't afford unrolling in debug mode, because the function
592 // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
593 // threads, which is not enough for the unrolled loop.
594#if SANITIZER_DEBUG
595 for (int idx = 0; idx < 4; idx++) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000596#include "tsan_update_shadow_word_inl.h"
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000597 }
Stephen Hines86277eb2015-03-23 12:06:32 -0700598#else
599 int idx = 0;
600#include "tsan_update_shadow_word_inl.h"
601 idx = 1;
602#include "tsan_update_shadow_word_inl.h"
603 idx = 2;
604#include "tsan_update_shadow_word_inl.h"
605 idx = 3;
606#include "tsan_update_shadow_word_inl.h"
607#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000608
609 // we did not find any races and had already stored
610 // the current access info, so we are done
611 if (LIKELY(store_word == 0))
612 return;
613 // choose a random candidate slot and replace it
614 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
615 StatInc(thr, StatShadowReplace);
616 return;
617 RACE:
618 HandleRace(thr, shadow_mem, cur, old);
619 return;
620}
621
Dmitry Vyukov8ecd0e52013-04-30 11:56:56 +0000622void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
623 int size, bool kAccessIsWrite, bool kIsAtomic) {
624 while (size) {
625 int size1 = 1;
626 int kAccessSizeLog = kSizeLog1;
Stephen Hines6d186232014-11-26 17:56:19 -0800627 if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
Dmitry Vyukov8ecd0e52013-04-30 11:56:56 +0000628 size1 = 8;
629 kAccessSizeLog = kSizeLog8;
Stephen Hines6d186232014-11-26 17:56:19 -0800630 } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
Dmitry Vyukov8ecd0e52013-04-30 11:56:56 +0000631 size1 = 4;
632 kAccessSizeLog = kSizeLog4;
Stephen Hines6d186232014-11-26 17:56:19 -0800633 } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
Dmitry Vyukov8ecd0e52013-04-30 11:56:56 +0000634 size1 = 2;
635 kAccessSizeLog = kSizeLog2;
636 }
637 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
638 addr += size1;
639 size -= size1;
640 }
641}
642
Stephen Hines6a211c52014-07-21 00:49:56 -0700643ALWAYS_INLINE
644bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
645 Shadow cur(a);
646 for (uptr i = 0; i < kShadowCnt; i++) {
647 Shadow old(LoadShadow(&s[i]));
648 if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
649 old.TidWithIgnore() == cur.TidWithIgnore() &&
650 old.epoch() > sync_epoch &&
651 old.IsAtomic() == cur.IsAtomic() &&
652 old.IsRead() <= cur.IsRead())
653 return true;
654 }
655 return false;
656}
657
Stephen Hines86277eb2015-03-23 12:06:32 -0700658#if defined(__SSE3__)
Stephen Hines6a211c52014-07-21 00:49:56 -0700659#define SHUF(v0, v1, i0, i1, i2, i3) _mm_castps_si128(_mm_shuffle_ps( \
660 _mm_castsi128_ps(v0), _mm_castsi128_ps(v1), \
661 (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))
662ALWAYS_INLINE
663bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
664 // This is an optimized version of ContainsSameAccessSlow.
665 // load current access into access[0:63]
666 const m128 access = _mm_cvtsi64_si128(a);
667 // duplicate high part of access in addr0:
668 // addr0[0:31] = access[32:63]
669 // addr0[32:63] = access[32:63]
670 // addr0[64:95] = access[32:63]
671 // addr0[96:127] = access[32:63]
672 const m128 addr0 = SHUF(access, access, 1, 1, 1, 1);
673 // load 4 shadow slots
674 const m128 shadow0 = _mm_load_si128((__m128i*)s);
675 const m128 shadow1 = _mm_load_si128((__m128i*)s + 1);
676 // load high parts of 4 shadow slots into addr_vect:
677 // addr_vect[0:31] = shadow0[32:63]
678 // addr_vect[32:63] = shadow0[96:127]
679 // addr_vect[64:95] = shadow1[32:63]
680 // addr_vect[96:127] = shadow1[96:127]
681 m128 addr_vect = SHUF(shadow0, shadow1, 1, 3, 1, 3);
682 if (!is_write) {
683 // set IsRead bit in addr_vect
684 const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
685 const m128 rw_mask = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0);
686 addr_vect = _mm_or_si128(addr_vect, rw_mask);
687 }
688 // addr0 == addr_vect?
689 const m128 addr_res = _mm_cmpeq_epi32(addr0, addr_vect);
690 // epoch1[0:63] = sync_epoch
691 const m128 epoch1 = _mm_cvtsi64_si128(sync_epoch);
692 // epoch[0:31] = sync_epoch[0:31]
693 // epoch[32:63] = sync_epoch[0:31]
694 // epoch[64:95] = sync_epoch[0:31]
695 // epoch[96:127] = sync_epoch[0:31]
696 const m128 epoch = SHUF(epoch1, epoch1, 0, 0, 0, 0);
697 // load low parts of shadow cell epochs into epoch_vect:
698 // epoch_vect[0:31] = shadow0[0:31]
699 // epoch_vect[32:63] = shadow0[64:95]
700 // epoch_vect[64:95] = shadow1[0:31]
701 // epoch_vect[96:127] = shadow1[64:95]
702 const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2);
703 // epoch_vect >= sync_epoch?
704 const m128 epoch_res = _mm_cmpgt_epi32(epoch_vect, epoch);
705 // addr_res & epoch_res
706 const m128 res = _mm_and_si128(addr_res, epoch_res);
707 // mask[0] = res[7]
708 // mask[1] = res[15]
709 // ...
710 // mask[15] = res[127]
711 const int mask = _mm_movemask_epi8(res);
712 return mask != 0;
713}
714#endif
715
716ALWAYS_INLINE
717bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
Stephen Hines86277eb2015-03-23 12:06:32 -0700718#if defined(__SSE3__)
Stephen Hines6a211c52014-07-21 00:49:56 -0700719 bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
Stephen Hines6d186232014-11-26 17:56:19 -0800720 // NOTE: this check can fail if the shadow is concurrently mutated
Stephen Hines86277eb2015-03-23 12:06:32 -0700721 // by other threads. But it still can be useful if you modify
722 // ContainsSameAccessFast and want to ensure that it's not completely broken.
723 // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
Stephen Hines6a211c52014-07-21 00:49:56 -0700724 return res;
725#else
726 return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
727#endif
728}
729
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000730ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000731void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000732 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000733 u64 *shadow_mem = (u64*)MemToShadow(addr);
Dmitry Vyukov68230a12012-12-07 19:23:59 +0000734 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
Alexey Samsonove9541012012-06-06 13:11:29 +0000735 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000736 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
737 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
Alexey Samsonove9541012012-06-06 13:11:29 +0000738 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
739 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
Stephen Hines86277eb2015-03-23 12:06:32 -0700740#if SANITIZER_DEBUG
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000741 if (!IsAppMem(addr)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000742 Printf("Access to non app mem %zx\n", addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000743 DCHECK(IsAppMem(addr));
744 }
745 if (!IsShadowMem((uptr)shadow_mem)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000746 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000747 DCHECK(IsShadowMem((uptr)shadow_mem));
748 }
749#endif
750
Stephen Hines6a211c52014-07-21 00:49:56 -0700751 if (kCppMode && *shadow_mem == kShadowRodata) {
Dmitry Vyukov82dbc512013-03-20 13:21:50 +0000752 // Access to .rodata section, no races here.
753 // Measurements show that it can be 10-20% of all memory accesses.
754 StatInc(thr, StatMop);
755 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
756 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
757 StatInc(thr, StatMopRodata);
758 return;
759 }
760
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000761 FastState fast_state = thr->fast_state;
Stephen Hines6a211c52014-07-21 00:49:56 -0700762 if (fast_state.GetIgnoreBit()) {
763 StatInc(thr, StatMop);
764 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
765 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
766 StatInc(thr, StatMopIgnored);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000767 return;
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700768 }
769
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000770 Shadow cur(fast_state);
771 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
772 cur.SetWrite(kAccessIsWrite);
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000773 cur.SetAtomic(kIsAtomic);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000774
Stephen Hines6a211c52014-07-21 00:49:56 -0700775 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
776 thr->fast_synch_epoch, kAccessIsWrite))) {
777 StatInc(thr, StatMop);
778 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
779 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
780 StatInc(thr, StatMopSame);
781 return;
782 }
783
784 if (kCollectHistory) {
785 fast_state.IncrementEpoch();
786 thr->fast_state = fast_state;
787 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
788 cur.IncrementEpoch();
789 }
790
791 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
792 shadow_mem, cur);
793}
794
795// Called by MemoryAccessRange in tsan_rtl_thread.cc
796ALWAYS_INLINE USED
797void MemoryAccessImpl(ThreadState *thr, uptr addr,
798 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
799 u64 *shadow_mem, Shadow cur) {
800 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
801 thr->fast_synch_epoch, kAccessIsWrite))) {
802 StatInc(thr, StatMop);
803 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
804 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
805 StatInc(thr, StatMopSame);
806 return;
807 }
808
809 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000810 shadow_mem, cur);
811}
812
813static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
814 u64 val) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000815 (void)thr;
816 (void)pc;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000817 if (size == 0)
818 return;
819 // FIXME: fix me.
820 uptr offset = addr % kShadowCell;
821 if (offset) {
822 offset = kShadowCell - offset;
823 if (size <= offset)
824 return;
825 addr += offset;
826 size -= offset;
827 }
Dmitry Vyukovaaac6e22012-09-02 12:04:51 +0000828 DCHECK_EQ(addr % 8, 0);
829 // If a user passes some insane arguments (memset(0)),
830 // let it just crash as usual.
831 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
832 return;
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000833 // Don't want to touch lots of shadow memory.
834 // If a program maps 10MB stack, there is no need reset the whole range.
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000835 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
Dmitry Vyukov9c4d7a42013-06-13 10:15:44 +0000836 // UnmapOrDie/MmapFixedNoReserve does not work on Windows,
837 // so we do it only for C/C++.
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700838 if (kGoMode || size < common_flags()->clear_shadow_mmap_threshold) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000839 u64 *p = (u64*)MemToShadow(addr);
840 CHECK(IsShadowMem((uptr)p));
841 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
842 // FIXME: may overwrite a part outside the region
843 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
844 p[i++] = val;
845 for (uptr j = 1; j < kShadowCnt; j++)
846 p[i++] = 0;
847 }
848 } else {
849 // The region is big, reset only beginning and end.
Stephen Hines86277eb2015-03-23 12:06:32 -0700850 const uptr kPageSize = GetPageSizeCached();
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000851 u64 *begin = (u64*)MemToShadow(addr);
852 u64 *end = begin + size / kShadowCell * kShadowCnt;
853 u64 *p = begin;
854 // Set at least first kPageSize/2 to page boundary.
855 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
856 *p++ = val;
857 for (uptr j = 1; j < kShadowCnt; j++)
858 *p++ = 0;
859 }
860 // Reset middle part.
861 u64 *p1 = p;
862 p = RoundDown(end, kPageSize);
863 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
864 MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1);
865 // Set the ending.
866 while (p < end) {
867 *p++ = val;
868 for (uptr j = 1; j < kShadowCnt; j++)
869 *p++ = 0;
870 }
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000871 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000872}
873
874void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
875 MemoryRangeSet(thr, pc, addr, size, 0);
876}
877
878void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000879 // Processing more than 1k (4k of shadow) is expensive,
880 // can cause excessive memory consumption (user does not necessary touch
881 // the whole range) and most likely unnecessary.
882 if (size > 1024)
883 size = 1024;
Dmitry Vyukov32858662013-02-01 14:41:58 +0000884 CHECK_EQ(thr->is_freeing, false);
885 thr->is_freeing = true;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000886 MemoryAccessRange(thr, pc, addr, size, true);
Dmitry Vyukov32858662013-02-01 14:41:58 +0000887 thr->is_freeing = false;
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700888 if (kCollectHistory) {
889 thr->fast_state.IncrementEpoch();
890 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
891 }
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000892 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000893 s.ClearIgnoreBit();
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000894 s.MarkAsFreed();
895 s.SetWrite(true);
896 s.SetAddr0AndSizeLog(0, 3);
897 MemoryRangeSet(thr, pc, addr, size, s.raw());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000898}
899
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000900void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700901 if (kCollectHistory) {
902 thr->fast_state.IncrementEpoch();
903 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
904 }
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000905 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000906 s.ClearIgnoreBit();
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000907 s.SetWrite(true);
908 s.SetAddr0AndSizeLog(0, 3);
909 MemoryRangeSet(thr, pc, addr, size, s.raw());
910}
911
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000912ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000913void FuncEntry(ThreadState *thr, uptr pc) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000914 StatInc(thr, StatFuncEnter);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000915 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700916 if (kCollectHistory) {
917 thr->fast_state.IncrementEpoch();
918 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
919 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000920
921 // Shadow stack maintenance can be replaced with
922 // stack unwinding during trace switch (which presumably must be faster).
Dmitry Vyukov01a7ce82013-10-16 15:35:12 +0000923 DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
Stephen Hines86277eb2015-03-23 12:06:32 -0700924#ifndef SANITIZER_GO
Dmitry Vyukov01a7ce82013-10-16 15:35:12 +0000925 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000926#else
Stephen Hines6a211c52014-07-21 00:49:56 -0700927 if (thr->shadow_stack_pos == thr->shadow_stack_end)
928 GrowShadowStack(thr);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000929#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000930 thr->shadow_stack_pos[0] = pc;
931 thr->shadow_stack_pos++;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000932}
933
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000934ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000935void FuncExit(ThreadState *thr) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000936 StatInc(thr, StatFuncExit);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000937 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700938 if (kCollectHistory) {
939 thr->fast_state.IncrementEpoch();
940 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
941 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000942
Dmitry Vyukov01a7ce82013-10-16 15:35:12 +0000943 DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
Stephen Hines86277eb2015-03-23 12:06:32 -0700944#ifndef SANITIZER_GO
Dmitry Vyukov01a7ce82013-10-16 15:35:12 +0000945 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000946#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000947 thr->shadow_stack_pos--;
948}
949
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700950void ThreadIgnoreBegin(ThreadState *thr, uptr pc) {
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000951 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
952 thr->ignore_reads_and_writes++;
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000953 CHECK_GT(thr->ignore_reads_and_writes, 0);
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000954 thr->fast_state.SetIgnoreBit();
Stephen Hines86277eb2015-03-23 12:06:32 -0700955#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700956 if (!ctx->after_multithreaded_fork)
957 thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
958#endif
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000959}
960
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700961void ThreadIgnoreEnd(ThreadState *thr, uptr pc) {
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000962 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
963 thr->ignore_reads_and_writes--;
964 CHECK_GE(thr->ignore_reads_and_writes, 0);
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700965 if (thr->ignore_reads_and_writes == 0) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000966 thr->fast_state.ClearIgnoreBit();
Stephen Hines86277eb2015-03-23 12:06:32 -0700967#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700968 thr->mop_ignore_set.Reset();
969#endif
970 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000971}
972
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700973void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000974 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
975 thr->ignore_sync++;
976 CHECK_GT(thr->ignore_sync, 0);
Stephen Hines86277eb2015-03-23 12:06:32 -0700977#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700978 if (!ctx->after_multithreaded_fork)
979 thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
980#endif
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000981}
982
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700983void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc) {
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000984 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
985 thr->ignore_sync--;
986 CHECK_GE(thr->ignore_sync, 0);
Stephen Hines86277eb2015-03-23 12:06:32 -0700987#ifndef SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700988 if (thr->ignore_sync == 0)
989 thr->sync_ignore_set.Reset();
990#endif
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000991}
992
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000993bool MD5Hash::operator==(const MD5Hash &other) const {
994 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
995}
996
Stephen Hines86277eb2015-03-23 12:06:32 -0700997#if SANITIZER_DEBUG
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000998void build_consistency_debug() {}
999#else
1000void build_consistency_release() {}
1001#endif
1002
1003#if TSAN_COLLECT_STATS
1004void build_consistency_stats() {}
1005#else
1006void build_consistency_nostats() {}
1007#endif
1008
Kostya Serebryany7ac41482012-05-10 13:48:04 +00001009} // namespace __tsan
1010
Stephen Hines86277eb2015-03-23 12:06:32 -07001011#ifndef SANITIZER_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +00001012// Must be included in this file to make sure everything is inlined.
1013#include "tsan_interface_inl.h"
Dmitry Vyukovb78caa62012-07-05 16:18:28 +00001014#endif