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
23namespace __scudo {
24
25struct 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() {
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() {
44    atomic_store_relaxed(&Precedence, 0);
45    Mutex.Lock();
46  }
47
48  INLINE void unlock() { 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
57void 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