blob: d67c9125f7bd14cb8bff22e226753bacf1b807bf [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 Vyukov7c984ca2013-01-30 09:46:53 +000042bool CPP_WEAK OnFinalize(bool failed) {
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000043 return failed;
44}
Dmitry Vyukov22881ec2013-01-30 09:24:00 +000045
Kostya Serebryany7ac41482012-05-10 13:48:04 +000046static Context *ctx;
47Context *CTX() {
48 return ctx;
49}
50
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000051static char thread_registry_placeholder[sizeof(ThreadRegistry)];
52
53static ThreadContextBase *CreateThreadContext(u32 tid) {
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000054 // Map thread trace when context is created.
55 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event));
Dmitry Vyukov9743d742013-03-20 10:31:53 +000056 MapThreadTrace(GetThreadTraceHeader(tid), sizeof(Trace));
57 new(ThreadTrace(tid)) Trace();
58 void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000059 return new(mem) ThreadContext(tid);
60}
61
62#ifndef TSAN_GO
63static const u32 kThreadQuarantineSize = 16;
64#else
65static const u32 kThreadQuarantineSize = 64;
66#endif
67
Kostya Serebryany7ac41482012-05-10 13:48:04 +000068Context::Context()
69 : initialized()
70 , report_mtx(MutexTypeReport, StatMtxReport)
71 , nreported()
72 , nmissed_expected()
Alexey Samsonov2bbd8be2013-03-15 13:48:44 +000073 , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
74 CreateThreadContext, kMaxTid, kThreadQuarantineSize))
Kostya Serebryany7ac41482012-05-10 13:48:04 +000075 , racy_stacks(MBlockRacyStacks)
Dmitry Vyukov158c6ac2012-10-05 15:51:32 +000076 , racy_addresses(MBlockRacyAddresses)
77 , fired_suppressions(MBlockRacyAddresses) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +000078}
79
80// The objects are allocated in TLS, so one may rely on zero-initialization.
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +000081ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
Kostya Serebryany7ac41482012-05-10 13:48:04 +000082 uptr stk_addr, uptr stk_size,
83 uptr tls_addr, uptr tls_size)
84 : fast_state(tid, epoch)
85 // Do not touch these, rely on zero initialization,
86 // they may be accessed before the ctor.
87 // , fast_ignore_reads()
88 // , fast_ignore_writes()
89 // , in_rtl()
90 , shadow_stack_pos(&shadow_stack[0])
Dmitry Vyukov8b30c252013-03-25 10:10:44 +000091#ifndef TSAN_GO
92 , jmp_bufs(MBlockJmpBuf)
93#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +000094 , tid(tid)
Dmitry Vyukovff35f1d2012-08-30 13:02:30 +000095 , unique_id(unique_id)
Kostya Serebryany7ac41482012-05-10 13:48:04 +000096 , stk_addr(stk_addr)
97 , stk_size(stk_size)
98 , tls_addr(tls_addr)
99 , tls_size(tls_size) {
100}
101
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000102static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000103 uptr n_threads;
104 uptr n_running_threads;
105 ctx->thread_registry->GetNumberOfThreads(&n_threads, &n_running_threads);
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000106 InternalScopedBuffer<char> buf(4096);
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000107 internal_snprintf(buf.data(), buf.size(), "%d: nthr=%d nlive=%d\n",
108 i, n_threads, n_running_threads);
109 internal_write(fd, buf.data(), internal_strlen(buf.data()));
110 WriteMemoryProfile(buf.data(), buf.size());
111 internal_write(fd, buf.data(), internal_strlen(buf.data()));
Dmitry Vyukov26127732012-05-22 11:33:03 +0000112}
113
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000114static void BackgroundThread(void *arg) {
115 ScopedInRtl in_rtl;
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000116 Context *ctx = CTX();
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000117 const u64 kMs2Ns = 1000 * 1000;
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000118
119 fd_t mprof_fd = kInvalidFd;
120 if (flags()->profile_memory && flags()->profile_memory[0]) {
121 InternalScopedBuffer<char> filename(4096);
122 internal_snprintf(filename.data(), filename.size(), "%s.%d",
123 flags()->profile_memory, GetPid());
124 mprof_fd = OpenFile(filename.data(), true);
125 if (mprof_fd == kInvalidFd) {
126 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
127 &filename[0]);
128 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000129 }
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000130
131 u64 last_flush = NanoTime();
132 for (int i = 0; ; i++) {
133 SleepForSeconds(1);
134 u64 now = NanoTime();
135
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000136 // Flush memory if requested.
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000137 if (flags()->flush_memory_ms) {
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000138 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000139 FlushShadowMemory();
140 last_flush = NanoTime();
141 }
142 }
143
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000144 // Write memory profile if requested.
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000145 if (mprof_fd != kInvalidFd)
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000146 MemoryProfiler(ctx, mprof_fd, i);
147
148#ifndef TSAN_GO
Dmitry Vyukovf63dde32013-03-21 13:01:50 +0000149 // Flush symbolizer cache if requested.
150 if (flags()->flush_symbolizer_ms > 0) {
151 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
152 memory_order_relaxed);
153 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
154 Lock l(&ctx->report_mtx);
155 SymbolizeFlush();
156 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
157 }
Dmitry Vyukova38e40f2013-03-21 07:02:36 +0000158 }
159#endif
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000160 }
Dmitry Vyukov26127732012-05-22 11:33:03 +0000161}
162
Dmitry Vyukov7ac33ac2013-03-18 15:49:07 +0000163void DontNeedShadowFor(uptr addr, uptr size) {
164 uptr shadow_beg = MemToShadow(addr);
165 uptr shadow_end = MemToShadow(addr + size);
166 FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
167}
168
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000169void MapShadow(uptr addr, uptr size) {
Dmitry Vyukov6b641c52012-11-06 16:48:46 +0000170 MmapFixedNoReserve(MemToShadow(addr), size * kShadowMultiplier);
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000171}
172
Dmitry Vyukov6535c312012-12-13 08:14:02 +0000173void MapThreadTrace(uptr addr, uptr size) {
Dmitry Vyukovdae12512012-12-21 12:30:52 +0000174 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
Dmitry Vyukov6535c312012-12-13 08:14:02 +0000175 CHECK_GE(addr, kTraceMemBegin);
176 CHECK_LE(addr + size, kTraceMemBegin + kTraceMemSize);
177 if (addr != (uptr)MmapFixedNoReserve(addr, size)) {
178 Printf("FATAL: ThreadSanitizer can not mmap thread trace\n");
179 Die();
180 }
181}
182
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000183void Initialize(ThreadState *thr) {
184 // Thread safe because done before all threads exist.
185 static bool is_initialized = false;
186 if (is_initialized)
187 return;
188 is_initialized = true;
Kostya Serebryany859778a2013-01-31 14:11:21 +0000189 SanitizerToolName = "ThreadSanitizer";
Alexey Samsonov591616d2012-09-11 09:44:48 +0000190 // Install tool-specific callbacks in sanitizer_common.
191 SetCheckFailedCallback(TsanCheckFailed);
192
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000193 ScopedInRtl in_rtl;
Dmitry Vyukovbbbb20b2012-08-16 19:36:45 +0000194#ifndef TSAN_GO
Dmitry Vyukov2e870512012-08-15 15:35:15 +0000195 InitializeAllocator();
Dmitry Vyukovbbbb20b2012-08-16 19:36:45 +0000196#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000197 InitializeInterceptors();
198 const char *env = InitializePlatform();
199 InitializeMutex();
200 InitializeDynamicAnnotations();
201 ctx = new(ctx_placeholder) Context;
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000202#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000203 InitializeShadowMemory();
Dmitry Vyukova05fcc12012-11-06 16:00:16 +0000204#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000205 InitializeFlags(&ctx->flags, env);
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000206 // Setup correct file descriptor for error reports.
Dmitry Vyukovcec60682012-11-28 12:56:52 +0000207 if (internal_strcmp(flags()->log_path, "stdout") == 0)
208 __sanitizer_set_report_fd(kStdoutFd);
209 else if (internal_strcmp(flags()->log_path, "stderr") == 0)
210 __sanitizer_set_report_fd(kStderrFd);
211 else
212 __sanitizer_set_report_path(flags()->log_path);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000213 InitializeSuppressions();
Dmitry Vyukov85a6dad2012-09-19 04:39:36 +0000214#ifndef TSAN_GO
Alexey Samsonov68bdcc42012-09-25 12:35:47 +0000215 // Initialize external symbolizer before internal threads are started.
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000216 const char *external_symbolizer = flags()->external_symbolizer_path;
217 if (external_symbolizer != 0 && external_symbolizer[0] != '\0') {
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000218 if (!InitializeExternalSymbolizer(external_symbolizer)) {
219 Printf("Failed to start external symbolizer: '%s'\n",
220 external_symbolizer);
221 Die();
222 }
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000223 }
Dmitry Vyukov85a6dad2012-09-19 04:39:36 +0000224#endif
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000225 internal_start_thread(&BackgroundThread, 0);
Alexey Samsonov8cc1f812012-09-06 08:48:43 +0000226
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000227 if (ctx->flags.verbosity)
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000228 Printf("***** Running under ThreadSanitizer v2 (pid %d) *****\n",
Alexey Samsonov67a64dd2012-06-06 10:13:27 +0000229 GetPid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000230
231 // Initialize thread 0.
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000232 int tid = ThreadCreate(thr, 0, 0, true);
233 CHECK_EQ(tid, 0);
Dmitry Vyukov7dccf3f2012-10-02 11:52:05 +0000234 ThreadStart(thr, tid, GetPid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000235 CHECK_EQ(thr->in_rtl, 1);
236 ctx->initialized = true;
237
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000238 if (flags()->stop_on_start) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000239 Printf("ThreadSanitizer is suspended at startup (pid %d)."
Dmitry Vyukovadfb6502012-05-22 18:07:45 +0000240 " Call __tsan_resume().\n",
241 GetPid());
Alexey Samsonovba5e9962013-01-30 07:45:58 +0000242 while (__tsan_resumed == 0) {}
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000243 }
244}
245
246int Finalize(ThreadState *thr) {
247 ScopedInRtl in_rtl;
248 Context *ctx = __tsan::ctx;
249 bool failed = false;
250
Dmitry Vyukov54e0a9a2012-11-07 16:41:57 +0000251 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
252 SleepForMillis(flags()->atexit_sleep_ms);
253
Dmitry Vyukovd0a51c02012-10-02 12:07:16 +0000254 // Wait for pending reports.
255 ctx->report_mtx.Lock();
256 ctx->report_mtx.Unlock();
257
Dmitry Vyukovbdd844c2013-01-24 09:08:03 +0000258#ifndef TSAN_GO
259 if (ctx->flags.verbosity)
260 AllocatorPrintStats();
261#endif
262
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000263 ThreadFinalize(thr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000264
265 if (ctx->nreported) {
266 failed = true;
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000267#ifndef TSAN_GO
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000268 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000269#else
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000270 Printf("Found %d data race(s)\n", ctx->nreported);
Dmitry Vyukovb3b21232012-10-07 14:21:24 +0000271#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000272 }
273
274 if (ctx->nmissed_expected) {
275 failed = true;
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000276 Printf("ThreadSanitizer: missed %d expected races\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000277 ctx->nmissed_expected);
278 }
279
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000280 failed = OnFinalize(failed);
Dmitry Vyukov22881ec2013-01-30 09:24:00 +0000281
Dmitry Vyukov08adb182012-11-13 13:53:43 +0000282 StatAggregate(ctx->stat, thr->stat);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000283 StatOutput(ctx->stat);
Dmitry Vyukovb7b6b1c2012-05-17 15:00:27 +0000284 return failed ? flags()->exitcode : 0;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000285}
286
Dmitry Vyukov0ab628c2012-09-06 15:18:14 +0000287#ifndef TSAN_GO
Dmitry Vyukov84853112012-08-31 17:27:49 +0000288u32 CurrentStackId(ThreadState *thr, uptr pc) {
289 if (thr->shadow_stack_pos == 0) // May happen during bootstrap.
290 return 0;
291 if (pc) {
292 thr->shadow_stack_pos[0] = pc;
293 thr->shadow_stack_pos++;
294 }
295 u32 id = StackDepotPut(thr->shadow_stack,
296 thr->shadow_stack_pos - thr->shadow_stack);
297 if (pc)
298 thr->shadow_stack_pos--;
299 return id;
300}
Dmitry Vyukov0ab628c2012-09-06 15:18:14 +0000301#endif
Dmitry Vyukov84853112012-08-31 17:27:49 +0000302
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000303void TraceSwitch(ThreadState *thr) {
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000304 thr->nomalloc++;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000305 ScopedInRtl in_rtl;
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000306 Trace *thr_trace = ThreadTrace(thr->tid);
307 Lock l(&thr_trace->mtx);
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000308 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000309 TraceHeader *hdr = &thr_trace->headers[trace];
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000310 hdr->epoch0 = thr->fast_state.epoch();
311 hdr->stack0.ObtainCurrent(thr, 0);
Dmitry Vyukovad9da372012-12-06 12:16:15 +0000312 hdr->mset0 = thr->mset;
Dmitry Vyukov9ad7c322012-06-22 11:08:55 +0000313 thr->nomalloc--;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000314}
315
Dmitry Vyukov9743d742013-03-20 10:31:53 +0000316Trace *ThreadTrace(int tid) {
317 return (Trace*)GetThreadTraceHeader(tid);
318}
319
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000320uptr TraceTopPC(ThreadState *thr) {
321 Event *events = (Event*)GetThreadTrace(thr->tid);
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000322 uptr pc = events[thr->fast_state.GetTracePos()];
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000323 return pc;
324}
325
Dmitry Vyukovd698edc2012-11-28 12:19:50 +0000326uptr TraceSize() {
327 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
328}
329
Dmitry Vyukov0415ac02012-12-04 12:19:53 +0000330uptr TraceParts() {
331 return TraceSize() / kTracePartSize;
332}
333
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000334#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000335extern "C" void __tsan_trace_switch() {
336 TraceSwitch(cur_thread());
337}
338
339extern "C" void __tsan_report_race() {
340 ReportRace(cur_thread());
341}
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000342#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000343
344ALWAYS_INLINE
345static Shadow LoadShadow(u64 *p) {
346 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
347 return Shadow(raw);
348}
349
350ALWAYS_INLINE
351static void StoreShadow(u64 *sp, u64 s) {
352 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
353}
354
355ALWAYS_INLINE
356static void StoreIfNotYetStored(u64 *sp, u64 *s) {
357 StoreShadow(sp, *s);
358 *s = 0;
359}
360
361static inline void HandleRace(ThreadState *thr, u64 *shadow_mem,
362 Shadow cur, Shadow old) {
363 thr->racy_state[0] = cur.raw();
364 thr->racy_state[1] = old.raw();
365 thr->racy_shadow_addr = shadow_mem;
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000366#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000367 HACKY_CALL(__tsan_report_race);
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000368#else
369 ReportRace(thr);
370#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000371}
372
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000373static inline bool OldIsInSameSynchEpoch(Shadow old, ThreadState *thr) {
374 return old.epoch() >= thr->fast_synch_epoch;
375}
376
377static inline bool HappensBefore(Shadow old, ThreadState *thr) {
Dmitry Vyukovc8f0a002012-11-30 20:02:11 +0000378 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000379}
380
381ALWAYS_INLINE
382void MemoryAccessImpl(ThreadState *thr, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000383 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000384 u64 *shadow_mem, Shadow cur) {
385 StatInc(thr, StatMop);
386 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
387 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
388
389 // This potentially can live in an MMX/SSE scratch register.
390 // The required intrinsics are:
391 // __m128i _mm_move_epi64(__m128i*);
392 // _mm_storel_epi64(u64*, __m128i);
393 u64 store_word = cur.raw();
394
395 // scan all the shadow values and dispatch to 4 categories:
396 // same, replace, candidate and race (see comments below).
397 // we consider only 3 cases regarding access sizes:
398 // equal, intersect and not intersect. initially I considered
399 // larger and smaller as well, it allowed to replace some
400 // 'candidates' with 'same' or 'replace', but I think
401 // it's just not worth it (performance- and complexity-wise).
402
Dmitry Vyukov286c9142013-03-20 11:22:03 +0000403 Shadow old(0);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000404 if (kShadowCnt == 1) {
405 int idx = 0;
406#include "tsan_update_shadow_word_inl.h"
407 } else if (kShadowCnt == 2) {
408 int idx = 0;
409#include "tsan_update_shadow_word_inl.h"
410 idx = 1;
411#include "tsan_update_shadow_word_inl.h"
412 } else if (kShadowCnt == 4) {
413 int idx = 0;
414#include "tsan_update_shadow_word_inl.h"
415 idx = 1;
416#include "tsan_update_shadow_word_inl.h"
417 idx = 2;
418#include "tsan_update_shadow_word_inl.h"
419 idx = 3;
420#include "tsan_update_shadow_word_inl.h"
421 } else if (kShadowCnt == 8) {
422 int idx = 0;
423#include "tsan_update_shadow_word_inl.h"
424 idx = 1;
425#include "tsan_update_shadow_word_inl.h"
426 idx = 2;
427#include "tsan_update_shadow_word_inl.h"
428 idx = 3;
429#include "tsan_update_shadow_word_inl.h"
430 idx = 4;
431#include "tsan_update_shadow_word_inl.h"
432 idx = 5;
433#include "tsan_update_shadow_word_inl.h"
434 idx = 6;
435#include "tsan_update_shadow_word_inl.h"
436 idx = 7;
437#include "tsan_update_shadow_word_inl.h"
438 } else {
439 CHECK(false);
440 }
441
442 // we did not find any races and had already stored
443 // the current access info, so we are done
444 if (LIKELY(store_word == 0))
445 return;
446 // choose a random candidate slot and replace it
447 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
448 StatInc(thr, StatShadowReplace);
449 return;
450 RACE:
451 HandleRace(thr, shadow_mem, cur, old);
452 return;
453}
454
455ALWAYS_INLINE
456void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000457 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000458 u64 *shadow_mem = (u64*)MemToShadow(addr);
Dmitry Vyukov68230a12012-12-07 19:23:59 +0000459 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
Alexey Samsonove9541012012-06-06 13:11:29 +0000460 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000461 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
462 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
Alexey Samsonove9541012012-06-06 13:11:29 +0000463 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
464 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000465#if TSAN_DEBUG
466 if (!IsAppMem(addr)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000467 Printf("Access to non app mem %zx\n", addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000468 DCHECK(IsAppMem(addr));
469 }
470 if (!IsShadowMem((uptr)shadow_mem)) {
Alexey Samsonovb1fe3022012-11-02 12:17:51 +0000471 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000472 DCHECK(IsShadowMem((uptr)shadow_mem));
473 }
474#endif
475
Dmitry Vyukov82dbc512013-03-20 13:21:50 +0000476 if (*shadow_mem == kShadowRodata) {
477 // Access to .rodata section, no races here.
478 // Measurements show that it can be 10-20% of all memory accesses.
479 StatInc(thr, StatMop);
480 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
481 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
482 StatInc(thr, StatMopRodata);
483 return;
484 }
485
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000486 FastState fast_state = thr->fast_state;
487 if (fast_state.GetIgnoreBit())
488 return;
489 fast_state.IncrementEpoch();
490 thr->fast_state = fast_state;
491 Shadow cur(fast_state);
492 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
493 cur.SetWrite(kAccessIsWrite);
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000494 cur.SetAtomic(kIsAtomic);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000495
496 // We must not store to the trace if we do not store to the shadow.
497 // That is, this call must be moved somewhere below.
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000498 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000499
Dmitry Vyukov334553e2013-02-01 09:42:06 +0000500 MemoryAccessImpl(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000501 shadow_mem, cur);
502}
503
504static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
505 u64 val) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000506 (void)thr;
507 (void)pc;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000508 if (size == 0)
509 return;
510 // FIXME: fix me.
511 uptr offset = addr % kShadowCell;
512 if (offset) {
513 offset = kShadowCell - offset;
514 if (size <= offset)
515 return;
516 addr += offset;
517 size -= offset;
518 }
Dmitry Vyukovaaac6e22012-09-02 12:04:51 +0000519 DCHECK_EQ(addr % 8, 0);
520 // If a user passes some insane arguments (memset(0)),
521 // let it just crash as usual.
522 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
523 return;
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000524 // Don't want to touch lots of shadow memory.
525 // If a program maps 10MB stack, there is no need reset the whole range.
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000526 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000527 if (size < 64*1024) {
528 u64 *p = (u64*)MemToShadow(addr);
529 CHECK(IsShadowMem((uptr)p));
530 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
531 // FIXME: may overwrite a part outside the region
532 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
533 p[i++] = val;
534 for (uptr j = 1; j < kShadowCnt; j++)
535 p[i++] = 0;
536 }
537 } else {
538 // The region is big, reset only beginning and end.
539 const uptr kPageSize = 4096;
540 u64 *begin = (u64*)MemToShadow(addr);
541 u64 *end = begin + size / kShadowCell * kShadowCnt;
542 u64 *p = begin;
543 // Set at least first kPageSize/2 to page boundary.
544 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
545 *p++ = val;
546 for (uptr j = 1; j < kShadowCnt; j++)
547 *p++ = 0;
548 }
549 // Reset middle part.
550 u64 *p1 = p;
551 p = RoundDown(end, kPageSize);
552 UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
553 MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1);
554 // Set the ending.
555 while (p < end) {
556 *p++ = val;
557 for (uptr j = 1; j < kShadowCnt; j++)
558 *p++ = 0;
559 }
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000560 }
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000561}
562
563void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
564 MemoryRangeSet(thr, pc, addr, size, 0);
565}
566
567void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
Dmitry Vyukov74172de2013-03-18 16:56:48 +0000568 // Processing more than 1k (4k of shadow) is expensive,
569 // can cause excessive memory consumption (user does not necessary touch
570 // the whole range) and most likely unnecessary.
571 if (size > 1024)
572 size = 1024;
Dmitry Vyukov32858662013-02-01 14:41:58 +0000573 CHECK_EQ(thr->is_freeing, false);
574 thr->is_freeing = true;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000575 MemoryAccessRange(thr, pc, addr, size, true);
Dmitry Vyukov32858662013-02-01 14:41:58 +0000576 thr->is_freeing = false;
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000577 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000578 s.ClearIgnoreBit();
Dmitry Vyukov069ce822012-05-17 14:17:51 +0000579 s.MarkAsFreed();
580 s.SetWrite(true);
581 s.SetAddr0AndSizeLog(0, 3);
582 MemoryRangeSet(thr, pc, addr, size, s.raw());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000583}
584
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000585void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
586 Shadow s(thr->fast_state);
Dmitry Vyukov064c8472012-11-30 06:39:01 +0000587 s.ClearIgnoreBit();
Dmitry Vyukov26af8932012-08-15 16:52:19 +0000588 s.SetWrite(true);
589 s.SetAddr0AndSizeLog(0, 3);
590 MemoryRangeSet(thr, pc, addr, size, s.raw());
591}
592
Dmitry Vyukov6fa4cc32012-11-23 07:14:11 +0000593ALWAYS_INLINE
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000594void FuncEntry(ThreadState *thr, uptr pc) {
595 DCHECK_EQ(thr->in_rtl, 0);
596 StatInc(thr, StatFuncEnter);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000597 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000598 thr->fast_state.IncrementEpoch();
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000599 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000600
601 // Shadow stack maintenance can be replaced with
602 // stack unwinding during trace switch (which presumably must be faster).
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000603 DCHECK_GE(thr->shadow_stack_pos, &thr->shadow_stack[0]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000604#ifndef TSAN_GO
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000605 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000606#else
607 if (thr->shadow_stack_pos == thr->shadow_stack_end) {
608 const int sz = thr->shadow_stack_end - thr->shadow_stack;
609 const int newsz = 2 * sz;
610 uptr *newstack = (uptr*)internal_alloc(MBlockShadowStack,
611 newsz * sizeof(uptr));
612 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
613 internal_free(thr->shadow_stack);
614 thr->shadow_stack = newstack;
615 thr->shadow_stack_pos = newstack + sz;
616 thr->shadow_stack_end = newstack + newsz;
617 }
618#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000619 thr->shadow_stack_pos[0] = pc;
620 thr->shadow_stack_pos++;
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000621}
622
Dmitry Vyukov6fa4cc32012-11-23 07:14:11 +0000623ALWAYS_INLINE
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000624void FuncExit(ThreadState *thr) {
625 DCHECK_EQ(thr->in_rtl, 0);
626 StatInc(thr, StatFuncExit);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000627 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000628 thr->fast_state.IncrementEpoch();
Dmitry Vyukov385542a2012-11-28 10:35:31 +0000629 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000630
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000631 DCHECK_GT(thr->shadow_stack_pos, &thr->shadow_stack[0]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000632#ifndef TSAN_GO
Dmitry Vyukov769544e2012-05-28 07:45:35 +0000633 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Dmitry Vyukov25d1c792012-07-16 16:44:47 +0000634#endif
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000635 thr->shadow_stack_pos--;
636}
637
638void IgnoreCtl(ThreadState *thr, bool write, bool begin) {
639 DPrintf("#%d: IgnoreCtl(%d, %d)\n", thr->tid, write, begin);
640 thr->ignore_reads_and_writes += begin ? 1 : -1;
641 CHECK_GE(thr->ignore_reads_and_writes, 0);
642 if (thr->ignore_reads_and_writes)
643 thr->fast_state.SetIgnoreBit();
644 else
645 thr->fast_state.ClearIgnoreBit();
646}
647
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000648bool MD5Hash::operator==(const MD5Hash &other) const {
649 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
650}
651
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000652#if TSAN_DEBUG
653void build_consistency_debug() {}
654#else
655void build_consistency_release() {}
656#endif
657
658#if TSAN_COLLECT_STATS
659void build_consistency_stats() {}
660#else
661void build_consistency_nostats() {}
662#endif
663
664#if TSAN_SHADOW_COUNT == 1
665void build_consistency_shadow1() {}
666#elif TSAN_SHADOW_COUNT == 2
667void build_consistency_shadow2() {}
668#elif TSAN_SHADOW_COUNT == 4
669void build_consistency_shadow4() {}
670#else
671void build_consistency_shadow8() {}
672#endif
673
674} // namespace __tsan
675
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000676#ifndef TSAN_GO
Kostya Serebryany7ac41482012-05-10 13:48:04 +0000677// Must be included in this file to make sure everything is inlined.
678#include "tsan_interface_inl.h"
Dmitry Vyukovb78caa62012-07-05 16:18:28 +0000679#endif