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