1 //===-- tsan_rtl.h ----------------------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of ThreadSanitizer (TSan), a race detector.
9 //
10 // Main internal TSan header file.
11 //
12 // Ground rules:
13 //   - C++ run-time should not be used (static CTORs, RTTI, exceptions, static
14 //     function-scope locals)
15 //   - All functions/classes/etc reside in namespace __tsan, except for those
16 //     declared in tsan_interface.h.
17 //   - Platform-specific files should be used instead of ifdefs (*).
18 //   - No system headers included in header files (*).
19 //   - Platform specific headres included only into platform-specific files (*).
20 //
21 //  (*) Except when inlining is critical for performance.
22 //===----------------------------------------------------------------------===//
23 
24 #ifndef TSAN_RTL_H
25 #define TSAN_RTL_H
26 
27 #include "sanitizer_common/sanitizer_allocator.h"
28 #include "sanitizer_common/sanitizer_allocator_internal.h"
29 #include "sanitizer_common/sanitizer_asm.h"
30 #include "sanitizer_common/sanitizer_common.h"
31 #include "sanitizer_common/sanitizer_libignore.h"
32 #include "sanitizer_common/sanitizer_suppressions.h"
33 #include "sanitizer_common/sanitizer_thread_registry.h"
34 #include "tsan_clock.h"
35 #include "tsan_defs.h"
36 #include "tsan_flags.h"
37 #include "tsan_sync.h"
38 #include "tsan_trace.h"
39 #include "tsan_vector.h"
40 #include "tsan_report.h"
41 #include "tsan_platform.h"
42 #include "tsan_mutexset.h"
43 #include "tsan_ignoreset.h"
44 
45 #if SANITIZER_WORDSIZE != 64
46 # error "ThreadSanitizer is supported only on 64-bit platforms"
47 #endif
48 
49 namespace __tsan {
50 
51 // Descriptor of user's memory block.
52 struct MBlock {
53   /*
54   u64 mtx : 1;  // must be first
55   u64 lst : 44;
56   u64 stk : 31;  // on word boundary
57   u64 tid : kTidBits;
58   u64 siz : 128 - 1 - 31 - 44 - kTidBits;  // 39
59   */
60   u64 raw[2];
61 
InitMBlock62   void Init(uptr siz, u32 tid, u32 stk) {
63     raw[0] = raw[1] = 0;
64     raw[1] |= (u64)siz << ((1 + 44 + 31 + kTidBits) % 64);
65     raw[1] |= (u64)tid << ((1 + 44 + 31) % 64);
66     raw[0] |= (u64)stk << (1 + 44);
67     raw[1] |= (u64)stk >> (64 - 44 - 1);
68     DCHECK_EQ(Size(), siz);
69     DCHECK_EQ(Tid(), tid);
70     DCHECK_EQ(StackId(), stk);
71   }
72 
TidMBlock73   u32 Tid() const {
74     return GetLsb(raw[1] >> ((1 + 44 + 31) % 64), kTidBits);
75   }
76 
SizeMBlock77   uptr Size() const {
78     return raw[1] >> ((1 + 31 + 44 + kTidBits) % 64);
79   }
80 
StackIdMBlock81   u32 StackId() const {
82     return (raw[0] >> (1 + 44)) | GetLsb(raw[1] << (64 - 44 - 1), 31);
83   }
84 
ListHeadMBlock85   SyncVar *ListHead() const {
86     return (SyncVar*)(GetLsb(raw[0] >> 1, 44) << 3);
87   }
88 
ListPushMBlock89   void ListPush(SyncVar *v) {
90     SyncVar *lst = ListHead();
91     v->next = lst;
92     u64 x = (u64)v ^ (u64)lst;
93     x = (x >> 3) << 1;
94     raw[0] ^= x;
95     DCHECK_EQ(ListHead(), v);
96   }
97 
ListPopMBlock98   SyncVar *ListPop() {
99     SyncVar *lst = ListHead();
100     SyncVar *nxt = lst->next;
101     lst->next = 0;
102     u64 x = (u64)lst ^ (u64)nxt;
103     x = (x >> 3) << 1;
104     raw[0] ^= x;
105     DCHECK_EQ(ListHead(), nxt);
106     return lst;
107   }
108 
ListResetMBlock109   void ListReset() {
110     SyncVar *lst = ListHead();
111     u64 x = (u64)lst;
112     x = (x >> 3) << 1;
113     raw[0] ^= x;
114     DCHECK_EQ(ListHead(), 0);
115   }
116 
117   void Lock();
118   void Unlock();
119   typedef GenericScopedLock<MBlock> ScopedLock;
120 };
121 
122 #ifndef TSAN_GO
123 #if defined(TSAN_COMPAT_SHADOW) && TSAN_COMPAT_SHADOW
124 const uptr kAllocatorSpace = 0x7d0000000000ULL;
125 #else
126 const uptr kAllocatorSpace = 0x7d0000000000ULL;
127 #endif
128 const uptr kAllocatorSize  =  0x10000000000ULL;  // 1T.
129 
130 struct MapUnmapCallback;
131 typedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, sizeof(MBlock),
132     DefaultSizeClassMap, MapUnmapCallback> PrimaryAllocator;
133 typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
134 typedef LargeMmapAllocator<MapUnmapCallback> SecondaryAllocator;
135 typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
136     SecondaryAllocator> Allocator;
137 Allocator *allocator();
138 #endif
139 
140 void TsanCheckFailed(const char *file, int line, const char *cond,
141                      u64 v1, u64 v2);
142 
143 const u64 kShadowRodata = (u64)-1;  // .rodata shadow marker
144 
145 // FastState (from most significant bit):
146 //   ignore          : 1
147 //   tid             : kTidBits
148 //   epoch           : kClkBits
149 //   unused          : -
150 //   history_size    : 3
151 class FastState {
152  public:
FastState(u64 tid,u64 epoch)153   FastState(u64 tid, u64 epoch) {
154     x_ = tid << kTidShift;
155     x_ |= epoch << kClkShift;
156     DCHECK_EQ(tid, this->tid());
157     DCHECK_EQ(epoch, this->epoch());
158     DCHECK_EQ(GetIgnoreBit(), false);
159   }
160 
FastState(u64 x)161   explicit FastState(u64 x)
162       : x_(x) {
163   }
164 
raw()165   u64 raw() const {
166     return x_;
167   }
168 
tid()169   u64 tid() const {
170     u64 res = (x_ & ~kIgnoreBit) >> kTidShift;
171     return res;
172   }
173 
TidWithIgnore()174   u64 TidWithIgnore() const {
175     u64 res = x_ >> kTidShift;
176     return res;
177   }
178 
epoch()179   u64 epoch() const {
180     u64 res = (x_ << (kTidBits + 1)) >> (64 - kClkBits);
181     return res;
182   }
183 
IncrementEpoch()184   void IncrementEpoch() {
185     u64 old_epoch = epoch();
186     x_ += 1 << kClkShift;
187     DCHECK_EQ(old_epoch + 1, epoch());
188     (void)old_epoch;
189   }
190 
SetIgnoreBit()191   void SetIgnoreBit() { x_ |= kIgnoreBit; }
ClearIgnoreBit()192   void ClearIgnoreBit() { x_ &= ~kIgnoreBit; }
GetIgnoreBit()193   bool GetIgnoreBit() const { return (s64)x_ < 0; }
194 
SetHistorySize(int hs)195   void SetHistorySize(int hs) {
196     CHECK_GE(hs, 0);
197     CHECK_LE(hs, 7);
198     x_ = (x_ & ~7) | hs;
199   }
200 
GetHistorySize()201   int GetHistorySize() const {
202     return (int)(x_ & 7);
203   }
204 
ClearHistorySize()205   void ClearHistorySize() {
206     x_ &= ~7;
207   }
208 
GetTracePos()209   u64 GetTracePos() const {
210     const int hs = GetHistorySize();
211     // When hs == 0, the trace consists of 2 parts.
212     const u64 mask = (1ull << (kTracePartSizeBits + hs + 1)) - 1;
213     return epoch() & mask;
214   }
215 
216  private:
217   friend class Shadow;
218   static const int kTidShift = 64 - kTidBits - 1;
219   static const int kClkShift = kTidShift - kClkBits;
220   static const u64 kIgnoreBit = 1ull << 63;
221   static const u64 kFreedBit = 1ull << 63;
222   u64 x_;
223 };
224 
225 // Shadow (from most significant bit):
226 //   freed           : 1
227 //   tid             : kTidBits
228 //   epoch           : kClkBits
229 //   is_atomic       : 1
230 //   is_read         : 1
231 //   size_log        : 2
232 //   addr0           : 3
233 class Shadow : public FastState {
234  public:
Shadow(u64 x)235   explicit Shadow(u64 x)
236       : FastState(x) {
237   }
238 
Shadow(const FastState & s)239   explicit Shadow(const FastState &s)
240       : FastState(s.x_) {
241     ClearHistorySize();
242   }
243 
SetAddr0AndSizeLog(u64 addr0,unsigned kAccessSizeLog)244   void SetAddr0AndSizeLog(u64 addr0, unsigned kAccessSizeLog) {
245     DCHECK_EQ(x_ & 31, 0);
246     DCHECK_LE(addr0, 7);
247     DCHECK_LE(kAccessSizeLog, 3);
248     x_ |= (kAccessSizeLog << 3) | addr0;
249     DCHECK_EQ(kAccessSizeLog, size_log());
250     DCHECK_EQ(addr0, this->addr0());
251   }
252 
SetWrite(unsigned kAccessIsWrite)253   void SetWrite(unsigned kAccessIsWrite) {
254     DCHECK_EQ(x_ & kReadBit, 0);
255     if (!kAccessIsWrite)
256       x_ |= kReadBit;
257     DCHECK_EQ(kAccessIsWrite, IsWrite());
258   }
259 
SetAtomic(bool kIsAtomic)260   void SetAtomic(bool kIsAtomic) {
261     DCHECK(!IsAtomic());
262     if (kIsAtomic)
263       x_ |= kAtomicBit;
264     DCHECK_EQ(IsAtomic(), kIsAtomic);
265   }
266 
IsAtomic()267   bool IsAtomic() const {
268     return x_ & kAtomicBit;
269   }
270 
IsZero()271   bool IsZero() const {
272     return x_ == 0;
273   }
274 
TidsAreEqual(const Shadow s1,const Shadow s2)275   static inline bool TidsAreEqual(const Shadow s1, const Shadow s2) {
276     u64 shifted_xor = (s1.x_ ^ s2.x_) >> kTidShift;
277     DCHECK_EQ(shifted_xor == 0, s1.TidWithIgnore() == s2.TidWithIgnore());
278     return shifted_xor == 0;
279   }
280 
Addr0AndSizeAreEqual(const Shadow s1,const Shadow s2)281   static inline bool Addr0AndSizeAreEqual(const Shadow s1, const Shadow s2) {
282     u64 masked_xor = (s1.x_ ^ s2.x_) & 31;
283     return masked_xor == 0;
284   }
285 
TwoRangesIntersect(Shadow s1,Shadow s2,unsigned kS2AccessSize)286   static inline bool TwoRangesIntersect(Shadow s1, Shadow s2,
287       unsigned kS2AccessSize) {
288     bool res = false;
289     u64 diff = s1.addr0() - s2.addr0();
290     if ((s64)diff < 0) {  // s1.addr0 < s2.addr0  // NOLINT
291       // if (s1.addr0() + size1) > s2.addr0()) return true;
292       if (s1.size() > -diff)  res = true;
293     } else {
294       // if (s2.addr0() + kS2AccessSize > s1.addr0()) return true;
295       if (kS2AccessSize > diff) res = true;
296     }
297     DCHECK_EQ(res, TwoRangesIntersectSLOW(s1, s2));
298     DCHECK_EQ(res, TwoRangesIntersectSLOW(s2, s1));
299     return res;
300   }
301 
302   // The idea behind the offset is as follows.
303   // Consider that we have 8 bool's contained within a single 8-byte block
304   // (mapped to a single shadow "cell"). Now consider that we write to the bools
305   // from a single thread (which we consider the common case).
306   // W/o offsetting each access will have to scan 4 shadow values at average
307   // to find the corresponding shadow value for the bool.
308   // With offsetting we start scanning shadow with the offset so that
309   // each access hits necessary shadow straight off (at least in an expected
310   // optimistic case).
311   // This logic works seamlessly for any layout of user data. For example,
312   // if user data is {int, short, char, char}, then accesses to the int are
313   // offsetted to 0, short - 4, 1st char - 6, 2nd char - 7. Hopefully, accesses
314   // from a single thread won't need to scan all 8 shadow values.
ComputeSearchOffset()315   unsigned ComputeSearchOffset() {
316     return x_ & 7;
317   }
addr0()318   u64 addr0() const { return x_ & 7; }
size()319   u64 size() const { return 1ull << size_log(); }
IsWrite()320   bool IsWrite() const { return !IsRead(); }
IsRead()321   bool IsRead() const { return x_ & kReadBit; }
322 
323   // The idea behind the freed bit is as follows.
324   // When the memory is freed (or otherwise unaccessible) we write to the shadow
325   // values with tid/epoch related to the free and the freed bit set.
326   // During memory accesses processing the freed bit is considered
327   // as msb of tid. So any access races with shadow with freed bit set
328   // (it is as if write from a thread with which we never synchronized before).
329   // This allows us to detect accesses to freed memory w/o additional
330   // overheads in memory access processing and at the same time restore
331   // tid/epoch of free.
MarkAsFreed()332   void MarkAsFreed() {
333      x_ |= kFreedBit;
334   }
335 
IsFreed()336   bool IsFreed() const {
337     return x_ & kFreedBit;
338   }
339 
GetFreedAndReset()340   bool GetFreedAndReset() {
341     bool res = x_ & kFreedBit;
342     x_ &= ~kFreedBit;
343     return res;
344   }
345 
IsBothReadsOrAtomic(bool kIsWrite,bool kIsAtomic)346   bool IsBothReadsOrAtomic(bool kIsWrite, bool kIsAtomic) const {
347     // analyzes 5-th bit (is_read) and 6-th bit (is_atomic)
348     bool v = x_ & u64(((kIsWrite ^ 1) << kReadShift)
349         | (kIsAtomic << kAtomicShift));
350     DCHECK_EQ(v, (!IsWrite() && !kIsWrite) || (IsAtomic() && kIsAtomic));
351     return v;
352   }
353 
IsRWNotWeaker(bool kIsWrite,bool kIsAtomic)354   bool IsRWNotWeaker(bool kIsWrite, bool kIsAtomic) const {
355     bool v = ((x_ >> kReadShift) & 3)
356         <= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
357     DCHECK_EQ(v, (IsAtomic() < kIsAtomic) ||
358         (IsAtomic() == kIsAtomic && !IsWrite() <= !kIsWrite));
359     return v;
360   }
361 
IsRWWeakerOrEqual(bool kIsWrite,bool kIsAtomic)362   bool IsRWWeakerOrEqual(bool kIsWrite, bool kIsAtomic) const {
363     bool v = ((x_ >> kReadShift) & 3)
364         >= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
365     DCHECK_EQ(v, (IsAtomic() > kIsAtomic) ||
366         (IsAtomic() == kIsAtomic && !IsWrite() >= !kIsWrite));
367     return v;
368   }
369 
370  private:
371   static const u64 kReadShift   = 5;
372   static const u64 kReadBit     = 1ull << kReadShift;
373   static const u64 kAtomicShift = 6;
374   static const u64 kAtomicBit   = 1ull << kAtomicShift;
375 
size_log()376   u64 size_log() const { return (x_ >> 3) & 3; }
377 
TwoRangesIntersectSLOW(const Shadow s1,const Shadow s2)378   static bool TwoRangesIntersectSLOW(const Shadow s1, const Shadow s2) {
379     if (s1.addr0() == s2.addr0()) return true;
380     if (s1.addr0() < s2.addr0() && s1.addr0() + s1.size() > s2.addr0())
381       return true;
382     if (s2.addr0() < s1.addr0() && s2.addr0() + s2.size() > s1.addr0())
383       return true;
384     return false;
385   }
386 };
387 
388 struct SignalContext;
389 
390 struct JmpBuf {
391   uptr sp;
392   uptr mangled_sp;
393   uptr *shadow_stack_pos;
394 };
395 
396 // This struct is stored in TLS.
397 struct ThreadState {
398   FastState fast_state;
399   // Synch epoch represents the threads's epoch before the last synchronization
400   // action. It allows to reduce number of shadow state updates.
401   // For example, fast_synch_epoch=100, last write to addr X was at epoch=150,
402   // if we are processing write to X from the same thread at epoch=200,
403   // we do nothing, because both writes happen in the same 'synch epoch'.
404   // That is, if another memory access does not race with the former write,
405   // it does not race with the latter as well.
406   // QUESTION: can we can squeeze this into ThreadState::Fast?
407   // E.g. ThreadState::Fast is a 44-bit, 32 are taken by synch_epoch and 12 are
408   // taken by epoch between synchs.
409   // This way we can save one load from tls.
410   u64 fast_synch_epoch;
411   // This is a slow path flag. On fast path, fast_state.GetIgnoreBit() is read.
412   // We do not distinguish beteween ignoring reads and writes
413   // for better performance.
414   int ignore_reads_and_writes;
415   int ignore_sync;
416   // Go does not support ignores.
417 #ifndef TSAN_GO
418   IgnoreSet mop_ignore_set;
419   IgnoreSet sync_ignore_set;
420 #endif
421   // C/C++ uses fixed size shadow stack embed into Trace.
422   // Go uses malloc-allocated shadow stack with dynamic size.
423   uptr *shadow_stack;
424   uptr *shadow_stack_end;
425   uptr *shadow_stack_pos;
426   u64 *racy_shadow_addr;
427   u64 racy_state[2];
428   MutexSet mset;
429   ThreadClock clock;
430 #ifndef TSAN_GO
431   AllocatorCache alloc_cache;
432   InternalAllocatorCache internal_alloc_cache;
433   Vector<JmpBuf> jmp_bufs;
434 #endif
435   u64 stat[StatCnt];
436   const int tid;
437   const int unique_id;
438   int in_rtl;
439   bool in_symbolizer;
440   bool in_ignored_lib;
441   bool is_alive;
442   bool is_freeing;
443   bool is_vptr_access;
444   const uptr stk_addr;
445   const uptr stk_size;
446   const uptr tls_addr;
447   const uptr tls_size;
448   ThreadContext *tctx;
449 
450   DeadlockDetector deadlock_detector;
451 
452   bool in_signal_handler;
453   SignalContext *signal_ctx;
454 
455 #ifndef TSAN_GO
456   u32 last_sleep_stack_id;
457   ThreadClock last_sleep_clock;
458 #endif
459 
460   // Set in regions of runtime that must be signal-safe and fork-safe.
461   // If set, malloc must not be called.
462   int nomalloc;
463 
464   explicit ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
465                        uptr stk_addr, uptr stk_size,
466                        uptr tls_addr, uptr tls_size);
467 };
468 
469 Context *CTX();
470 
471 #ifndef TSAN_GO
472 extern THREADLOCAL char cur_thread_placeholder[];
cur_thread()473 INLINE ThreadState *cur_thread() {
474   return reinterpret_cast<ThreadState *>(&cur_thread_placeholder);
475 }
476 #endif
477 
478 class ThreadContext : public ThreadContextBase {
479  public:
480   explicit ThreadContext(int tid);
481   ~ThreadContext();
482   ThreadState *thr;
483 #ifdef TSAN_GO
484   StackTrace creation_stack;
485 #else
486   u32 creation_stack_id;
487 #endif
488   SyncClock sync;
489   // Epoch at which the thread had started.
490   // If we see an event from the thread stamped by an older epoch,
491   // the event is from a dead thread that shared tid with this thread.
492   u64 epoch0;
493   u64 epoch1;
494 
495   // Override superclass callbacks.
496   void OnDead();
497   void OnJoined(void *arg);
498   void OnFinished();
499   void OnStarted(void *arg);
500   void OnCreated(void *arg);
501   void OnReset();
502 };
503 
504 struct RacyStacks {
505   MD5Hash hash[2];
506   bool operator==(const RacyStacks &other) const {
507     if (hash[0] == other.hash[0] && hash[1] == other.hash[1])
508       return true;
509     if (hash[0] == other.hash[1] && hash[1] == other.hash[0])
510       return true;
511     return false;
512   }
513 };
514 
515 struct RacyAddress {
516   uptr addr_min;
517   uptr addr_max;
518 };
519 
520 struct FiredSuppression {
521   ReportType type;
522   uptr pc;
523   Suppression *supp;
524 };
525 
526 struct Context {
527   Context();
528 
529   bool initialized;
530 
531   SyncTab synctab;
532 
533   Mutex report_mtx;
534   int nreported;
535   int nmissed_expected;
536   atomic_uint64_t last_symbolize_time_ns;
537 
538   ThreadRegistry *thread_registry;
539 
540   Vector<RacyStacks> racy_stacks;
541   Vector<RacyAddress> racy_addresses;
542   // Number of fired suppressions may be large enough.
543   InternalMmapVector<FiredSuppression> fired_suppressions;
544 
545   Flags flags;
546 
547   u64 stat[StatCnt];
548   u64 int_alloc_cnt[MBlockTypeCount];
549   u64 int_alloc_siz[MBlockTypeCount];
550 };
551 
552 class ScopedInRtl {
553  public:
554   ScopedInRtl();
555   ~ScopedInRtl();
556  private:
557   ThreadState*thr_;
558   int in_rtl_;
559   int errno_;
560 };
561 
562 class ScopedReport {
563  public:
564   explicit ScopedReport(ReportType typ);
565   ~ScopedReport();
566 
567   void AddStack(const StackTrace *stack);
568   void AddMemoryAccess(uptr addr, Shadow s, const StackTrace *stack,
569                        const MutexSet *mset);
570   void AddThread(const ThreadContext *tctx);
571   void AddMutex(const SyncVar *s);
572   void AddLocation(uptr addr, uptr size);
573   void AddSleep(u32 stack_id);
574   void SetCount(int count);
575 
576   const ReportDesc *GetReport() const;
577 
578  private:
579   Context *ctx_;
580   ReportDesc *rep_;
581 
582   void AddMutex(u64 id);
583 
584   ScopedReport(const ScopedReport&);
585   void operator = (const ScopedReport&);
586 };
587 
588 void RestoreStack(int tid, const u64 epoch, StackTrace *stk, MutexSet *mset);
589 
590 void StatAggregate(u64 *dst, u64 *src);
591 void StatOutput(u64 *stat);
592 void ALWAYS_INLINE StatInc(ThreadState *thr, StatType typ, u64 n = 1) {
593   if (kCollectStats)
594     thr->stat[typ] += n;
595 }
StatSet(ThreadState * thr,StatType typ,u64 n)596 void ALWAYS_INLINE StatSet(ThreadState *thr, StatType typ, u64 n) {
597   if (kCollectStats)
598     thr->stat[typ] = n;
599 }
600 
601 void MapShadow(uptr addr, uptr size);
602 void MapThreadTrace(uptr addr, uptr size);
603 void DontNeedShadowFor(uptr addr, uptr size);
604 void InitializeShadowMemory();
605 void InitializeInterceptors();
606 void InitializeLibIgnore();
607 void InitializeDynamicAnnotations();
608 
609 void ReportRace(ThreadState *thr);
610 bool OutputReport(Context *ctx,
611                   const ScopedReport &srep,
612                   const ReportStack *suppress_stack1 = 0,
613                   const ReportStack *suppress_stack2 = 0,
614                   const ReportLocation *suppress_loc = 0);
615 bool IsFiredSuppression(Context *ctx,
616                         const ScopedReport &srep,
617                         const StackTrace &trace);
618 bool IsExpectedReport(uptr addr, uptr size);
619 void PrintMatchedBenignRaces();
620 bool FrameIsInternal(const ReportStack *frame);
621 ReportStack *SkipTsanInternalFrames(ReportStack *ent);
622 
623 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 1
624 # define DPrintf Printf
625 #else
626 # define DPrintf(...)
627 #endif
628 
629 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 2
630 # define DPrintf2 Printf
631 #else
632 # define DPrintf2(...)
633 #endif
634 
635 u32 CurrentStackId(ThreadState *thr, uptr pc);
636 ReportStack *SymbolizeStackId(u32 stack_id);
637 void PrintCurrentStack(ThreadState *thr, uptr pc);
638 void PrintCurrentStackSlow();  // uses libunwind
639 
640 void Initialize(ThreadState *thr);
641 int Finalize(ThreadState *thr);
642 
643 SyncVar* GetJavaSync(ThreadState *thr, uptr pc, uptr addr,
644                      bool write_lock, bool create);
645 SyncVar* GetAndRemoveJavaSync(ThreadState *thr, uptr pc, uptr addr);
646 
647 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
648     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic);
649 void MemoryAccessImpl(ThreadState *thr, uptr addr,
650     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
651     u64 *shadow_mem, Shadow cur);
652 void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
653     uptr size, bool is_write);
654 void MemoryAccessRangeStep(ThreadState *thr, uptr pc, uptr addr,
655     uptr size, uptr step, bool is_write);
656 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr,
657     int size, bool kAccessIsWrite, bool kIsAtomic);
658 
659 const int kSizeLog1 = 0;
660 const int kSizeLog2 = 1;
661 const int kSizeLog4 = 2;
662 const int kSizeLog8 = 3;
663 
MemoryRead(ThreadState * thr,uptr pc,uptr addr,int kAccessSizeLog)664 void ALWAYS_INLINE MemoryRead(ThreadState *thr, uptr pc,
665                                      uptr addr, int kAccessSizeLog) {
666   MemoryAccess(thr, pc, addr, kAccessSizeLog, false, false);
667 }
668 
MemoryWrite(ThreadState * thr,uptr pc,uptr addr,int kAccessSizeLog)669 void ALWAYS_INLINE MemoryWrite(ThreadState *thr, uptr pc,
670                                       uptr addr, int kAccessSizeLog) {
671   MemoryAccess(thr, pc, addr, kAccessSizeLog, true, false);
672 }
673 
MemoryReadAtomic(ThreadState * thr,uptr pc,uptr addr,int kAccessSizeLog)674 void ALWAYS_INLINE MemoryReadAtomic(ThreadState *thr, uptr pc,
675                                            uptr addr, int kAccessSizeLog) {
676   MemoryAccess(thr, pc, addr, kAccessSizeLog, false, true);
677 }
678 
MemoryWriteAtomic(ThreadState * thr,uptr pc,uptr addr,int kAccessSizeLog)679 void ALWAYS_INLINE MemoryWriteAtomic(ThreadState *thr, uptr pc,
680                                             uptr addr, int kAccessSizeLog) {
681   MemoryAccess(thr, pc, addr, kAccessSizeLog, true, true);
682 }
683 
684 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size);
685 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size);
686 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size);
687 
688 void ThreadIgnoreBegin(ThreadState *thr, uptr pc);
689 void ThreadIgnoreEnd(ThreadState *thr, uptr pc);
690 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc);
691 void ThreadIgnoreSyncEnd(ThreadState *thr, uptr pc);
692 
693 void FuncEntry(ThreadState *thr, uptr pc);
694 void FuncExit(ThreadState *thr);
695 
696 int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached);
697 void ThreadStart(ThreadState *thr, int tid, uptr os_id);
698 void ThreadFinish(ThreadState *thr);
699 int ThreadTid(ThreadState *thr, uptr pc, uptr uid);
700 void ThreadJoin(ThreadState *thr, uptr pc, int tid);
701 void ThreadDetach(ThreadState *thr, uptr pc, int tid);
702 void ThreadFinalize(ThreadState *thr);
703 void ThreadSetName(ThreadState *thr, const char *name);
704 int ThreadCount(ThreadState *thr);
705 void ProcessPendingSignals(ThreadState *thr);
706 
707 void MutexCreate(ThreadState *thr, uptr pc, uptr addr,
708                  bool rw, bool recursive, bool linker_init);
709 void MutexDestroy(ThreadState *thr, uptr pc, uptr addr);
710 void MutexLock(ThreadState *thr, uptr pc, uptr addr, int rec = 1);
711 int  MutexUnlock(ThreadState *thr, uptr pc, uptr addr, bool all = false);
712 void MutexReadLock(ThreadState *thr, uptr pc, uptr addr);
713 void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr);
714 void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr);
715 void MutexRepair(ThreadState *thr, uptr pc, uptr addr);  // call on EOWNERDEAD
716 
717 void Acquire(ThreadState *thr, uptr pc, uptr addr);
718 void AcquireGlobal(ThreadState *thr, uptr pc);
719 void Release(ThreadState *thr, uptr pc, uptr addr);
720 void ReleaseStore(ThreadState *thr, uptr pc, uptr addr);
721 void AfterSleep(ThreadState *thr, uptr pc);
722 void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
723 void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
724 void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c);
725 void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
726 
727 // The hacky call uses custom calling convention and an assembly thunk.
728 // It is considerably faster that a normal call for the caller
729 // if it is not executed (it is intended for slow paths from hot functions).
730 // The trick is that the call preserves all registers and the compiler
731 // does not treat it as a call.
732 // If it does not work for you, use normal call.
733 #if TSAN_DEBUG == 0
734 // The caller may not create the stack frame for itself at all,
735 // so we create a reserve stack frame for it (1024b must be enough).
736 #define HACKY_CALL(f) \
737   __asm__ __volatile__("sub $1024, %%rsp;" \
738                        CFI_INL_ADJUST_CFA_OFFSET(1024) \
739                        ".hidden " #f "_thunk;" \
740                        "call " #f "_thunk;" \
741                        "add $1024, %%rsp;" \
742                        CFI_INL_ADJUST_CFA_OFFSET(-1024) \
743                        ::: "memory", "cc");
744 #else
745 #define HACKY_CALL(f) f()
746 #endif
747 
748 void TraceSwitch(ThreadState *thr);
749 uptr TraceTopPC(ThreadState *thr);
750 uptr TraceSize();
751 uptr TraceParts();
752 Trace *ThreadTrace(int tid);
753 
754 extern "C" void __tsan_trace_switch();
TraceAddEvent(ThreadState * thr,FastState fs,EventType typ,u64 addr)755 void ALWAYS_INLINE TraceAddEvent(ThreadState *thr, FastState fs,
756                                         EventType typ, u64 addr) {
757   DCHECK_GE((int)typ, 0);
758   DCHECK_LE((int)typ, 7);
759   DCHECK_EQ(GetLsb(addr, 61), addr);
760   StatInc(thr, StatEvents);
761   u64 pos = fs.GetTracePos();
762   if (UNLIKELY((pos % kTracePartSize) == 0)) {
763 #ifndef TSAN_GO
764     HACKY_CALL(__tsan_trace_switch);
765 #else
766     TraceSwitch(thr);
767 #endif
768   }
769   Event *trace = (Event*)GetThreadTrace(fs.tid());
770   Event *evp = &trace[pos];
771   Event ev = (u64)addr | ((u64)typ << 61);
772   *evp = ev;
773 }
774 
775 }  // namespace __tsan
776 
777 #endif  // TSAN_RTL_H
778