blob: dcaf071460d8d3b8559a415e97cd9f32d75ca8e1 [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"
Kostya Serebryany7ac41482012-05-10 13:48:04 +000027
Dmitry Vyukovadfb6502012-05-22 18:07:45 +000028volatile int __tsan_resumed = 0;
Kostya Serebryany7ac41482012-05-10 13:48:04 +000029
30extern "C" void __tsan_resume() {
Dmitry Vyukovadfb6502012-05-22 18:07:45 +000031 __tsan_resumed = 1;
Kostya Serebryany7ac41482012-05-10 13:48:04 +000032}
33
34namespace __tsan {
35
Dmitry Vyukovb78caa62012-07-05 16:18:28 +000036#ifndef TSAN_GO
Alexey Samsonov0a4c9062012-06-05 13:50:57 +000037THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64);
Dmitry Vyukovb78caa62012-07-05 16:18:28 +000038#endif
Alexey Samsonov0a4c9062012-06-05 13:50:57 +000039static char ctx_placeholder[sizeof(Context)] ALIGNED(64);
Kostya Serebryany7ac41482012-05-10 13:48:04 +000040
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000041// Can be overriden by a front-end.
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000042#ifdef TSAN_EXTERNAL_HOOKS
43bool OnFinalize(bool failed);
44#else
45bool WEAK OnFinalize(bool failed) {
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000046 return failed;
47}
Dmitry Vyukov6a135be2013-10-14 06:31:03 +000048#endif
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000049
Kostya Serebryany7ac41482012-05-10 13:48:04 +000050static Context *ctx;
51Context *CTX() {
52 return ctx;
53}
54
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000055static char thread_registry_placeholder[sizeof(ThreadRegistry)];
56
57static ThreadContextBase *CreateThreadContext(u32 tid) {
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000058 // Map thread trace when context is created.
59 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event));
Dmitry Vyukov9743d742013-03-20 10:31:53 +000060 MapThreadTrace(GetThreadTraceHeader(tid), sizeof(Trace));
61 new(ThreadTrace(tid)) Trace();
62 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000063 return new(mem) ThreadContext(tid);
64}
65
66#ifndef TSAN_GO
67static const u32 kThreadQuarantineSize = 16;
68#else
69static const u32 kThreadQuarantineSize = 64;
70#endif
71
Kostya Serebryany7ac41482012-05-10 13:48:04 +000072Context::Context()
73 : initialized()
74 , report_mtx(MutexTypeReport, StatMtxReport)
75 , nreported()
76 , nmissed_expected()
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000077 , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
78 CreateThreadContext, kMaxTid, kThreadQuarantineSize))
Kostya Serebryany7ac41482012-05-10 13:48:04 +000079 , racy_stacks(MBlockRacyStacks)
Dmitry Vyukov158c6ac2012-10-05 15:51:32 +000080 , racy_addresses(MBlockRacyAddresses)
Alexey Samsonov0a05e5f2013-06-14 11:18:58 +000081 , fired_suppressions(8) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +000082}
83
84// The objects are allocated in TLS, so one may rely on zero-initialization.
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +000085ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
Kostya Serebryany7ac41482012-05-10 13:48:04 +000086 uptr stk_addr, uptr stk_size,
87 uptr tls_addr, uptr tls_size)
88 : fast_state(tid, epoch)
89 // Do not touch these, rely on zero initialization,
90 // they may be accessed before the ctor.
Dmitry Vyukovdc563c02013-05-21 08:12:35 +000091 // , ignore_reads_and_writes()
Kostya Serebryany7ac41482012-05-10 13:48:04 +000092 // , in_rtl()
93 , shadow_stack_pos(&shadow_stack[0])
Dmitry Vyukov8b30c252013-03-25 10:10:44 +000094#ifndef TSAN_GO
95 , jmp_bufs(MBlockJmpBuf)
96#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +000097 , tid(tid)
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +000098 , unique_id(unique_id)
Kostya Serebryany7ac41482012-05-10 13:48:04 +000099 , stk_addr(stk_addr)
100 , stk_size(stk_size)
101 , tls_addr(tls_addr)
102 , tls_size(tls_size) {
103}
104
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000105static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000106 uptr n_threads;
107 uptr n_running_threads;
108 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000109 InternalScopedBuffer<char> buf(4096);
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000110 internal_snprintf(buf.data(), buf.size(), "%d: nthr=%d nlive=%d\n",
111 i, n_threads, n_running_threads);
112 internal_write(fd, buf.data(), internal_strlen(buf.data()));
113 WriteMemoryProfile(buf.data(), buf.size());
114 internal_write(fd, buf.data(), internal_strlen(buf.data()));
Dmitry Vyukov26127732012-05-22 11:33:03 +0000115}
116
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000117static void BackgroundThread(void *arg) {
118 ScopedInRtl in_rtl;
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000119 Context *ctx = CTX();
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000120 const u64 kMs2Ns = 1000 * 1000;
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000121
122 fd_t mprof_fd = kInvalidFd;
123 if (flags()->profile_memory && flags()->profile_memory[0]) {
124 InternalScopedBuffer<char> filename(4096);
125 internal_snprintf(filename.data(), filename.size(), "%s.%d",
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000126 flags()->profile_memory, (int)internal_getpid());
Peter Collingbourne9578a3e2013-05-08 14:43:49 +0000127 uptr openrv = OpenFile(filename.data(), true);
128 if (internal_iserror(openrv)) {
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000129 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
130 &filename[0]);
Peter Collingbourne9578a3e2013-05-08 14:43:49 +0000131 } else {
132 mprof_fd = openrv;
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000133 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000134 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000135
136 u64 last_flush = NanoTime();
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000137 uptr last_rss = 0;
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000138 for (int i = 0; ; i++) {
139 SleepForSeconds(1);
140 u64 now = NanoTime();
141
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000142 // Flush memory if requested.
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000143 if (flags()->flush_memory_ms > 0) {
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000144 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000145 if (flags()->verbosity > 0)
146 Printf("ThreadSanitizer: periodic memory flush\n");
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000147 FlushShadowMemory();
148 last_flush = NanoTime();
149 }
150 }
Dmitry Vyukov92b54792013-10-03 17:14:35 +0000151 if (flags()->memory_limit_mb > 0) {
152 uptr rss = GetRSS();
153 uptr limit = uptr(flags()->memory_limit_mb) << 20;
154 if (flags()->verbosity > 0) {
155 Printf("ThreadSanitizer: memory flush check"
156 " RSS=%llu LAST=%llu LIMIT=%llu\n",
157 (u64)rss>>20, (u64)last_rss>>20, (u64)limit>>20);
158 }
159 if (2 * rss > limit + last_rss) {
160 if (flags()->verbosity > 0)
161 Printf("ThreadSanitizer: flushing memory due to RSS\n");
162 FlushShadowMemory();
163 rss = GetRSS();
164 if (flags()->verbosity > 0)
165 Printf("ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20);
166 }
167 last_rss = rss;
168 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000169
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000170 // Write memory profile if requested.
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000171 if (mprof_fd != kInvalidFd)
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000172 MemoryProfiler(ctx, mprof_fd, i);
173
174#ifndef TSAN_GO
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000175 // Flush symbolizer cache if requested.
176 if (flags()->flush_symbolizer_ms > 0) {
177 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
178 memory_order_relaxed);
179 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
180 Lock l(&ctx->report_mtx);
Alexey Samsonov7ed46ff2013-04-05 07:30:29 +0000181 SpinMutexLock l2(&CommonSanitizerReportMutex);
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000182 SymbolizeFlush();
183 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
184 }
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000185 }
186#endif
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000187 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000188}
189
Dmitry Vyukov7ac33ac2013-03-18 15:49:07 +0000190void DontNeedShadowFor(uptr addr, uptr size) {
191 uptr shadow_beg = MemToShadow(addr);
192 uptr shadow_end = MemToShadow(addr + size);
193 FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
194}
195
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000196void MapShadow(uptr addr, uptr size) {
Dmitry Vyukov6b641c52012-11-06 16:48:46 +0000197 MmapFixedNoReserve(MemToShadow(addr), size * kShadowMultiplier);
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000198}
199
Dmitry Vyukov6535c312012-12-13 08:14:02 +0000200void MapThreadTrace(uptr addr, uptr size) {
Dmitry Vyukovdae12512012-12-21 12:30:52 +0000201 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
Dmitry Vyukov6535c312012-12-13 08:14:02 +0000202 CHECK_GE(addr, kTraceMemBegin);
203 CHECK_LE(addr + size, kTraceMemBegin + kTraceMemSize);
204 if (addr != (uptr)MmapFixedNoReserve(addr, size)) {
205 Printf("FATAL: ThreadSanitizer can not mmap thread trace\n");
206 Die();
207 }
208}
209
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000210void Initialize(ThreadState *thr) {
211 // Thread safe because done before all threads exist.
212 static bool is_initialized = false;
213 if (is_initialized)
214 return;
215 is_initialized = true;
Kostya Serebryany859778a2013-01-31 14:11:21 +0000216 SanitizerToolName = "ThreadSanitizer";
Alexey Samsonov591616d2012-09-11 09:44:48 +0000217 // Install tool-specific callbacks in sanitizer_common.
218 SetCheckFailedCallback(TsanCheckFailed);
219
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000220 ScopedInRtl in_rtl;
Dmitry Vyukovbbbb20b2012-08-16 19:36:45 +0000221#ifndef TSAN_GO
Dmitry Vyukov2e870512012-08-15 15:35:15 +0000222 InitializeAllocator();
Dmitry Vyukovbbbb20b2012-08-16 19:36:45 +0000223#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000224 InitializeInterceptors();
225 const char *env = InitializePlatform();
226 InitializeMutex();
227 InitializeDynamicAnnotations();
228 ctx = new(ctx_placeholder) Context;
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000229#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000230 InitializeShadowMemory();
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000231#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000232 InitializeFlags(&ctx->flags, env);
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000233 // Setup correct file descriptor for error reports.
Dmitry Vyukovb48c2b22013-10-15 12:25:29 +0000234 __sanitizer_set_report_path(flags()->log_path);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000235 InitializeSuppressions();
Dmitry Vyukov85a6dad2012-09-19 04:39:36 +0000236#ifndef TSAN_GO
Dmitry Vyukov4af0f212013-10-03 13:37:17 +0000237 InitializeLibIgnore();
Alexey Samsonov68bdcc42012-09-25 12:35:47 +0000238 // Initialize external symbolizer before internal threads are started.
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000239 const char *external_symbolizer = flags()->external_symbolizer_path;
Alexey Samsonov5b894002013-10-04 13:38:35 +0000240 bool symbolizer_started =
241 getSymbolizer()->InitializeExternal(external_symbolizer);
242 if (external_symbolizer != 0 && external_symbolizer[0] != '\0' &&
243 !symbolizer_started) {
244 Printf("Failed to start external symbolizer: '%s'\n",
245 external_symbolizer);
246 Die();
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000247 }
Dmitry Vyukov85a6dad2012-09-19 04:39:36 +0000248#endif
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000249 internal_start_thread(&BackgroundThread, 0);
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000250
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000251 if (ctx->flags.verbosity)
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000252 Printf("***** Running under ThreadSanitizer v2 (pid %d) *****\n",
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000253 (int)internal_getpid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000254
255 // Initialize thread 0.
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000256 int tid = ThreadCreate(thr, 0, 0, true);
257 CHECK_EQ(tid, 0);
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000258 ThreadStart(thr, tid, internal_getpid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000259 CHECK_EQ(thr->in_rtl, 1);
260 ctx->initialized = true;
261
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000262 if (flags()->stop_on_start) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000263 Printf("ThreadSanitizer is suspended at startup (pid %d)."
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000264 " Call __tsan_resume().\n",
Peter Collingbourne0b694fc2013-05-17 16:56:53 +0000265 (int)internal_getpid());
Alexey Samsonovba5e9962013-01-30 07:45:58 +0000266 while (__tsan_resumed == 0) {}
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000267 }
268}
269
270int Finalize(ThreadState *thr) {
271 ScopedInRtl in_rtl;
272 Context *ctx = __tsan::ctx;
273 bool failed = false;
274
Dmitry Vyukov54e0a9a2012-11-07 16:41:57 +0000275 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
276 SleepForMillis(flags()->atexit_sleep_ms);
277
Dmitry Vyukovd0a51c02012-10-02 12:07:16 +0000278 // Wait for pending reports.
279 ctx->report_mtx.Lock();
Alexey Samsonov7ed46ff2013-04-05 07:30:29 +0000280 CommonSanitizerReportMutex.Lock();
281 CommonSanitizerReportMutex.Unlock();
Dmitry Vyukovd0a51c02012-10-02 12:07:16 +0000282 ctx->report_mtx.Unlock();
283
Dmitry Vyukovbdd844c2013-01-24 09:08:03 +0000284#ifndef TSAN_GO
285 if (ctx->flags.verbosity)
286 AllocatorPrintStats();
287#endif
288
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000289 ThreadFinalize(thr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000290
291 if (ctx->nreported) {
292 failed = true;
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000293#ifndef TSAN_GO
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000294 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000295#else
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000296 Printf("Found %d data race(s)\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000297#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000298 }
299
300 if (ctx->nmissed_expected) {
301 failed = true;
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000302 Printf("ThreadSanitizer: missed %d expected races\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000303 ctx->nmissed_expected);
304 }
305
Dmitry Vyukovf754eb52013-03-27 17:59:57 +0000306 if (flags()->print_suppressions)
307 PrintMatchedSuppressions();
Dmitry Vyukov0fd908c2013-03-28 16:21:19 +0000308#ifndef TSAN_GO
309 if (flags()->print_benign)
310 PrintMatchedBenignRaces();
311#endif
Dmitry Vyukovf754eb52013-03-27 17:59:57 +0000312
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000313 failed = OnFinalize(failed);
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000314
Dmitry Vyukov08adb182012-11-13 13:53:43 +0000315 StatAggregate(ctx->stat, thr->stat);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000316 StatOutput(ctx->stat);
Dmitry Vyukovb7b6b1c2012-05-17 15:00:27 +0000317 return failed ? flags()->exitcode : 0;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000318}
319
Dmitry Vyukov0ab628c2012-09-06 15:18:14 +0000320#ifndef TSAN_GO
Dmitry Vyukov84853112012-08-31 17:27:49 +0000321u32 CurrentStackId(ThreadState *thr, uptr pc) {
322 if (thr->shadow_stack_pos == 0) // May happen during bootstrap.
323 return 0;
324 if (pc) {
325 thr->shadow_stack_pos[0] = pc;
326 thr->shadow_stack_pos++;
327 }
328 u32 id = StackDepotPut(thr->shadow_stack,
329 thr->shadow_stack_pos - thr->shadow_stack);
330 if (pc)
331 thr->shadow_stack_pos--;
332 return id;
333}
Dmitry Vyukov0ab628c2012-09-06 15:18:14 +0000334#endif
Dmitry Vyukov84853112012-08-31 17:27:49 +0000335
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000336void TraceSwitch(ThreadState *thr) {
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000337 thr->nomalloc++;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000338 ScopedInRtl in_rtl;
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000339 Trace *thr_trace = ThreadTrace(thr->tid);
340 Lock l(&thr_trace->mtx);
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000341 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000342 TraceHeader *hdr = &thr_trace->headers[trace];
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000343 hdr->epoch0 = thr->fast_state.epoch();
344 hdr->stack0.ObtainCurrent(thr, 0);
Dmitry Vyukovad9da372012-12-06 12:16:15 +0000345 hdr->mset0 = thr->mset;
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000346 thr->nomalloc--;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000347}
348
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000349Trace *ThreadTrace(int tid) {
350 return (Trace*)GetThreadTraceHeader(tid);
351}
352
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000353uptr TraceTopPC(ThreadState *thr) {
354 Event *events = (Event*)GetThreadTrace(thr->tid);
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000355 uptr pc = events[thr->fast_state.GetTracePos()];
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000356 return pc;
357}
358
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000359uptr TraceSize() {
360 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
361}
362
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000363uptr TraceParts() {
364 return TraceSize() / kTracePartSize;
365}
366
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000367#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000368extern "C" void __tsan_trace_switch() {
369 TraceSwitch(cur_thread());
370}
371
372extern "C" void __tsan_report_race() {
373 ReportRace(cur_thread());
374}
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000375#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000376
377ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000378Shadow LoadShadow(u64 *p) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000379 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
380 return Shadow(raw);
381}
382
383ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000384void StoreShadow(u64 *sp, u64 s) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000385 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
386}
387
388ALWAYS_INLINE
Timur Iskhodzhanov43c36e42013-03-28 22:23:03 +0000389void StoreIfNotYetStored(u64 *sp, u64 *s) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000390 StoreShadow(sp, *s);
391 *s = 0;
392}
393
394static inline void HandleRace(ThreadState *thr, u64 *shadow_mem,
395 Shadow cur, Shadow old) {
396 thr->racy_state[0] = cur.raw();
397 thr->racy_state[1] = old.raw();
398 thr->racy_shadow_addr = shadow_mem;
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000399#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000400 HACKY_CALL(__tsan_report_race);
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000401#else
402 ReportRace(thr);
403#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000404}
405
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000406static inline bool OldIsInSameSynchEpoch(Shadow old, ThreadState *thr) {
407 return old.epoch() >= thr->fast_synch_epoch;
408}
409
410static inline bool HappensBefore(Shadow old, ThreadState *thr) {
Dmitry Vyukovc8f0a002012-11-30 20:02:11 +0000411 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000412}
413
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000414ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000415void MemoryAccessImpl(ThreadState *thr, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000416 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000417 u64 *shadow_mem, Shadow cur) {
418 StatInc(thr, StatMop);
419 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
420 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
421
422 // This potentially can live in an MMX/SSE scratch register.
423 // The required intrinsics are:
424 // __m128i _mm_move_epi64(__m128i*);
425 // _mm_storel_epi64(u64*, __m128i);
426 u64 store_word = cur.raw();
427
428 // scan all the shadow values and dispatch to 4 categories:
429 // same, replace, candidate and race (see comments below).
430 // we consider only 3 cases regarding access sizes:
431 // equal, intersect and not intersect. initially I considered
432 // larger and smaller as well, it allowed to replace some
433 // 'candidates' with 'same' or 'replace', but I think
434 // it's just not worth it (performance- and complexity-wise).
435
Dmitry Vyukov286c9142013-03-20 11:22:03 +0000436 Shadow old(0);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000437 if (kShadowCnt == 1) {
438 int idx = 0;
439#include "tsan_update_shadow_word_inl.h"
440 } else if (kShadowCnt == 2) {
441 int idx = 0;
442#include "tsan_update_shadow_word_inl.h"
443 idx = 1;
444#include "tsan_update_shadow_word_inl.h"
445 } else if (kShadowCnt == 4) {
446 int idx = 0;
447#include "tsan_update_shadow_word_inl.h"
448 idx = 1;
449#include "tsan_update_shadow_word_inl.h"
450 idx = 2;
451#include "tsan_update_shadow_word_inl.h"
452 idx = 3;
453#include "tsan_update_shadow_word_inl.h"
454 } else if (kShadowCnt == 8) {
455 int idx = 0;
456#include "tsan_update_shadow_word_inl.h"
457 idx = 1;
458#include "tsan_update_shadow_word_inl.h"
459 idx = 2;
460#include "tsan_update_shadow_word_inl.h"
461 idx = 3;
462#include "tsan_update_shadow_word_inl.h"
463 idx = 4;
464#include "tsan_update_shadow_word_inl.h"
465 idx = 5;
466#include "tsan_update_shadow_word_inl.h"
467 idx = 6;
468#include "tsan_update_shadow_word_inl.h"
469 idx = 7;
470#include "tsan_update_shadow_word_inl.h"
471 } else {
472 CHECK(false);
473 }
474
475 // we did not find any races and had already stored
476 // the current access info, so we are done
477 if (LIKELY(store_word == 0))
478 return;
479 // choose a random candidate slot and replace it
480 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
481 StatInc(thr, StatShadowReplace);
482 return;
483 RACE:
484 HandleRace(thr, shadow_mem, cur, old);
485 return;
486}
487
Dmitry Vyukov8ecd0e52013-04-30 11:56:56 +0000488void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
489 int size, bool kAccessIsWrite, bool kIsAtomic) {
490 while (size) {
491 int size1 = 1;
492 int kAccessSizeLog = kSizeLog1;
493 if (size >= 8 && (addr & ~7) == ((addr + 8) & ~7)) {
494 size1 = 8;
495 kAccessSizeLog = kSizeLog8;
496 } else if (size >= 4 && (addr & ~7) == ((addr + 4) & ~7)) {
497 size1 = 4;
498 kAccessSizeLog = kSizeLog4;
499 } else if (size >= 2 && (addr & ~7) == ((addr + 2) & ~7)) {
500 size1 = 2;
501 kAccessSizeLog = kSizeLog2;
502 }
503 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
504 addr += size1;
505 size -= size1;
506 }
507}
508
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000509ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000510void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000511 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000512 u64 *shadow_mem = (u64*)MemToShadow(addr);
Dmitry Vyukov68230a12012-12-07 19:23:59 +0000513 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
Alexey Samsonove9541012012-06-06 13:11:29 +0000514 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000515 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
516 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
Alexey Samsonove9541012012-06-06 13:11:29 +0000517 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
518 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000519#if TSAN_DEBUG
520 if (!IsAppMem(addr)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000521 Printf("Access to non app mem %zx\n", addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000522 DCHECK(IsAppMem(addr));
523 }
524 if (!IsShadowMem((uptr)shadow_mem)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000525 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000526 DCHECK(IsShadowMem((uptr)shadow_mem));
527 }
528#endif
529
Dmitry Vyukov82dbc512013-03-20 13:21:50 +0000530 if (*shadow_mem == kShadowRodata) {
531 // Access to .rodata section, no races here.
532 // Measurements show that it can be 10-20% of all memory accesses.
533 StatInc(thr, StatMop);
534 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
535 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
536 StatInc(thr, StatMopRodata);
537 return;
538 }
539
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000540 FastState fast_state = thr->fast_state;
541 if (fast_state.GetIgnoreBit())
542 return;
543 fast_state.IncrementEpoch();
544 thr->fast_state = fast_state;
545 Shadow cur(fast_state);
546 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
547 cur.SetWrite(kAccessIsWrite);
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000548 cur.SetAtomic(kIsAtomic);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000549
550 // We must not store to the trace if we do not store to the shadow.
551 // That is, this call must be moved somewhere below.
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000552 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000553
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000554 MemoryAccessImpl(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000555 shadow_mem, cur);
556}
557
558static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
559 u64 val) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000560 (void)thr;
561 (void)pc;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000562 if (size == 0)
563 return;
564 // FIXME: fix me.
565 uptr offset = addr % kShadowCell;
566 if (offset) {
567 offset = kShadowCell - offset;
568 if (size <= offset)
569 return;
570 addr += offset;
571 size -= offset;
572 }
Dmitry Vyukovaaac6e22012-09-02 12:04:51 +0000573 DCHECK_EQ(addr % 8, 0);
574 // If a user passes some insane arguments (memset(0)),
575 // let it just crash as usual.
576 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
577 return;
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000578 // Don't want to touch lots of shadow memory.
579 // If a program maps 10MB stack, there is no need reset the whole range.
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000580 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
Dmitry Vyukov9c4d7a42013-06-13 10:15:44 +0000581 // UnmapOrDie/MmapFixedNoReserve does not work on Windows,
582 // so we do it only for C/C++.
583 if (kGoMode || size < 64*1024) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000584 u64 *p = (u64*)MemToShadow(addr);
585 CHECK(IsShadowMem((uptr)p));
586 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
587 // FIXME: may overwrite a part outside the region
588 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
589 p[i++] = val;
590 for (uptr j = 1; j < kShadowCnt; j++)
591 p[i++] = 0;
592 }
593 } else {
594 // The region is big, reset only beginning and end.
595 const uptr kPageSize = 4096;
596 u64 *begin = (u64*)MemToShadow(addr);
597 u64 *end = begin + size / kShadowCell * kShadowCnt;
598 u64 *p = begin;
599 // Set at least first kPageSize/2 to page boundary.
600 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
601 *p++ = val;
602 for (uptr j = 1; j < kShadowCnt; j++)
603 *p++ = 0;
604 }
605 // Reset middle part.
606 u64 *p1 = p;
607 p = RoundDown(end, kPageSize);
608 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
609 MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1);
610 // Set the ending.
611 while (p < end) {
612 *p++ = val;
613 for (uptr j = 1; j < kShadowCnt; j++)
614 *p++ = 0;
615 }
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000616 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000617}
618
619void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
620 MemoryRangeSet(thr, pc, addr, size, 0);
621}
622
623void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000624 // Processing more than 1k (4k of shadow) is expensive,
625 // can cause excessive memory consumption (user does not necessary touch
626 // the whole range) and most likely unnecessary.
627 if (size > 1024)
628 size = 1024;
Dmitry Vyukov32858662013-02-01 14:41:58 +0000629 CHECK_EQ(thr->is_freeing, false);
630 thr->is_freeing = true;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000631 MemoryAccessRange(thr, pc, addr, size, true);
Dmitry Vyukov32858662013-02-01 14:41:58 +0000632 thr->is_freeing = false;
Dmitry Vyukov46fea912013-04-24 11:16:47 +0000633 thr->fast_state.IncrementEpoch();
634 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000635 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000636 s.ClearIgnoreBit();
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000637 s.MarkAsFreed();
638 s.SetWrite(true);
639 s.SetAddr0AndSizeLog(0, 3);
640 MemoryRangeSet(thr, pc, addr, size, s.raw());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000641}
642
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000643void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
Dmitry Vyukov46fea912013-04-24 11:16:47 +0000644 thr->fast_state.IncrementEpoch();
645 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000646 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000647 s.ClearIgnoreBit();
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000648 s.SetWrite(true);
649 s.SetAddr0AndSizeLog(0, 3);
650 MemoryRangeSet(thr, pc, addr, size, s.raw());
651}
652
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000653ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000654void FuncEntry(ThreadState *thr, uptr pc) {
655 DCHECK_EQ(thr->in_rtl, 0);
656 StatInc(thr, StatFuncEnter);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000657 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000658 thr->fast_state.IncrementEpoch();
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000659 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000660
661 // Shadow stack maintenance can be replaced with
662 // stack unwinding during trace switch (which presumably must be faster).
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000663 DCHECK_GE(thr->shadow_stack_pos, &thr->shadow_stack[0]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000664#ifndef TSAN_GO
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000665 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000666#else
667 if (thr->shadow_stack_pos == thr->shadow_stack_end) {
668 const int sz = thr->shadow_stack_end - thr->shadow_stack;
669 const int newsz = 2 * sz;
670 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
671 newsz * sizeof(uptr));
672 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
673 internal_free(thr->shadow_stack);
674 thr->shadow_stack = newstack;
675 thr->shadow_stack_pos = newstack + sz;
676 thr->shadow_stack_end = newstack + newsz;
677 }
678#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000679 thr->shadow_stack_pos[0] = pc;
680 thr->shadow_stack_pos++;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000681}
682
Kostya Serebryanyd475aa82013-03-29 09:44:16 +0000683ALWAYS_INLINE USED
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000684void FuncExit(ThreadState *thr) {
685 DCHECK_EQ(thr->in_rtl, 0);
686 StatInc(thr, StatFuncExit);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000687 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000688 thr->fast_state.IncrementEpoch();
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000689 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000690
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000691 DCHECK_GT(thr->shadow_stack_pos, &thr->shadow_stack[0]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000692#ifndef TSAN_GO
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000693 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000694#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000695 thr->shadow_stack_pos--;
696}
697
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000698void ThreadIgnoreBegin(ThreadState *thr) {
699 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
700 thr->ignore_reads_and_writes++;
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000701 CHECK_GT(thr->ignore_reads_and_writes, 0);
Dmitry Vyukov652f78a2013-09-19 04:39:04 +0000702 thr->fast_state.SetIgnoreBit();
703}
704
705void ThreadIgnoreEnd(ThreadState *thr) {
706 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
707 thr->ignore_reads_and_writes--;
708 CHECK_GE(thr->ignore_reads_and_writes, 0);
709 if (thr->ignore_reads_and_writes == 0)
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000710 thr->fast_state.ClearIgnoreBit();
711}
712
Dmitry Vyukove1ddbf92013-10-10 15:58:12 +0000713void ThreadIgnoreSyncBegin(ThreadState *thr) {
714 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
715 thr->ignore_sync++;
716 CHECK_GT(thr->ignore_sync, 0);
717}
718
719void ThreadIgnoreSyncEnd(ThreadState *thr) {
720 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
721 thr->ignore_sync--;
722 CHECK_GE(thr->ignore_sync, 0);
723}
724
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000725bool MD5Hash::operator==(const MD5Hash &other) const {
726 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
727}
728
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000729#if TSAN_DEBUG
730void build_consistency_debug() {}
731#else
732void build_consistency_release() {}
733#endif
734
735#if TSAN_COLLECT_STATS
736void build_consistency_stats() {}
737#else
738void build_consistency_nostats() {}
739#endif
740
741#if TSAN_SHADOW_COUNT == 1
742void build_consistency_shadow1() {}
743#elif TSAN_SHADOW_COUNT == 2
744void build_consistency_shadow2() {}
745#elif TSAN_SHADOW_COUNT == 4
746void build_consistency_shadow4() {}
747#else
748void build_consistency_shadow8() {}
749#endif
750
751} // namespace __tsan
752
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000753#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000754// Must be included in this file to make sure everything is inlined.
755#include "tsan_interface_inl.h"
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000756#endif