1 //===-- scudo_tsd.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 /// Scudo thread specific data definition.
10 /// Implementation will differ based on the thread local storage primitives
11 /// offered by the underlying platform.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef SCUDO_TSD_H_
16 #define SCUDO_TSD_H_
17 
18 #include "scudo_allocator.h"
19 #include "scudo_utils.h"
20 
21 #include <pthread.h>
22 
23 namespace __scudo {
24 
ALIGNED(SANITIZER_CACHE_LINE_SIZE)25 struct ALIGNED(SANITIZER_CACHE_LINE_SIZE) ScudoTSD {
26   AllocatorCacheT Cache;
27   uptr QuarantineCachePlaceHolder[4];
28 
29   void init();
30   void commitBack();
31 
32   inline bool tryLock() TRY_ACQUIRE(true, Mutex) {
33     if (Mutex.TryLock()) {
34       atomic_store_relaxed(&Precedence, 0);
35       return true;
36     }
37     if (atomic_load_relaxed(&Precedence) == 0)
38       atomic_store_relaxed(&Precedence, static_cast<uptr>(
39           MonotonicNanoTime() >> FIRST_32_SECOND_64(16, 0)));
40     return false;
41   }
42 
43   inline void lock() ACQUIRE(Mutex) {
44     atomic_store_relaxed(&Precedence, 0);
45     Mutex.Lock();
46   }
47 
48   inline void unlock() RELEASE(Mutex) { Mutex.Unlock(); }
49 
50   inline uptr getPrecedence() { return atomic_load_relaxed(&Precedence); }
51 
52  private:
53   StaticSpinMutex Mutex;
54   atomic_uintptr_t Precedence;
55 };
56 
57 void initThread(bool MinimalInit);
58 
59 // TSD model specific fastpath functions definitions.
60 #include "scudo_tsd_exclusive.inc"
61 #include "scudo_tsd_shared.inc"
62 
63 }  // namespace __scudo
64 
65 #endif  // SCUDO_TSD_H_
66