blob: 2a2fcc3c6c56ab8024afba9527815eb065a54eb3 [file] [log] [blame]
Kostya Serebryany4ad375f2012-05-10 13:48:04 +00001//===-- tsan_rtl.cc ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of ThreadSanitizer (TSan), a race detector.
11//
12// Main file (entry points) for the TSan run-time.
13//===----------------------------------------------------------------------===//
14
15#include "tsan_defs.h"
16#include "tsan_platform.h"
17#include "tsan_rtl.h"
18#include "tsan_interface.h"
19#include "tsan_atomic.h"
20#include "tsan_mman.h"
21#include "tsan_placement_new.h"
22#include "tsan_suppressions.h"
23
Dmitry Vyukov302cebb2012-05-22 18:07:45 +000024volatile int __tsan_resumed = 0;
Kostya Serebryany4ad375f2012-05-10 13:48:04 +000025
26extern "C" void __tsan_resume() {
Dmitry Vyukov302cebb2012-05-22 18:07:45 +000027 __tsan_resumed = 1;
Kostya Serebryany4ad375f2012-05-10 13:48:04 +000028}
29
30namespace __tsan {
31
32THREADLOCAL char cur_thread_placeholder[sizeof(ThreadState)] ALIGN(64);
33static char ctx_placeholder[sizeof(Context)] ALIGN(64);
34
35static Context *ctx;
36Context *CTX() {
37 return ctx;
38}
39
40Context::Context()
41 : initialized()
42 , report_mtx(MutexTypeReport, StatMtxReport)
43 , nreported()
44 , nmissed_expected()
45 , thread_mtx(MutexTypeThreads, StatMtxThreads)
46 , racy_stacks(MBlockRacyStacks)
47 , racy_addresses(MBlockRacyAddresses) {
48}
49
50// The objects are allocated in TLS, so one may rely on zero-initialization.
51ThreadState::ThreadState(Context *ctx, int tid, u64 epoch,
52 uptr stk_addr, uptr stk_size,
53 uptr tls_addr, uptr tls_size)
54 : fast_state(tid, epoch)
55 // Do not touch these, rely on zero initialization,
56 // they may be accessed before the ctor.
57 // , fast_ignore_reads()
58 // , fast_ignore_writes()
59 // , in_rtl()
60 , shadow_stack_pos(&shadow_stack[0])
61 , tid(tid)
Kostya Serebryany4ad375f2012-05-10 13:48:04 +000062 , stk_addr(stk_addr)
63 , stk_size(stk_size)
64 , tls_addr(tls_addr)
65 , tls_size(tls_size) {
66}
67
68ThreadContext::ThreadContext(int tid)
69 : tid(tid)
70 , unique_id()
71 , user_id()
72 , thr()
73 , status(ThreadStatusInvalid)
74 , detached()
75 , reuse_count()
76 , epoch0()
77 , epoch1()
Dmitry Vyukovf6985e32012-05-22 14:34:43 +000078 , dead_info()
Kostya Serebryany4ad375f2012-05-10 13:48:04 +000079 , dead_next() {
80}
81
Dmitry Vyukov15710c92012-05-22 11:33:03 +000082static void WriteMemoryProfile(char *buf, uptr buf_size, int num) {
83 uptr shadow = GetShadowMemoryConsumption();
84
85 int nthread = 0;
86 int nlivethread = 0;
87 uptr threadmem = 0;
88 {
89 Lock l(&ctx->thread_mtx);
90 for (unsigned i = 0; i < kMaxTid; i++) {
91 ThreadContext *tctx = ctx->threads[i];
92 if (tctx == 0)
93 continue;
94 nthread += 1;
95 threadmem += sizeof(ThreadContext);
96 if (tctx->status != ThreadStatusRunning)
97 continue;
98 nlivethread += 1;
99 threadmem += sizeof(ThreadState);
100 }
101 }
102
103 uptr nsync = 0;
104 uptr syncmem = CTX()->synctab.GetMemoryConsumption(&nsync);
105
106 Snprintf(buf, buf_size, "%d: shadow=%luMB"
107 " thread=%luMB(total=%d/live=%d)"
108 " sync=%luMB(cnt=%lu)\n",
109 num,
110 shadow >> 20,
111 threadmem >> 20, nthread, nlivethread,
112 syncmem >> 20, nsync);
113}
114
115static void MemoryProfileThread(void *arg) {
116 ScopedInRtl in_rtl;
117 fd_t fd = (fd_t)(uptr)arg;
118 for (int i = 0; ; i++) {
119 InternalScopedBuf<char> buf(4096);
120 WriteMemoryProfile(buf.Ptr(), buf.Size(), i);
121 internal_write(fd, buf.Ptr(), internal_strlen(buf.Ptr()));
122 internal_sleep_ms(1000);
123 }
124}
125
126static void InitializeMemoryProfile() {
127 if (flags()->profile_memory == 0 || flags()->profile_memory[0] == 0)
128 return;
129 InternalScopedBuf<char> filename(4096);
130 Snprintf(filename.Ptr(), filename.Size(), "%s.%d",
131 flags()->profile_memory, GetPid());
132 fd_t fd = internal_open(filename.Ptr(), true);
133 if (fd == kInvalidFd) {
134 Printf("Failed to open memory profile file '%s'\n", &filename[0]);
135 Die();
136 }
137 internal_start_thread(&MemoryProfileThread, (void*)(uptr)fd);
138}
139
Dmitry Vyukov302cebb2012-05-22 18:07:45 +0000140static void MemoryFlushThread(void *arg) {
141 ScopedInRtl in_rtl;
142 for (int i = 0; ; i++) {
143 internal_sleep_ms(flags()->flush_memory_ms);
144 FlushShadowMemory();
145 }
146}
147
148static void InitializeMemoryFlush() {
149 if (flags()->flush_memory_ms == 0)
150 return;
151 if (flags()->flush_memory_ms < 100)
152 flags()->flush_memory_ms = 100;
153 internal_start_thread(&MemoryFlushThread, 0);
154}
155
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000156void Initialize(ThreadState *thr) {
157 // Thread safe because done before all threads exist.
158 static bool is_initialized = false;
159 if (is_initialized)
160 return;
161 is_initialized = true;
162 ScopedInRtl in_rtl;
163 InitializeInterceptors();
164 const char *env = InitializePlatform();
165 InitializeMutex();
166 InitializeDynamicAnnotations();
167 ctx = new(ctx_placeholder) Context;
168 InitializeShadowMemory();
169 ctx->dead_list_size = 0;
170 ctx->dead_list_head = 0;
171 ctx->dead_list_tail = 0;
172 InitializeFlags(&ctx->flags, env);
173 InitializeSuppressions();
Dmitry Vyukov15710c92012-05-22 11:33:03 +0000174 InitializeMemoryProfile();
Dmitry Vyukov302cebb2012-05-22 18:07:45 +0000175 InitializeMemoryFlush();
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000176
177 if (ctx->flags.verbosity)
Dmitry Vyukov302cebb2012-05-22 18:07:45 +0000178 Printf("***** Running under ThreadSanitizer v2 (pid %d) *****\n", GetPid());
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000179
180 // Initialize thread 0.
181 ctx->thread_seq = 0;
182 int tid = ThreadCreate(thr, 0, 0, true);
183 CHECK_EQ(tid, 0);
184 ThreadStart(thr, tid);
185 CHECK_EQ(thr->in_rtl, 1);
186 ctx->initialized = true;
187
Dmitry Vyukov302cebb2012-05-22 18:07:45 +0000188 if (flags()->stop_on_start) {
189 Printf("ThreadSanitizer is suspended at startup (pid %d)."
190 " Call __tsan_resume().\n",
191 GetPid());
192 while (__tsan_resumed == 0);
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000193 }
194}
195
196int Finalize(ThreadState *thr) {
197 ScopedInRtl in_rtl;
198 Context *ctx = __tsan::ctx;
199 bool failed = false;
200
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000201 ThreadFinalize(thr);
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000202
203 if (ctx->nreported) {
204 failed = true;
205 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
206 }
207
208 if (ctx->nmissed_expected) {
209 failed = true;
210 Printf("ThreadSanitizer: missed %d expected races\n",
211 ctx->nmissed_expected);
212 }
213
214 StatOutput(ctx->stat);
Dmitry Vyukov19b855f2012-05-17 15:00:27 +0000215 return failed ? flags()->exitcode : 0;
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000216}
217
218static void TraceSwitch(ThreadState *thr) {
219 ScopedInRtl in_rtl;
220 Lock l(&thr->trace.mtx);
221 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % kTraceParts;
222 TraceHeader *hdr = &thr->trace.headers[trace];
223 hdr->epoch0 = thr->fast_state.epoch();
224 hdr->stack0.ObtainCurrent(thr, 0);
225}
226
227extern "C" void __tsan_trace_switch() {
228 TraceSwitch(cur_thread());
229}
230
231extern "C" void __tsan_report_race() {
232 ReportRace(cur_thread());
233}
234
235ALWAYS_INLINE
236static Shadow LoadShadow(u64 *p) {
237 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
238 return Shadow(raw);
239}
240
241ALWAYS_INLINE
242static void StoreShadow(u64 *sp, u64 s) {
243 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
244}
245
246ALWAYS_INLINE
247static void StoreIfNotYetStored(u64 *sp, u64 *s) {
248 StoreShadow(sp, *s);
249 *s = 0;
250}
251
252static inline void HandleRace(ThreadState *thr, u64 *shadow_mem,
253 Shadow cur, Shadow old) {
254 thr->racy_state[0] = cur.raw();
255 thr->racy_state[1] = old.raw();
256 thr->racy_shadow_addr = shadow_mem;
257 HACKY_CALL(__tsan_report_race);
258}
259
260static inline bool BothReads(Shadow s, int kAccessIsWrite) {
261 return !kAccessIsWrite && !s.is_write();
262}
263
264static inline bool OldIsRWStronger(Shadow old, int kAccessIsWrite) {
265 return old.is_write() || !kAccessIsWrite;
266}
267
268static inline bool OldIsRWWeaker(Shadow old, int kAccessIsWrite) {
269 return !old.is_write() || kAccessIsWrite;
270}
271
272static inline bool OldIsInSameSynchEpoch(Shadow old, ThreadState *thr) {
273 return old.epoch() >= thr->fast_synch_epoch;
274}
275
276static inline bool HappensBefore(Shadow old, ThreadState *thr) {
277 return thr->clock.get(old.tid()) >= old.epoch();
278}
279
280ALWAYS_INLINE
281void MemoryAccessImpl(ThreadState *thr, uptr addr,
282 int kAccessSizeLog, bool kAccessIsWrite, FastState fast_state,
283 u64 *shadow_mem, Shadow cur) {
284 StatInc(thr, StatMop);
285 StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
286 StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
287
288 // This potentially can live in an MMX/SSE scratch register.
289 // The required intrinsics are:
290 // __m128i _mm_move_epi64(__m128i*);
291 // _mm_storel_epi64(u64*, __m128i);
292 u64 store_word = cur.raw();
293
294 // scan all the shadow values and dispatch to 4 categories:
295 // same, replace, candidate and race (see comments below).
296 // we consider only 3 cases regarding access sizes:
297 // equal, intersect and not intersect. initially I considered
298 // larger and smaller as well, it allowed to replace some
299 // 'candidates' with 'same' or 'replace', but I think
300 // it's just not worth it (performance- and complexity-wise).
301
302 Shadow old(0);
303 if (kShadowCnt == 1) {
304 int idx = 0;
305#include "tsan_update_shadow_word_inl.h"
306 } else if (kShadowCnt == 2) {
307 int idx = 0;
308#include "tsan_update_shadow_word_inl.h"
309 idx = 1;
310#include "tsan_update_shadow_word_inl.h"
311 } else if (kShadowCnt == 4) {
312 int idx = 0;
313#include "tsan_update_shadow_word_inl.h"
314 idx = 1;
315#include "tsan_update_shadow_word_inl.h"
316 idx = 2;
317#include "tsan_update_shadow_word_inl.h"
318 idx = 3;
319#include "tsan_update_shadow_word_inl.h"
320 } else if (kShadowCnt == 8) {
321 int idx = 0;
322#include "tsan_update_shadow_word_inl.h"
323 idx = 1;
324#include "tsan_update_shadow_word_inl.h"
325 idx = 2;
326#include "tsan_update_shadow_word_inl.h"
327 idx = 3;
328#include "tsan_update_shadow_word_inl.h"
329 idx = 4;
330#include "tsan_update_shadow_word_inl.h"
331 idx = 5;
332#include "tsan_update_shadow_word_inl.h"
333 idx = 6;
334#include "tsan_update_shadow_word_inl.h"
335 idx = 7;
336#include "tsan_update_shadow_word_inl.h"
337 } else {
338 CHECK(false);
339 }
340
341 // we did not find any races and had already stored
342 // the current access info, so we are done
343 if (LIKELY(store_word == 0))
344 return;
345 // choose a random candidate slot and replace it
346 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
347 StatInc(thr, StatShadowReplace);
348 return;
349 RACE:
350 HandleRace(thr, shadow_mem, cur, old);
351 return;
352}
353
354ALWAYS_INLINE
355void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
356 int kAccessSizeLog, bool kAccessIsWrite) {
357 u64 *shadow_mem = (u64*)MemToShadow(addr);
358 DPrintf2("#%d: tsan::OnMemoryAccess: @%p %p size=%d"
359 " is_write=%d shadow_mem=%p {%llx, %llx, %llx, %llx}\n",
360 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
361 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
362 shadow_mem[0], shadow_mem[1], shadow_mem[2], shadow_mem[3]);
363#if TSAN_DEBUG
364 if (!IsAppMem(addr)) {
365 Printf("Access to non app mem %lx\n", addr);
366 DCHECK(IsAppMem(addr));
367 }
368 if (!IsShadowMem((uptr)shadow_mem)) {
369 Printf("Bad shadow addr %p (%lx)\n", shadow_mem, addr);
370 DCHECK(IsShadowMem((uptr)shadow_mem));
371 }
372#endif
373
374 FastState fast_state = thr->fast_state;
375 if (fast_state.GetIgnoreBit())
376 return;
377 fast_state.IncrementEpoch();
378 thr->fast_state = fast_state;
379 Shadow cur(fast_state);
380 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
381 cur.SetWrite(kAccessIsWrite);
382
383 // We must not store to the trace if we do not store to the shadow.
384 // That is, this call must be moved somewhere below.
385 TraceAddEvent(thr, fast_state.epoch(), EventTypeMop, pc);
386
387 MemoryAccessImpl(thr, addr, kAccessSizeLog, kAccessIsWrite, fast_state,
388 shadow_mem, cur);
389}
390
391static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
392 u64 val) {
393 if (size == 0)
394 return;
395 // FIXME: fix me.
396 uptr offset = addr % kShadowCell;
397 if (offset) {
398 offset = kShadowCell - offset;
399 if (size <= offset)
400 return;
401 addr += offset;
402 size -= offset;
403 }
404 CHECK_EQ(addr % 8, 0);
405 CHECK(IsAppMem(addr));
406 CHECK(IsAppMem(addr + size - 1));
407 (void)thr;
408 (void)pc;
409 // Some programs mmap like hundreds of GBs but actually used a small part.
410 // So, it's better to report a false positive on the memory
411 // then to hang here senselessly.
412 const uptr kMaxResetSize = 1024*1024*1024;
413 if (size > kMaxResetSize)
414 size = kMaxResetSize;
415 size = (size + 7) & ~7;
416 u64 *p = (u64*)MemToShadow(addr);
417 CHECK(IsShadowMem((uptr)p));
418 CHECK(IsShadowMem((uptr)(p + size * kShadowCnt / kShadowCell - 1)));
419 // FIXME: may overwrite a part outside the region
420 for (uptr i = 0; i < size * kShadowCnt / kShadowCell; i++)
421 p[i] = val;
422}
423
424void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
425 MemoryRangeSet(thr, pc, addr, size, 0);
426}
427
428void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
429 MemoryAccessRange(thr, pc, addr, size, true);
Dmitry Vyukovfee5b7d2012-05-17 14:17:51 +0000430 Shadow s(thr->fast_state);
431 s.MarkAsFreed();
432 s.SetWrite(true);
433 s.SetAddr0AndSizeLog(0, 3);
434 MemoryRangeSet(thr, pc, addr, size, s.raw());
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000435}
436
437void FuncEntry(ThreadState *thr, uptr pc) {
438 DCHECK_EQ(thr->in_rtl, 0);
439 StatInc(thr, StatFuncEnter);
440 DPrintf2("#%d: tsan::FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
441 thr->fast_state.IncrementEpoch();
442 TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeFuncEnter, pc);
443
444 // Shadow stack maintenance can be replaced with
445 // stack unwinding during trace switch (which presumably must be faster).
Dmitry Vyukov3de9ca02012-05-28 07:45:35 +0000446 DCHECK_GE(thr->shadow_stack_pos, &thr->shadow_stack[0]);
447 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000448 thr->shadow_stack_pos[0] = pc;
449 thr->shadow_stack_pos++;
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000450}
451
452void FuncExit(ThreadState *thr) {
453 DCHECK_EQ(thr->in_rtl, 0);
454 StatInc(thr, StatFuncExit);
455 DPrintf2("#%d: tsan::FuncExit\n", (int)thr->fast_state.tid());
456 thr->fast_state.IncrementEpoch();
457 TraceAddEvent(thr, thr->fast_state.epoch(), EventTypeFuncExit, 0);
458
Dmitry Vyukov3de9ca02012-05-28 07:45:35 +0000459 DCHECK_GT(thr->shadow_stack_pos, &thr->shadow_stack[0]);
460 DCHECK_LT(thr->shadow_stack_pos, &thr->shadow_stack[kShadowStackSize]);
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000461 thr->shadow_stack_pos--;
462}
463
464void IgnoreCtl(ThreadState *thr, bool write, bool begin) {
465 DPrintf("#%d: IgnoreCtl(%d, %d)\n", thr->tid, write, begin);
466 thr->ignore_reads_and_writes += begin ? 1 : -1;
467 CHECK_GE(thr->ignore_reads_and_writes, 0);
468 if (thr->ignore_reads_and_writes)
469 thr->fast_state.SetIgnoreBit();
470 else
471 thr->fast_state.ClearIgnoreBit();
472}
473
Kostya Serebryany4ad375f2012-05-10 13:48:04 +0000474#if TSAN_DEBUG
475void build_consistency_debug() {}
476#else
477void build_consistency_release() {}
478#endif
479
480#if TSAN_COLLECT_STATS
481void build_consistency_stats() {}
482#else
483void build_consistency_nostats() {}
484#endif
485
486#if TSAN_SHADOW_COUNT == 1
487void build_consistency_shadow1() {}
488#elif TSAN_SHADOW_COUNT == 2
489void build_consistency_shadow2() {}
490#elif TSAN_SHADOW_COUNT == 4
491void build_consistency_shadow4() {}
492#else
493void build_consistency_shadow8() {}
494#endif
495
496} // namespace __tsan
497
498// Must be included in this file to make sure everything is inlined.
499#include "tsan_interface_inl.h"