1 //===-- tsan_rtl.h ----------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 //
11 // Main internal TSan header file.
12 //
13 // Ground rules:
14 //   - C++ run-time should not be used (static CTORs, RTTI, exceptions, static
15 //     function-scope locals)
16 //   - All functions/classes/etc reside in namespace __tsan, except for those
17 //     declared in tsan_interface.h.
18 //   - Platform-specific files should be used instead of ifdefs (*).
19 //   - No system headers included in header files (*).
20 //   - Platform specific headres included only into platform-specific files (*).
21 //
22 //  (*) Except when inlining is critical for performance.
23 //===----------------------------------------------------------------------===//
24 
25 #ifndef TSAN_RTL_H
26 #define TSAN_RTL_H
27 
28 #include "sanitizer_common/sanitizer_allocator.h"
29 #include "sanitizer_common/sanitizer_allocator_internal.h"
30 #include "sanitizer_common/sanitizer_asm.h"
31 #include "sanitizer_common/sanitizer_common.h"
32 #include "sanitizer_common/sanitizer_deadlock_detector_interface.h"
33 #include "sanitizer_common/sanitizer_libignore.h"
34 #include "sanitizer_common/sanitizer_suppressions.h"
35 #include "sanitizer_common/sanitizer_thread_registry.h"
36 #include "sanitizer_common/sanitizer_vector.h"
37 #include "tsan_clock.h"
38 #include "tsan_defs.h"
39 #include "tsan_flags.h"
40 #include "tsan_ignoreset.h"
41 #include "tsan_mman.h"
42 #include "tsan_mutexset.h"
43 #include "tsan_platform.h"
44 #include "tsan_report.h"
45 #include "tsan_shadow.h"
46 #include "tsan_stack_trace.h"
47 #include "tsan_sync.h"
48 #include "tsan_trace.h"
49 
50 #if SANITIZER_WORDSIZE != 64
51 # error "ThreadSanitizer is supported only on 64-bit platforms"
52 #endif
53 
54 namespace __tsan {
55 
56 #if !SANITIZER_GO
57 struct MapUnmapCallback;
58 #if defined(__mips64) || defined(__aarch64__) || defined(__powerpc__)
59 
60 struct AP32 {
61   static const uptr kSpaceBeg = 0;
62   static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
63   static const uptr kMetadataSize = 0;
64   typedef __sanitizer::CompactSizeClassMap SizeClassMap;
65   static const uptr kRegionSizeLog = 20;
66   using AddressSpaceView = LocalAddressSpaceView;
67   typedef __tsan::MapUnmapCallback MapUnmapCallback;
68   static const uptr kFlags = 0;
69 };
70 typedef SizeClassAllocator32<AP32> PrimaryAllocator;
71 #else
72 struct AP64 {  // Allocator64 parameters. Deliberately using a short name.
73 #    if defined(__s390x__)
74   typedef MappingS390x Mapping;
75 #    else
76   typedef Mapping48AddressSpace Mapping;
77 #    endif
78   static const uptr kSpaceBeg = Mapping::kHeapMemBeg;
79   static const uptr kSpaceSize = Mapping::kHeapMemEnd - Mapping::kHeapMemBeg;
80   static const uptr kMetadataSize = 0;
81   typedef DefaultSizeClassMap SizeClassMap;
82   typedef __tsan::MapUnmapCallback MapUnmapCallback;
83   static const uptr kFlags = 0;
84   using AddressSpaceView = LocalAddressSpaceView;
85 };
86 typedef SizeClassAllocator64<AP64> PrimaryAllocator;
87 #endif
88 typedef CombinedAllocator<PrimaryAllocator> Allocator;
89 typedef Allocator::AllocatorCache AllocatorCache;
90 Allocator *allocator();
91 #endif
92 
93 struct ThreadSignalContext;
94 
95 struct JmpBuf {
96   uptr sp;
97   int int_signal_send;
98   bool in_blocking_func;
99   uptr in_signal_handler;
100   uptr *shadow_stack_pos;
101 };
102 
103 // A Processor represents a physical thread, or a P for Go.
104 // It is used to store internal resources like allocate cache, and does not
105 // participate in race-detection logic (invisible to end user).
106 // In C++ it is tied to an OS thread just like ThreadState, however ideally
107 // it should be tied to a CPU (this way we will have fewer allocator caches).
108 // In Go it is tied to a P, so there are significantly fewer Processor's than
109 // ThreadState's (which are tied to Gs).
110 // A ThreadState must be wired with a Processor to handle events.
111 struct Processor {
112   ThreadState *thr; // currently wired thread, or nullptr
113 #if !SANITIZER_GO
114   AllocatorCache alloc_cache;
115   InternalAllocatorCache internal_alloc_cache;
116 #endif
117   DenseSlabAllocCache block_cache;
118   DenseSlabAllocCache sync_cache;
119   DenseSlabAllocCache clock_cache;
120   DDPhysicalThread *dd_pt;
121 };
122 
123 #if !SANITIZER_GO
124 // ScopedGlobalProcessor temporary setups a global processor for the current
125 // thread, if it does not have one. Intended for interceptors that can run
126 // at the very thread end, when we already destroyed the thread processor.
127 struct ScopedGlobalProcessor {
128   ScopedGlobalProcessor();
129   ~ScopedGlobalProcessor();
130 };
131 #endif
132 
133 // This struct is stored in TLS.
134 struct ThreadState {
135   FastState fast_state;
136   // Synch epoch represents the threads's epoch before the last synchronization
137   // action. It allows to reduce number of shadow state updates.
138   // For example, fast_synch_epoch=100, last write to addr X was at epoch=150,
139   // if we are processing write to X from the same thread at epoch=200,
140   // we do nothing, because both writes happen in the same 'synch epoch'.
141   // That is, if another memory access does not race with the former write,
142   // it does not race with the latter as well.
143   // QUESTION: can we can squeeze this into ThreadState::Fast?
144   // E.g. ThreadState::Fast is a 44-bit, 32 are taken by synch_epoch and 12 are
145   // taken by epoch between synchs.
146   // This way we can save one load from tls.
147   u64 fast_synch_epoch;
148   // Technically `current` should be a separate THREADLOCAL variable;
149   // but it is placed here in order to share cache line with previous fields.
150   ThreadState* current;
151   // This is a slow path flag. On fast path, fast_state.GetIgnoreBit() is read.
152   // We do not distinguish beteween ignoring reads and writes
153   // for better performance.
154   int ignore_reads_and_writes;
155   atomic_sint32_t pending_signals;
156   int ignore_sync;
157   int suppress_reports;
158   // Go does not support ignores.
159 #if !SANITIZER_GO
160   IgnoreSet mop_ignore_set;
161   IgnoreSet sync_ignore_set;
162 #endif
163   uptr *shadow_stack;
164   uptr *shadow_stack_end;
165   uptr *shadow_stack_pos;
166   RawShadow *racy_shadow_addr;
167   RawShadow racy_state[2];
168   MutexSet mset;
169   ThreadClock clock;
170 #if !SANITIZER_GO
171   Vector<JmpBuf> jmp_bufs;
172   int ignore_interceptors;
173 #endif
174   const Tid tid;
175   const int unique_id;
176   bool in_symbolizer;
177   bool in_ignored_lib;
178   bool is_inited;
179   bool is_dead;
180   bool is_freeing;
181   bool is_vptr_access;
182   const uptr stk_addr;
183   const uptr stk_size;
184   const uptr tls_addr;
185   const uptr tls_size;
186   ThreadContext *tctx;
187 
188   DDLogicalThread *dd_lt;
189 
190   // Current wired Processor, or nullptr. Required to handle any events.
191   Processor *proc1;
192 #if !SANITIZER_GO
procThreadState193   Processor *proc() { return proc1; }
194 #else
195   Processor *proc();
196 #endif
197 
198   atomic_uintptr_t in_signal_handler;
199   ThreadSignalContext *signal_ctx;
200 
201 #if !SANITIZER_GO
202   StackID last_sleep_stack_id;
203   ThreadClock last_sleep_clock;
204 #endif
205 
206   // Set in regions of runtime that must be signal-safe and fork-safe.
207   // If set, malloc must not be called.
208   int nomalloc;
209 
210   const ReportDesc *current_report;
211 
212   // Current position in tctx->trace.Back()->events (Event*).
213   atomic_uintptr_t trace_pos;
214   // PC of the last memory access, used to compute PC deltas in the trace.
215   uptr trace_prev_pc;
216   Sid sid;
217   Epoch epoch;
218 
219   explicit ThreadState(Context *ctx, Tid tid, int unique_id, u64 epoch,
220                        unsigned reuse_count, uptr stk_addr, uptr stk_size,
221                        uptr tls_addr, uptr tls_size);
222 } ALIGNED(SANITIZER_CACHE_LINE_SIZE);
223 
224 #if !SANITIZER_GO
225 #if SANITIZER_APPLE || SANITIZER_ANDROID
226 ThreadState *cur_thread();
227 void set_cur_thread(ThreadState *thr);
228 void cur_thread_finalize();
cur_thread_init()229 inline ThreadState *cur_thread_init() { return cur_thread(); }
230 #  else
231 __attribute__((tls_model("initial-exec")))
232 extern THREADLOCAL char cur_thread_placeholder[];
cur_thread()233 inline ThreadState *cur_thread() {
234   return reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current;
235 }
cur_thread_init()236 inline ThreadState *cur_thread_init() {
237   ThreadState *thr = reinterpret_cast<ThreadState *>(cur_thread_placeholder);
238   if (UNLIKELY(!thr->current))
239     thr->current = thr;
240   return thr->current;
241 }
set_cur_thread(ThreadState * thr)242 inline void set_cur_thread(ThreadState *thr) {
243   reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current = thr;
244 }
cur_thread_finalize()245 inline void cur_thread_finalize() { }
246 #  endif  // SANITIZER_APPLE || SANITIZER_ANDROID
247 #endif  // SANITIZER_GO
248 
249 class ThreadContext final : public ThreadContextBase {
250  public:
251   explicit ThreadContext(Tid tid);
252   ~ThreadContext();
253   ThreadState *thr;
254   StackID creation_stack_id;
255   SyncClock sync;
256   // Epoch at which the thread had started.
257   // If we see an event from the thread stamped by an older epoch,
258   // the event is from a dead thread that shared tid with this thread.
259   u64 epoch0;
260   u64 epoch1;
261 
262   v3::Trace trace;
263 
264   // Override superclass callbacks.
265   void OnDead() override;
266   void OnJoined(void *arg) override;
267   void OnFinished() override;
268   void OnStarted(void *arg) override;
269   void OnCreated(void *arg) override;
270   void OnReset() override;
271   void OnDetached(void *arg) override;
272 };
273 
274 struct RacyStacks {
275   MD5Hash hash[2];
276   bool operator==(const RacyStacks &other) const;
277 };
278 
279 struct RacyAddress {
280   uptr addr_min;
281   uptr addr_max;
282 };
283 
284 struct FiredSuppression {
285   ReportType type;
286   uptr pc_or_addr;
287   Suppression *supp;
288 };
289 
290 struct Context {
291   Context();
292 
293   bool initialized;
294 #if !SANITIZER_GO
295   bool after_multithreaded_fork;
296 #endif
297 
298   MetaMap metamap;
299 
300   Mutex report_mtx;
301   int nreported;
302   atomic_uint64_t last_symbolize_time_ns;
303 
304   void *background_thread;
305   atomic_uint32_t stop_background_thread;
306 
307   ThreadRegistry thread_registry;
308 
309   Mutex racy_mtx;
310   Vector<RacyStacks> racy_stacks;
311   Vector<RacyAddress> racy_addresses;
312   // Number of fired suppressions may be large enough.
313   Mutex fired_suppressions_mtx;
314   InternalMmapVector<FiredSuppression> fired_suppressions;
315   DDetector *dd;
316 
317   ClockAlloc clock_alloc;
318 
319   Flags flags;
320   fd_t memprof_fd;
321 
322   Mutex slot_mtx;
323 };
324 
325 extern Context *ctx;  // The one and the only global runtime context.
326 
flags()327 ALWAYS_INLINE Flags *flags() {
328   return &ctx->flags;
329 }
330 
331 struct ScopedIgnoreInterceptors {
ScopedIgnoreInterceptorsScopedIgnoreInterceptors332   ScopedIgnoreInterceptors() {
333 #if !SANITIZER_GO
334     cur_thread()->ignore_interceptors++;
335 #endif
336   }
337 
~ScopedIgnoreInterceptorsScopedIgnoreInterceptors338   ~ScopedIgnoreInterceptors() {
339 #if !SANITIZER_GO
340     cur_thread()->ignore_interceptors--;
341 #endif
342   }
343 };
344 
345 const char *GetObjectTypeFromTag(uptr tag);
346 const char *GetReportHeaderFromTag(uptr tag);
347 uptr TagFromShadowStackFrame(uptr pc);
348 
349 class ScopedReportBase {
350  public:
351   void AddMemoryAccess(uptr addr, uptr external_tag, Shadow s, StackTrace stack,
352                        const MutexSet *mset);
353   void AddStack(StackTrace stack, bool suppressable = false);
354   void AddThread(const ThreadContext *tctx, bool suppressable = false);
355   void AddThread(Tid unique_tid, bool suppressable = false);
356   void AddUniqueTid(Tid unique_tid);
357   void AddMutex(const SyncVar *s);
358   u64 AddMutex(u64 id);
359   void AddLocation(uptr addr, uptr size);
360   void AddSleep(StackID stack_id);
361   void SetCount(int count);
362 
363   const ReportDesc *GetReport() const;
364 
365  protected:
366   ScopedReportBase(ReportType typ, uptr tag);
367   ~ScopedReportBase();
368 
369  private:
370   ReportDesc *rep_;
371   // Symbolizer makes lots of intercepted calls. If we try to process them,
372   // at best it will cause deadlocks on internal mutexes.
373   ScopedIgnoreInterceptors ignore_interceptors_;
374 
375   void AddDeadMutex(u64 id);
376 
377   ScopedReportBase(const ScopedReportBase &) = delete;
378   void operator=(const ScopedReportBase &) = delete;
379 };
380 
381 class ScopedReport : public ScopedReportBase {
382  public:
383   explicit ScopedReport(ReportType typ, uptr tag = kExternalTagNone);
384   ~ScopedReport();
385 
386  private:
387   ScopedErrorReportLock lock_;
388 };
389 
390 bool ShouldReport(ThreadState *thr, ReportType typ);
391 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack);
392 void RestoreStack(Tid tid, const u64 epoch, VarSizeStackTrace *stk,
393                   MutexSet *mset, uptr *tag = nullptr);
394 
395 // The stack could look like:
396 //   <start> | <main> | <foo> | tag | <bar>
397 // This will extract the tag and keep:
398 //   <start> | <main> | <foo> | <bar>
399 template<typename StackTraceTy>
400 void ExtractTagFromStack(StackTraceTy *stack, uptr *tag = nullptr) {
401   if (stack->size < 2) return;
402   uptr possible_tag_pc = stack->trace[stack->size - 2];
403   uptr possible_tag = TagFromShadowStackFrame(possible_tag_pc);
404   if (possible_tag == kExternalTagNone) return;
405   stack->trace_buffer[stack->size - 2] = stack->trace_buffer[stack->size - 1];
406   stack->size -= 1;
407   if (tag) *tag = possible_tag;
408 }
409 
410 template<typename StackTraceTy>
411 void ObtainCurrentStack(ThreadState *thr, uptr toppc, StackTraceTy *stack,
412                         uptr *tag = nullptr) {
413   uptr size = thr->shadow_stack_pos - thr->shadow_stack;
414   uptr start = 0;
415   if (size + !!toppc > kStackTraceMax) {
416     start = size + !!toppc - kStackTraceMax;
417     size = kStackTraceMax - !!toppc;
418   }
419   stack->Init(&thr->shadow_stack[start], size, toppc);
420   ExtractTagFromStack(stack, tag);
421 }
422 
423 #define GET_STACK_TRACE_FATAL(thr, pc) \
424   VarSizeStackTrace stack; \
425   ObtainCurrentStack(thr, pc, &stack); \
426   stack.ReverseOrder();
427 
428 void MapShadow(uptr addr, uptr size);
429 void MapThreadTrace(uptr addr, uptr size, const char *name);
430 void DontNeedShadowFor(uptr addr, uptr size);
431 void UnmapShadow(ThreadState *thr, uptr addr, uptr size);
432 void InitializeShadowMemory();
433 void InitializeInterceptors();
434 void InitializeLibIgnore();
435 void InitializeDynamicAnnotations();
436 
437 void ForkBefore(ThreadState *thr, uptr pc);
438 void ForkParentAfter(ThreadState *thr, uptr pc);
439 void ForkChildAfter(ThreadState *thr, uptr pc, bool start_thread);
440 
441 void ReportRace(ThreadState *thr);
442 bool OutputReport(ThreadState *thr, const ScopedReport &srep);
443 bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace);
444 bool IsExpectedReport(uptr addr, uptr size);
445 
446 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 1
447 # define DPrintf Printf
448 #else
449 # define DPrintf(...)
450 #endif
451 
452 #if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 2
453 # define DPrintf2 Printf
454 #else
455 # define DPrintf2(...)
456 #endif
457 
458 StackID CurrentStackId(ThreadState *thr, uptr pc);
459 ReportStack *SymbolizeStackId(StackID stack_id);
460 void PrintCurrentStack(ThreadState *thr, uptr pc);
461 void PrintCurrentStackSlow(uptr pc);  // uses libunwind
462 MBlock *JavaHeapBlock(uptr addr, uptr *start);
463 
464 void Initialize(ThreadState *thr);
465 void MaybeSpawnBackgroundThread();
466 int Finalize(ThreadState *thr);
467 
468 void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write);
469 void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write);
470 
471 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
472     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic);
473 void MemoryAccessImpl(ThreadState *thr, uptr addr,
474     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
475     u64 *shadow_mem, Shadow cur);
476 void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
477     uptr size, bool is_write);
478 void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
479                            AccessType typ);
480 
481 const int kSizeLog1 = 0;
482 const int kSizeLog2 = 1;
483 const int kSizeLog4 = 2;
484 const int kSizeLog8 = 3;
485 
486 ALWAYS_INLINE
MemoryAccess(ThreadState * thr,uptr pc,uptr addr,uptr size,AccessType typ)487 void MemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
488                   AccessType typ) {
489   int size_log;
490   switch (size) {
491     case 1:
492       size_log = kSizeLog1;
493       break;
494     case 2:
495       size_log = kSizeLog2;
496       break;
497     case 4:
498       size_log = kSizeLog4;
499       break;
500     default:
501       DCHECK_EQ(size, 8);
502       size_log = kSizeLog8;
503       break;
504   }
505   bool is_write = !(typ & kAccessRead);
506   bool is_atomic = typ & kAccessAtomic;
507   if (typ & kAccessVptr)
508     thr->is_vptr_access = true;
509   if (typ & kAccessFree)
510     thr->is_freeing = true;
511   MemoryAccess(thr, pc, addr, size_log, is_write, is_atomic);
512   if (typ & kAccessVptr)
513     thr->is_vptr_access = false;
514   if (typ & kAccessFree)
515     thr->is_freeing = false;
516 }
517 
518 void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size);
519 void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size);
520 void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size);
521 void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
522                                          uptr size);
523 
524 void ThreadIgnoreBegin(ThreadState *thr, uptr pc);
525 void ThreadIgnoreEnd(ThreadState *thr);
526 void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc);
527 void ThreadIgnoreSyncEnd(ThreadState *thr);
528 
529 void FuncEntry(ThreadState *thr, uptr pc);
530 void FuncExit(ThreadState *thr);
531 
532 Tid ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached);
533 void ThreadStart(ThreadState *thr, Tid tid, tid_t os_id,
534                  ThreadType thread_type);
535 void ThreadFinish(ThreadState *thr);
536 Tid ThreadConsumeTid(ThreadState *thr, uptr pc, uptr uid);
537 void ThreadJoin(ThreadState *thr, uptr pc, Tid tid);
538 void ThreadDetach(ThreadState *thr, uptr pc, Tid tid);
539 void ThreadFinalize(ThreadState *thr);
540 void ThreadSetName(ThreadState *thr, const char *name);
541 int ThreadCount(ThreadState *thr);
542 void ProcessPendingSignalsImpl(ThreadState *thr);
543 void ThreadNotJoined(ThreadState *thr, uptr pc, Tid tid, uptr uid);
544 
545 Processor *ProcCreate();
546 void ProcDestroy(Processor *proc);
547 void ProcWire(Processor *proc, ThreadState *thr);
548 void ProcUnwire(Processor *proc, ThreadState *thr);
549 
550 // Note: the parameter is called flagz, because flags is already taken
551 // by the global function that returns flags.
552 void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
553 void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
554 void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
555 void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0,
556     int rec = 1);
557 int  MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
558 void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
559 void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
560 void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr);
561 void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr);
562 void MutexRepair(ThreadState *thr, uptr pc, uptr addr);  // call on EOWNERDEAD
563 void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr);
564 
565 void Acquire(ThreadState *thr, uptr pc, uptr addr);
566 // AcquireGlobal synchronizes the current thread with all other threads.
567 // In terms of happens-before relation, it draws a HB edge from all threads
568 // (where they happen to execute right now) to the current thread. We use it to
569 // handle Go finalizers. Namely, finalizer goroutine executes AcquireGlobal
570 // right before executing finalizers. This provides a coarse, but simple
571 // approximation of the actual required synchronization.
572 void AcquireGlobal(ThreadState *thr);
573 void Release(ThreadState *thr, uptr pc, uptr addr);
574 void ReleaseStoreAcquire(ThreadState *thr, uptr pc, uptr addr);
575 void ReleaseStore(ThreadState *thr, uptr pc, uptr addr);
576 void AfterSleep(ThreadState *thr, uptr pc);
577 void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
578 void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
579 void ReleaseStoreAcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
580 void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c);
581 void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
582 
583 // The hacky call uses custom calling convention and an assembly thunk.
584 // It is considerably faster that a normal call for the caller
585 // if it is not executed (it is intended for slow paths from hot functions).
586 // The trick is that the call preserves all registers and the compiler
587 // does not treat it as a call.
588 // If it does not work for you, use normal call.
589 #if !SANITIZER_DEBUG && defined(__x86_64__) && !SANITIZER_APPLE
590 // The caller may not create the stack frame for itself at all,
591 // so we create a reserve stack frame for it (1024b must be enough).
592 #define HACKY_CALL(f) \
593   __asm__ __volatile__("sub $1024, %%rsp;" \
594                        CFI_INL_ADJUST_CFA_OFFSET(1024) \
595                        ".hidden " #f "_thunk;" \
596                        "call " #f "_thunk;" \
597                        "add $1024, %%rsp;" \
598                        CFI_INL_ADJUST_CFA_OFFSET(-1024) \
599                        ::: "memory", "cc");
600 #else
601 #define HACKY_CALL(f) f()
602 #endif
603 
604 void TraceSwitch(ThreadState *thr);
605 uptr TraceTopPC(ThreadState *thr);
606 uptr TraceSize();
607 uptr TraceParts();
608 Trace *ThreadTrace(Tid tid);
609 
610 extern "C" void __tsan_trace_switch();
TraceAddEvent(ThreadState * thr,FastState fs,EventType typ,u64 addr)611 void ALWAYS_INLINE TraceAddEvent(ThreadState *thr, FastState fs,
612                                         EventType typ, u64 addr) {
613   if (!kCollectHistory)
614     return;
615   // TraceSwitch accesses shadow_stack, but it's called infrequently,
616   // so we check it here proactively.
617   DCHECK(thr->shadow_stack);
618   DCHECK_GE((int)typ, 0);
619   DCHECK_LE((int)typ, 7);
620   DCHECK_EQ(GetLsb(addr, kEventPCBits), addr);
621   u64 pos = fs.GetTracePos();
622   if (UNLIKELY((pos % kTracePartSize) == 0)) {
623 #if !SANITIZER_GO
624     HACKY_CALL(__tsan_trace_switch);
625 #else
626     TraceSwitch(thr);
627 #endif
628   }
629   Event *trace = (Event*)GetThreadTrace(fs.tid());
630   Event *evp = &trace[pos];
631   Event ev = (u64)addr | ((u64)typ << kEventPCBits);
632   *evp = ev;
633 }
634 
635 #if !SANITIZER_GO
HeapEnd()636 uptr ALWAYS_INLINE HeapEnd() {
637   return HeapMemEnd() + PrimaryAllocator::AdditionalSize();
638 }
639 #endif
640 
641 ThreadState *FiberCreate(ThreadState *thr, uptr pc, unsigned flags);
642 void FiberDestroy(ThreadState *thr, uptr pc, ThreadState *fiber);
643 void FiberSwitch(ThreadState *thr, uptr pc, ThreadState *fiber, unsigned flags);
644 
645 // These need to match __tsan_switch_to_fiber_* flags defined in
646 // tsan_interface.h. See documentation there as well.
647 enum FiberSwitchFlags {
648   FiberSwitchFlagNoSync = 1 << 0, // __tsan_switch_to_fiber_no_sync
649 };
650 
ProcessPendingSignals(ThreadState * thr)651 ALWAYS_INLINE void ProcessPendingSignals(ThreadState *thr) {
652   if (UNLIKELY(atomic_load_relaxed(&thr->pending_signals)))
653     ProcessPendingSignalsImpl(thr);
654 }
655 
656 extern bool is_initialized;
657 
658 ALWAYS_INLINE
LazyInitialize(ThreadState * thr)659 void LazyInitialize(ThreadState *thr) {
660   // If we can use .preinit_array, assume that __tsan_init
661   // called from .preinit_array initializes runtime before
662   // any instrumented code.
663 #if !SANITIZER_CAN_USE_PREINIT_ARRAY
664   if (UNLIKELY(!is_initialized))
665     Initialize(thr);
666 #endif
667 }
668 
669 namespace v3 {
670 
671 void TraceSwitchPart(ThreadState *thr);
672 bool RestoreStack(Tid tid, EventType type, Sid sid, Epoch epoch, uptr addr,
673                   uptr size, AccessType typ, VarSizeStackTrace *pstk,
674                   MutexSet *pmset, uptr *ptag);
675 
676 template <typename EventT>
TraceAcquire(ThreadState * thr,EventT ** ev)677 ALWAYS_INLINE WARN_UNUSED_RESULT bool TraceAcquire(ThreadState *thr,
678                                                    EventT **ev) {
679   Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
680 #if SANITIZER_DEBUG
681   // TraceSwitch acquires these mutexes,
682   // so we lock them here to detect deadlocks more reliably.
683   { Lock lock(&ctx->slot_mtx); }
684   { Lock lock(&thr->tctx->trace.mtx); }
685   TracePart *current = thr->tctx->trace.parts.Back();
686   if (current) {
687     DCHECK_GE(pos, &current->events[0]);
688     DCHECK_LE(pos, &current->events[TracePart::kSize]);
689   } else {
690     DCHECK_EQ(pos, nullptr);
691   }
692 #endif
693   // TracePart is allocated with mmap and is at least 4K aligned.
694   // So the following check is a faster way to check for part end.
695   // It may have false positives in the middle of the trace,
696   // they are filtered out in TraceSwitch.
697   if (UNLIKELY(((uptr)(pos + 1) & TracePart::kAlignment) == 0))
698     return false;
699   *ev = reinterpret_cast<EventT *>(pos);
700   return true;
701 }
702 
703 template <typename EventT>
TraceRelease(ThreadState * thr,EventT * evp)704 ALWAYS_INLINE void TraceRelease(ThreadState *thr, EventT *evp) {
705   DCHECK_LE(evp + 1, &thr->tctx->trace.parts.Back()->events[TracePart::kSize]);
706   atomic_store_relaxed(&thr->trace_pos, (uptr)(evp + 1));
707 }
708 
709 template <typename EventT>
TraceEvent(ThreadState * thr,EventT ev)710 void TraceEvent(ThreadState *thr, EventT ev) {
711   EventT *evp;
712   if (!TraceAcquire(thr, &evp)) {
713     TraceSwitchPart(thr);
714     UNUSED bool res = TraceAcquire(thr, &evp);
715     DCHECK(res);
716   }
717   *evp = ev;
718   TraceRelease(thr, evp);
719 }
720 
721 ALWAYS_INLINE WARN_UNUSED_RESULT bool TryTraceFunc(ThreadState *thr,
722                                                    uptr pc = 0) {
723   if (!kCollectHistory)
724     return true;
725   EventFunc *ev;
726   if (UNLIKELY(!TraceAcquire(thr, &ev)))
727     return false;
728   ev->is_access = 0;
729   ev->is_func = 1;
730   ev->pc = pc;
731   TraceRelease(thr, ev);
732   return true;
733 }
734 
735 WARN_UNUSED_RESULT
736 bool TryTraceMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
737                           AccessType typ);
738 WARN_UNUSED_RESULT
739 bool TryTraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
740                                AccessType typ);
741 void TraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
742                             AccessType typ);
743 void TraceFunc(ThreadState *thr, uptr pc = 0);
744 void TraceMutexLock(ThreadState *thr, EventType type, uptr pc, uptr addr,
745                     StackID stk);
746 void TraceMutexUnlock(ThreadState *thr, uptr addr);
747 void TraceTime(ThreadState *thr);
748 
749 }  // namespace v3
750 
751 void GrowShadowStack(ThreadState *thr);
752 
753 ALWAYS_INLINE
FuncEntry(ThreadState * thr,uptr pc)754 void FuncEntry(ThreadState *thr, uptr pc) {
755   DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void *)pc);
756   if (kCollectHistory) {
757     thr->fast_state.IncrementEpoch();
758     TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
759   }
760 
761   // Shadow stack maintenance can be replaced with
762   // stack unwinding during trace switch (which presumably must be faster).
763   DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
764 #if !SANITIZER_GO
765   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
766 #else
767   if (thr->shadow_stack_pos == thr->shadow_stack_end)
768     GrowShadowStack(thr);
769 #endif
770   thr->shadow_stack_pos[0] = pc;
771   thr->shadow_stack_pos++;
772 }
773 
774 ALWAYS_INLINE
FuncExit(ThreadState * thr)775 void FuncExit(ThreadState *thr) {
776   DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
777   if (kCollectHistory) {
778     thr->fast_state.IncrementEpoch();
779     TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
780   }
781 
782   DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
783 #if !SANITIZER_GO
784   DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
785 #endif
786   thr->shadow_stack_pos--;
787 }
788 
789 #if !SANITIZER_GO
790 extern void (*on_initialize)(void);
791 extern int (*on_finalize)(int);
792 #endif
793 
794 }  // namespace __tsan
795 
796 #endif  // TSAN_RTL_H
797