]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.h
Merge ^/head r317281 through r317502.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / tsan / rtl / tsan_rtl.h
1 //===-- tsan_rtl.h ----------------------------------------------*- 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 internal TSan header file.
13 //
14 // Ground rules:
15 //   - C++ run-time should not be used (static CTORs, RTTI, exceptions, static
16 //     function-scope locals)
17 //   - All functions/classes/etc reside in namespace __tsan, except for those
18 //     declared in tsan_interface.h.
19 //   - Platform-specific files should be used instead of ifdefs (*).
20 //   - No system headers included in header files (*).
21 //   - Platform specific headres included only into platform-specific files (*).
22 //
23 //  (*) Except when inlining is critical for performance.
24 //===----------------------------------------------------------------------===//
25
26 #ifndef TSAN_RTL_H
27 #define TSAN_RTL_H
28
29 #include "sanitizer_common/sanitizer_allocator.h"
30 #include "sanitizer_common/sanitizer_allocator_internal.h"
31 #include "sanitizer_common/sanitizer_asm.h"
32 #include "sanitizer_common/sanitizer_common.h"
33 #include "sanitizer_common/sanitizer_deadlock_detector_interface.h"
34 #include "sanitizer_common/sanitizer_libignore.h"
35 #include "sanitizer_common/sanitizer_suppressions.h"
36 #include "sanitizer_common/sanitizer_thread_registry.h"
37 #include "tsan_clock.h"
38 #include "tsan_defs.h"
39 #include "tsan_flags.h"
40 #include "tsan_sync.h"
41 #include "tsan_trace.h"
42 #include "tsan_vector.h"
43 #include "tsan_report.h"
44 #include "tsan_platform.h"
45 #include "tsan_mutexset.h"
46 #include "tsan_ignoreset.h"
47 #include "tsan_stack_trace.h"
48
49 #if SANITIZER_WORDSIZE != 64
50 # error "ThreadSanitizer is supported only on 64-bit platforms"
51 #endif
52
53 namespace __tsan {
54
55 #if !SANITIZER_GO
56 struct MapUnmapCallback;
57 #if defined(__mips64) || defined(__aarch64__) || defined(__powerpc__)
58 static const uptr kAllocatorSpace = 0;
59 static const uptr kAllocatorSize = SANITIZER_MMAP_RANGE_SIZE;
60 static const uptr kAllocatorRegionSizeLog = 20;
61 static const uptr kAllocatorNumRegions =
62     kAllocatorSize >> kAllocatorRegionSizeLog;
63 typedef TwoLevelByteMap<(kAllocatorNumRegions >> 12), 1 << 12,
64     MapUnmapCallback> ByteMap;
65 typedef SizeClassAllocator32<kAllocatorSpace, kAllocatorSize, 0,
66     CompactSizeClassMap, kAllocatorRegionSizeLog, ByteMap,
67     MapUnmapCallback> PrimaryAllocator;
68 #else
69 struct AP64 {  // Allocator64 parameters. Deliberately using a short name.
70   static const uptr kSpaceBeg = Mapping::kHeapMemBeg;
71   static const uptr kSpaceSize = Mapping::kHeapMemEnd - Mapping::kHeapMemBeg;
72   static const uptr kMetadataSize = 0;
73   typedef DefaultSizeClassMap SizeClassMap;
74   typedef __tsan::MapUnmapCallback MapUnmapCallback;
75   static const uptr kFlags = 0;
76 };
77 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
78 #endif
79 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
80 typedef LargeMmapAllocator<MapUnmapCallback> SecondaryAllocator;
81 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
82     SecondaryAllocator> Allocator;
83 Allocator *allocator();
84 #endif
85
86 void TsanCheckFailed(const char *file, int line, const char *cond,
87                      u64 v1, u64 v2);
88
89 const u64 kShadowRodata = (u64)-1;  // .rodata shadow marker
90
91 // FastState (from most significant bit):
92 //   ignore          : 1
93 //   tid             : kTidBits
94 //   unused          : -
95 //   history_size    : 3
96 //   epoch           : kClkBits
97 class FastState {
98  public:
99   FastState(u64 tid, u64 epoch) {
100     x_ = tid << kTidShift;
101     x_ |= epoch;
102     DCHECK_EQ(tid, this->tid());
103     DCHECK_EQ(epoch, this->epoch());
104     DCHECK_EQ(GetIgnoreBit(), false);
105   }
106
107   explicit FastState(u64 x)
108       : x_(x) {
109   }
110
111   u64 raw() const {
112     return x_;
113   }
114
115   u64 tid() const {
116     u64 res = (x_ & ~kIgnoreBit) >> kTidShift;
117     return res;
118   }
119
120   u64 TidWithIgnore() const {
121     u64 res = x_ >> kTidShift;
122     return res;
123   }
124
125   u64 epoch() const {
126     u64 res = x_ & ((1ull << kClkBits) - 1);
127     return res;
128   }
129
130   void IncrementEpoch() {
131     u64 old_epoch = epoch();
132     x_ += 1;
133     DCHECK_EQ(old_epoch + 1, epoch());
134     (void)old_epoch;
135   }
136
137   void SetIgnoreBit() { x_ |= kIgnoreBit; }
138   void ClearIgnoreBit() { x_ &= ~kIgnoreBit; }
139   bool GetIgnoreBit() const { return (s64)x_ < 0; }
140
141   void SetHistorySize(int hs) {
142     CHECK_GE(hs, 0);
143     CHECK_LE(hs, 7);
144     x_ = (x_ & ~(kHistoryMask << kHistoryShift)) | (u64(hs) << kHistoryShift);
145   }
146
147   ALWAYS_INLINE
148   int GetHistorySize() const {
149     return (int)((x_ >> kHistoryShift) & kHistoryMask);
150   }
151
152   void ClearHistorySize() {
153     SetHistorySize(0);
154   }
155
156   ALWAYS_INLINE
157   u64 GetTracePos() const {
158     const int hs = GetHistorySize();
159     // When hs == 0, the trace consists of 2 parts.
160     const u64 mask = (1ull << (kTracePartSizeBits + hs + 1)) - 1;
161     return epoch() & mask;
162   }
163
164  private:
165   friend class Shadow;
166   static const int kTidShift = 64 - kTidBits - 1;
167   static const u64 kIgnoreBit = 1ull << 63;
168   static const u64 kFreedBit = 1ull << 63;
169   static const u64 kHistoryShift = kClkBits;
170   static const u64 kHistoryMask = 7;
171   u64 x_;
172 };
173
174 // Shadow (from most significant bit):
175 //   freed           : 1
176 //   tid             : kTidBits
177 //   is_atomic       : 1
178 //   is_read         : 1
179 //   size_log        : 2
180 //   addr0           : 3
181 //   epoch           : kClkBits
182 class Shadow : public FastState {
183  public:
184   explicit Shadow(u64 x)
185       : FastState(x) {
186   }
187
188   explicit Shadow(const FastState &s)
189       : FastState(s.x_) {
190     ClearHistorySize();
191   }
192
193   void SetAddr0AndSizeLog(u64 addr0, unsigned kAccessSizeLog) {
194     DCHECK_EQ((x_ >> kClkBits) & 31, 0);
195     DCHECK_LE(addr0, 7);
196     DCHECK_LE(kAccessSizeLog, 3);
197     x_ |= ((kAccessSizeLog << 3) | addr0) << kClkBits;
198     DCHECK_EQ(kAccessSizeLog, size_log());
199     DCHECK_EQ(addr0, this->addr0());
200   }
201
202   void SetWrite(unsigned kAccessIsWrite) {
203     DCHECK_EQ(x_ & kReadBit, 0);
204     if (!kAccessIsWrite)
205       x_ |= kReadBit;
206     DCHECK_EQ(kAccessIsWrite, IsWrite());
207   }
208
209   void SetAtomic(bool kIsAtomic) {
210     DCHECK(!IsAtomic());
211     if (kIsAtomic)
212       x_ |= kAtomicBit;
213     DCHECK_EQ(IsAtomic(), kIsAtomic);
214   }
215
216   bool IsAtomic() const {
217     return x_ & kAtomicBit;
218   }
219
220   bool IsZero() const {
221     return x_ == 0;
222   }
223
224   static inline bool TidsAreEqual(const Shadow s1, const Shadow s2) {
225     u64 shifted_xor = (s1.x_ ^ s2.x_) >> kTidShift;
226     DCHECK_EQ(shifted_xor == 0, s1.TidWithIgnore() == s2.TidWithIgnore());
227     return shifted_xor == 0;
228   }
229
230   static ALWAYS_INLINE
231   bool Addr0AndSizeAreEqual(const Shadow s1, const Shadow s2) {
232     u64 masked_xor = ((s1.x_ ^ s2.x_) >> kClkBits) & 31;
233     return masked_xor == 0;
234   }
235
236   static ALWAYS_INLINE bool TwoRangesIntersect(Shadow s1, Shadow s2,
237       unsigned kS2AccessSize) {
238     bool res = false;
239     u64 diff = s1.addr0() - s2.addr0();
240     if ((s64)diff < 0) {  // s1.addr0 < s2.addr0  // NOLINT
241       // if (s1.addr0() + size1) > s2.addr0()) return true;
242       if (s1.size() > -diff)
243         res = true;
244     } else {
245       // if (s2.addr0() + kS2AccessSize > s1.addr0()) return true;
246       if (kS2AccessSize > diff)
247         res = true;
248     }
249     DCHECK_EQ(res, TwoRangesIntersectSlow(s1, s2));
250     DCHECK_EQ(res, TwoRangesIntersectSlow(s2, s1));
251     return res;
252   }
253
254   u64 ALWAYS_INLINE addr0() const { return (x_ >> kClkBits) & 7; }
255   u64 ALWAYS_INLINE size() const { return 1ull << size_log(); }
256   bool ALWAYS_INLINE IsWrite() const { return !IsRead(); }
257   bool ALWAYS_INLINE IsRead() const { return x_ & kReadBit; }
258
259   // The idea behind the freed bit is as follows.
260   // When the memory is freed (or otherwise unaccessible) we write to the shadow
261   // values with tid/epoch related to the free and the freed bit set.
262   // During memory accesses processing the freed bit is considered
263   // as msb of tid. So any access races with shadow with freed bit set
264   // (it is as if write from a thread with which we never synchronized before).
265   // This allows us to detect accesses to freed memory w/o additional
266   // overheads in memory access processing and at the same time restore
267   // tid/epoch of free.
268   void MarkAsFreed() {
269      x_ |= kFreedBit;
270   }
271
272   bool IsFreed() const {
273     return x_ & kFreedBit;
274   }
275
276   bool GetFreedAndReset() {
277     bool res = x_ & kFreedBit;
278     x_ &= ~kFreedBit;
279     return res;
280   }
281
282   bool ALWAYS_INLINE IsBothReadsOrAtomic(bool kIsWrite, bool kIsAtomic) const {
283     bool v = x_ & ((u64(kIsWrite ^ 1) << kReadShift)
284         | (u64(kIsAtomic) << kAtomicShift));
285     DCHECK_EQ(v, (!IsWrite() && !kIsWrite) || (IsAtomic() && kIsAtomic));
286     return v;
287   }
288
289   bool ALWAYS_INLINE IsRWNotWeaker(bool kIsWrite, bool kIsAtomic) const {
290     bool v = ((x_ >> kReadShift) & 3)
291         <= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
292     DCHECK_EQ(v, (IsAtomic() < kIsAtomic) ||
293         (IsAtomic() == kIsAtomic && !IsWrite() <= !kIsWrite));
294     return v;
295   }
296
297   bool ALWAYS_INLINE IsRWWeakerOrEqual(bool kIsWrite, bool kIsAtomic) const {
298     bool v = ((x_ >> kReadShift) & 3)
299         >= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
300     DCHECK_EQ(v, (IsAtomic() > kIsAtomic) ||
301         (IsAtomic() == kIsAtomic && !IsWrite() >= !kIsWrite));
302     return v;
303   }
304
305  private:
306   static const u64 kReadShift   = 5 + kClkBits;
307   static const u64 kReadBit     = 1ull << kReadShift;
308   static const u64 kAtomicShift = 6 + kClkBits;
309   static const u64 kAtomicBit   = 1ull << kAtomicShift;
310
311   u64 size_log() const { return (x_ >> (3 + kClkBits)) & 3; }
312
313   static bool TwoRangesIntersectSlow(const Shadow s1, const Shadow s2) {
314     if (s1.addr0() == s2.addr0()) return true;
315     if (s1.addr0() < s2.addr0() && s1.addr0() + s1.size() > s2.addr0())
316       return true;
317     if (s2.addr0() < s1.addr0() && s2.addr0() + s2.size() > s1.addr0())
318       return true;
319     return false;
320   }
321 };
322
323 struct ThreadSignalContext;
324
325 struct JmpBuf {
326   uptr sp;
327   uptr mangled_sp;
328   int int_signal_send;
329   bool in_blocking_func;
330   uptr in_signal_handler;
331   uptr *shadow_stack_pos;
332 };
333
334 // A Processor represents a physical thread, or a P for Go.
335 // It is used to store internal resources like allocate cache, and does not
336 // participate in race-detection logic (invisible to end user).
337 // In C++ it is tied to an OS thread just like ThreadState, however ideally
338 // it should be tied to a CPU (this way we will have fewer allocator caches).
339 // In Go it is tied to a P, so there are significantly fewer Processor's than
340 // ThreadState's (which are tied to Gs).
341 // A ThreadState must be wired with a Processor to handle events.
342 struct Processor {
343   ThreadState *thr; // currently wired thread, or nullptr
344 #if !SANITIZER_GO
345   AllocatorCache alloc_cache;
346   InternalAllocatorCache internal_alloc_cache;
347 #endif
348   DenseSlabAllocCache block_cache;
349   DenseSlabAllocCache sync_cache;
350   DenseSlabAllocCache clock_cache;
351   DDPhysicalThread *dd_pt;
352 };
353
354 #if !SANITIZER_GO
355 // ScopedGlobalProcessor temporary setups a global processor for the current
356 // thread, if it does not have one. Intended for interceptors that can run
357 // at the very thread end, when we already destroyed the thread processor.
358 struct ScopedGlobalProcessor {
359   ScopedGlobalProcessor();
360   ~ScopedGlobalProcessor();
361 };
362 #endif
363
364 // This struct is stored in TLS.
365 struct ThreadState {
366   FastState fast_state;
367   // Synch epoch represents the threads's epoch before the last synchronization
368   // action. It allows to reduce number of shadow state updates.
369   // For example, fast_synch_epoch=100, last write to addr X was at epoch=150,
370   // if we are processing write to X from the same thread at epoch=200,
371   // we do nothing, because both writes happen in the same 'synch epoch'.
372   // That is, if another memory access does not race with the former write,
373   // it does not race with the latter as well.
374   // QUESTION: can we can squeeze this into ThreadState::Fast?
375   // E.g. ThreadState::Fast is a 44-bit, 32 are taken by synch_epoch and 12 are
376   // taken by epoch between synchs.
377   // This way we can save one load from tls.
378   u64 fast_synch_epoch;
379   // This is a slow path flag. On fast path, fast_state.GetIgnoreBit() is read.
380   // We do not distinguish beteween ignoring reads and writes
381   // for better performance.
382   int ignore_reads_and_writes;
383   int ignore_sync;
384   int suppress_reports;
385   // Go does not support ignores.
386 #if !SANITIZER_GO
387   IgnoreSet mop_ignore_set;
388   IgnoreSet sync_ignore_set;
389 #endif
390   // C/C++ uses fixed size shadow stack embed into Trace.
391   // Go uses malloc-allocated shadow stack with dynamic size.
392   uptr *shadow_stack;
393   uptr *shadow_stack_end;
394   uptr *shadow_stack_pos;
395   u64 *racy_shadow_addr;
396   u64 racy_state[2];
397   MutexSet mset;
398   ThreadClock clock;
399 #if !SANITIZER_GO
400   Vector<JmpBuf> jmp_bufs;
401   int ignore_interceptors;
402 #endif
403 #if TSAN_COLLECT_STATS
404   u64 stat[StatCnt];
405 #endif
406   const int tid;
407   const int unique_id;
408   bool in_symbolizer;
409   bool in_ignored_lib;
410   bool is_inited;
411   bool is_dead;
412   bool is_freeing;
413   bool is_vptr_access;
414   uptr external_tag;
415   const uptr stk_addr;
416   const uptr stk_size;
417   const uptr tls_addr;
418   const uptr tls_size;
419   ThreadContext *tctx;
420
421 #if SANITIZER_DEBUG && !SANITIZER_GO
422   InternalDeadlockDetector internal_deadlock_detector;
423 #endif
424   DDLogicalThread *dd_lt;
425
426   // Current wired Processor, or nullptr. Required to handle any events.
427   Processor *proc1;
428 #if !SANITIZER_GO
429   Processor *proc() { return proc1; }
430 #else
431   Processor *proc();
432 #endif
433
434   atomic_uintptr_t in_signal_handler;
435   ThreadSignalContext *signal_ctx;
436
437 #if !SANITIZER_GO
438   u32 last_sleep_stack_id;
439   ThreadClock last_sleep_clock;
440 #endif
441
442   // Set in regions of runtime that must be signal-safe and fork-safe.
443   // If set, malloc must not be called.
444   int nomalloc;
445
446   const ReportDesc *current_report;
447
448   explicit ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
449                        unsigned reuse_count,
450                        uptr stk_addr, uptr stk_size,
451                        uptr tls_addr, uptr tls_size);
452 };
453
454 #if !SANITIZER_GO
455 #if SANITIZER_MAC || SANITIZER_ANDROID
456 ThreadState *cur_thread();
457 void cur_thread_finalize();
458 #else
459 __attribute__((tls_model("initial-exec")))
460 extern THREADLOCAL char cur_thread_placeholder[];
461 INLINE ThreadState *cur_thread() {
462   return reinterpret_cast<ThreadState *>(&cur_thread_placeholder);
463 }
464 INLINE void cur_thread_finalize() { }
465 #endif  // SANITIZER_MAC || SANITIZER_ANDROID
466 #endif  // SANITIZER_GO
467
468 class ThreadContext : public ThreadContextBase {
469  public:
470   explicit ThreadContext(int tid);
471   ~ThreadContext();
472   ThreadState *thr;
473   u32 creation_stack_id;
474   SyncClock sync;
475   // Epoch at which the thread had started.
476   // If we see an event from the thread stamped by an older epoch,
477   // the event is from a dead thread that shared tid with this thread.
478   u64 epoch0;
479   u64 epoch1;
480
481   // Override superclass callbacks.
482   void OnDead() override;
483   void OnJoined(void *arg) override;
484   void OnFinished() override;
485   void OnStarted(void *arg) override;
486   void OnCreated(void *arg) override;
487   void OnReset() override;
488   void OnDetached(void *arg) override;
489 };
490
491 struct RacyStacks {
492   MD5Hash hash[2];
493   bool operator==(const RacyStacks &other) const {
494     if (hash[0] == other.hash[0] && hash[1] == other.hash[1])
495       return true;
496     if (hash[0] == other.hash[1] && hash[1] == other.hash[0])
497       return true;
498     return false;
499   }
500 };
501
502 struct RacyAddress {
503   uptr addr_min;
504   uptr addr_max;
505 };
506
507 struct FiredSuppression {
508   ReportType type;
509   uptr pc_or_addr;
510   Suppression *supp;
511 };
512
513 struct Context {
514   Context();
515
516   bool initialized;
517   bool after_multithreaded_fork;
518
519   MetaMap metamap;
520
521   Mutex report_mtx;
522   int nreported;
523   int nmissed_expected;
524   atomic_uint64_t last_symbolize_time_ns;
525
526   void *background_thread;
527   atomic_uint32_t stop_background_thread;
528
529   ThreadRegistry *thread_registry;
530
531   Mutex racy_mtx;
532   Vector<RacyStacks> racy_stacks;
533   Vector<RacyAddress> racy_addresses;
534   // Number of fired suppressions may be large enough.
535   Mutex fired_suppressions_mtx;
536   InternalMmapVector<FiredSuppression> fired_suppressions;
537   DDetector *dd;
538
539   ClockAlloc clock_alloc;
540
541   Flags flags;
542
543   u64 stat[StatCnt];
544   u64 int_alloc_cnt[MBlockTypeCount];
545   u64 int_alloc_siz[MBlockTypeCount];
546 };
547
548 extern Context *ctx;  // The one and the only global runtime context.
549
550 ALWAYS_INLINE Flags *flags() {
551   return &ctx->flags;
552 }
553
554 struct ScopedIgnoreInterceptors {
555   ScopedIgnoreInterceptors() {
556 #if !SANITIZER_GO
557     cur_thread()->ignore_interceptors++;
558 #endif
559   }
560
561   ~ScopedIgnoreInterceptors() {
562 #if !SANITIZER_GO
563     cur_thread()->ignore_interceptors--;
564 #endif
565   }
566 };
567
568 class ScopedReport {
569  public:
570   explicit ScopedReport(ReportType typ);
571   ~ScopedReport();
572
573   void AddMemoryAccess(uptr addr, uptr external_tag, Shadow s, StackTrace stack,
574                        const MutexSet *mset);
575   void AddStack(StackTrace stack, bool suppressable = false);
576   void AddThread(const ThreadContext *tctx, bool suppressable = false);
577   void AddThread(int unique_tid, bool suppressable = false);
578   void AddUniqueTid(int unique_tid);
579   void AddMutex(const SyncVar *s);
580   u64 AddMutex(u64 id);
581   void AddLocation(uptr addr, uptr size);
582   void AddSleep(u32 stack_id);
583   void SetCount(int count);
584
585   const ReportDesc *GetReport() const;
586
587  private:
588   ReportDesc *rep_;
589   // Symbolizer makes lots of intercepted calls. If we try to process them,
590   // at best it will cause deadlocks on internal mutexes.
591   ScopedIgnoreInterceptors ignore_interceptors_;
592
593   void AddDeadMutex(u64 id);
594
595   ScopedReport(const ScopedReport&);
596   void operator = (const ScopedReport&);
597 };
598
599 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack);
600 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
601                   MutexSet *mset);
602
603 template<typename StackTraceTy>
604 void ObtainCurrentStack(ThreadState *thr, uptr toppc, StackTraceTy *stack) {
605   uptr size = thr->shadow_stack_pos - thr->shadow_stack;
606   uptr start = 0;
607   if (size + !!toppc > kStackTraceMax) {
608     start = size + !!toppc - kStackTraceMax;
609     size = kStackTraceMax - !!toppc;
610   }
611   stack->Init(&thr->shadow_stack[start], size, toppc);
612 }
613
614
615 #if TSAN_COLLECT_STATS
616 void StatAggregate(u64 *dst, u64 *src);
617 void StatOutput(u64 *stat);
618 #endif
619
620 void ALWAYS_INLINE StatInc(ThreadState *thr, StatType typ, u64 n = 1) {
621 #if TSAN_COLLECT_STATS
622   thr->stat[typ] += n;
623 #endif
624 }
625 void ALWAYS_INLINE StatSet(ThreadState *thr, StatType typ, u64 n) {
626 #if TSAN_COLLECT_STATS
627   thr->stat[typ] = n;
628 #endif
629 }
630
631 void MapShadow(uptr addr, uptr size);
632 void MapThreadTrace(uptr addr, uptr size, const char *name);
633 void DontNeedShadowFor(uptr addr, uptr size);
634 void InitializeShadowMemory();
635 void InitializeInterceptors();
636 void InitializeLibIgnore();
637 void InitializeDynamicAnnotations();
638
639 void ForkBefore(ThreadState *thr, uptr pc);
640 void ForkParentAfter(ThreadState *thr, uptr pc);
641 void ForkChildAfter(ThreadState *thr, uptr pc);
642
643 void ReportRace(ThreadState *thr);
644 bool OutputReport(ThreadState *thr, const ScopedReport &srep);
645 bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace);
646 bool IsExpectedReport(uptr addr, uptr size);
647 void PrintMatchedBenignRaces();
648
649 const char *GetObjectTypeFromTag(uptr tag);
650
651 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 1
652 # define DPrintf Printf
653 #else
654 # define DPrintf(...)
655 #endif
656
657 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 2
658 # define DPrintf2 Printf
659 #else
660 # define DPrintf2(...)
661 #endif
662
663 u32 CurrentStackId(ThreadState *thr, uptr pc);
664 ReportStack *SymbolizeStackId(u32 stack_id);
665 void PrintCurrentStack(ThreadState *thr, uptr pc);
666 void PrintCurrentStackSlow(uptr pc);  // uses libunwind
667
668 void Initialize(ThreadState *thr);
669 int Finalize(ThreadState *thr);
670
671 void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write);
672 void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write);
673
674 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
675     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic);
676 void MemoryAccessImpl(ThreadState *thr, uptr addr,
677     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
678     u64 *shadow_mem, Shadow cur);
679 void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
680     uptr size, bool is_write);
681 void MemoryAccessRangeStep(ThreadState *thr, uptr pc, uptr addr,
682     uptr size, uptr step, bool is_write);
683 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
684     int size, bool kAccessIsWrite, bool kIsAtomic);
685
686 const int kSizeLog1 = 0;
687 const int kSizeLog2 = 1;
688 const int kSizeLog4 = 2;
689 const int kSizeLog8 = 3;
690
691 void ALWAYS_INLINE MemoryRead(ThreadState *thr, uptr pc,
692                                      uptr addr, int kAccessSizeLog) {
693   MemoryAccess(thr, pc, addr, kAccessSizeLog, false, false);
694 }
695
696 void ALWAYS_INLINE MemoryWrite(ThreadState *thr, uptr pc,
697                                       uptr addr, int kAccessSizeLog) {
698   MemoryAccess(thr, pc, addr, kAccessSizeLog, true, false);
699 }
700
701 void ALWAYS_INLINE MemoryReadAtomic(ThreadState *thr, uptr pc,
702                                            uptr addr, int kAccessSizeLog) {
703   MemoryAccess(thr, pc, addr, kAccessSizeLog, false, true);
704 }
705
706 void ALWAYS_INLINE MemoryWriteAtomic(ThreadState *thr, uptr pc,
707                                             uptr addr, int kAccessSizeLog) {
708   MemoryAccess(thr, pc, addr, kAccessSizeLog, true, true);
709 }
710
711 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size);
712 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size);
713 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size);
714
715 void ThreadIgnoreBegin(ThreadState *thr, uptr pc, bool save_stack = true);
716 void ThreadIgnoreEnd(ThreadState *thr, uptr pc);
717 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc, bool save_stack = true);
718 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc);
719
720 void FuncEntry(ThreadState *thr, uptr pc);
721 void FuncExit(ThreadState *thr);
722
723 int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached);
724 void ThreadStart(ThreadState *thr, int tid, tid_t os_id, bool workerthread);
725 void ThreadFinish(ThreadState *thr);
726 int ThreadTid(ThreadState *thr, uptr pc, uptr uid);
727 void ThreadJoin(ThreadState *thr, uptr pc, int tid);
728 void ThreadDetach(ThreadState *thr, uptr pc, int tid);
729 void ThreadFinalize(ThreadState *thr);
730 void ThreadSetName(ThreadState *thr, const char *name);
731 int ThreadCount(ThreadState *thr);
732 void ProcessPendingSignals(ThreadState *thr);
733
734 Processor *ProcCreate();
735 void ProcDestroy(Processor *proc);
736 void ProcWire(Processor *proc, ThreadState *thr);
737 void ProcUnwire(Processor *proc, ThreadState *thr);
738
739 // Note: the parameter is called flagz, because flags is already taken
740 // by the global function that returns flags.
741 void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
742 void MutexDestroy(ThreadState *thr, uptr pc, uptr addr);
743 void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
744 void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0,
745     int rec = 1);
746 int  MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
747 void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
748 void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
749 void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr);
750 void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr);
751 void MutexRepair(ThreadState *thr, uptr pc, uptr addr);  // call on EOWNERDEAD
752 void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr);
753
754 void Acquire(ThreadState *thr, uptr pc, uptr addr);
755 // AcquireGlobal synchronizes the current thread with all other threads.
756 // In terms of happens-before relation, it draws a HB edge from all threads
757 // (where they happen to execute right now) to the current thread. We use it to
758 // handle Go finalizers. Namely, finalizer goroutine executes AcquireGlobal
759 // right before executing finalizers. This provides a coarse, but simple
760 // approximation of the actual required synchronization.
761 void AcquireGlobal(ThreadState *thr, uptr pc);
762 void Release(ThreadState *thr, uptr pc, uptr addr);
763 void ReleaseStore(ThreadState *thr, uptr pc, uptr addr);
764 void AfterSleep(ThreadState *thr, uptr pc);
765 void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
766 void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
767 void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c);
768 void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
769
770 // The hacky call uses custom calling convention and an assembly thunk.
771 // It is considerably faster that a normal call for the caller
772 // if it is not executed (it is intended for slow paths from hot functions).
773 // The trick is that the call preserves all registers and the compiler
774 // does not treat it as a call.
775 // If it does not work for you, use normal call.
776 #if !SANITIZER_DEBUG && defined(__x86_64__) && !SANITIZER_MAC
777 // The caller may not create the stack frame for itself at all,
778 // so we create a reserve stack frame for it (1024b must be enough).
779 #define HACKY_CALL(f) \
780   __asm__ __volatile__("sub $1024, %%rsp;" \
781                        CFI_INL_ADJUST_CFA_OFFSET(1024) \
782                        ".hidden " #f "_thunk;" \
783                        "call " #f "_thunk;" \
784                        "add $1024, %%rsp;" \
785                        CFI_INL_ADJUST_CFA_OFFSET(-1024) \
786                        ::: "memory", "cc");
787 #else
788 #define HACKY_CALL(f) f()
789 #endif
790
791 void TraceSwitch(ThreadState *thr);
792 uptr TraceTopPC(ThreadState *thr);
793 uptr TraceSize();
794 uptr TraceParts();
795 Trace *ThreadTrace(int tid);
796
797 extern "C" void __tsan_trace_switch();
798 void ALWAYS_INLINE TraceAddEvent(ThreadState *thr, FastState fs,
799                                         EventType typ, u64 addr) {
800   if (!kCollectHistory)
801     return;
802   DCHECK_GE((int)typ, 0);
803   DCHECK_LE((int)typ, 7);
804   DCHECK_EQ(GetLsb(addr, 61), addr);
805   StatInc(thr, StatEvents);
806   u64 pos = fs.GetTracePos();
807   if (UNLIKELY((pos % kTracePartSize) == 0)) {
808 #if !SANITIZER_GO
809     HACKY_CALL(__tsan_trace_switch);
810 #else
811     TraceSwitch(thr);
812 #endif
813   }
814   Event *trace = (Event*)GetThreadTrace(fs.tid());
815   Event *evp = &trace[pos];
816   Event ev = (u64)addr | ((u64)typ << 61);
817   *evp = ev;
818 }
819
820 #if !SANITIZER_GO
821 uptr ALWAYS_INLINE HeapEnd() {
822   return HeapMemEnd() + PrimaryAllocator::AdditionalSize();
823 }
824 #endif
825
826 }  // namespace __tsan
827
828 #endif  // TSAN_RTL_H