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