1 //===-- sanitizer_stack_store.cpp -------------------------------*- 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 #include "sanitizer_stack_store.h"
10 
11 #include "sanitizer_atomic.h"
12 #include "sanitizer_common.h"
13 #include "sanitizer_stacktrace.h"
14 
15 namespace __sanitizer {
16 
17 namespace {
18 struct StackTraceHeader {
19   static constexpr u32 kStackSizeBits = 8;
20 
21   u8 size;
22   u8 tag;
23   explicit StackTraceHeader(const StackTrace &trace)
24       : size(Min<uptr>(trace.size, (1u << 8) - 1)), tag(trace.tag) {
25     CHECK_EQ(trace.tag, static_cast<uptr>(tag));
26   }
27   explicit StackTraceHeader(uptr h)
28       : size(h & ((1 << kStackSizeBits) - 1)), tag(h >> kStackSizeBits) {}
29 
30   uptr ToUptr() const {
31     return static_cast<uptr>(size) | (static_cast<uptr>(tag) << kStackSizeBits);
32   }
33 };
34 }  // namespace
35 
36 StackStore::Id StackStore::Store(const StackTrace &trace, uptr *pack) {
37   if (!trace.size && !trace.tag)
38     return 0;
39   StackTraceHeader h(trace);
40   uptr idx = 0;
41   *pack = 0;
42   uptr *stack_trace = Alloc(h.size + 1, &idx, pack);
43   *stack_trace = h.ToUptr();
44   internal_memcpy(stack_trace + 1, trace.trace, h.size * sizeof(uptr));
45   *pack += blocks_[GetBlockIdx(idx)].Stored(h.size + 1);
46   return OffsetToId(idx);
47 }
48 
49 StackTrace StackStore::Load(Id id) {
50   if (!id)
51     return {};
52   uptr idx = IdToOffset(id);
53   uptr block_idx = GetBlockIdx(idx);
54   CHECK_LT(block_idx, ARRAY_SIZE(blocks_));
55   const uptr *stack_trace = blocks_[block_idx].GetOrUnpack();
56   if (!stack_trace)
57     return {};
58   stack_trace += GetInBlockIdx(idx);
59   StackTraceHeader h(*stack_trace);
60   return StackTrace(stack_trace + 1, h.size, h.tag);
61 }
62 
63 uptr StackStore::Allocated() const {
64   uptr next_block = GetBlockIdx(
65       RoundUpTo(atomic_load_relaxed(&total_frames_), kBlockSizeFrames));
66   uptr res = 0;
67   for (uptr i = 0; i < next_block; ++i) res += blocks_[i].Allocated();
68   return res + sizeof(*this);
69 }
70 
71 uptr *StackStore::Alloc(uptr count, uptr *idx, uptr *pack) {
72   for (;;) {
73     // Optimisic lock-free allocation, essentially try to bump the
74     // total_frames_.
75     uptr start = atomic_fetch_add(&total_frames_, count, memory_order_relaxed);
76     uptr block_idx = GetBlockIdx(start);
77     uptr last_idx = GetBlockIdx(start + count - 1);
78     if (LIKELY(block_idx == last_idx)) {
79       // Fits into the a single block.
80       CHECK_LT(block_idx, ARRAY_SIZE(blocks_));
81       *idx = start;
82       return blocks_[block_idx].GetOrCreate() + GetInBlockIdx(start);
83     }
84 
85     // Retry. We can't use range allocated in two different blocks.
86     CHECK_LE(count, kBlockSizeFrames);
87     uptr in_first = kBlockSizeFrames - GetInBlockIdx(start);
88     // Mark tail/head of these blocks as "stored".to avoid waiting before we can
89     // Pack().
90     *pack += blocks_[block_idx].Stored(in_first);
91     *pack += blocks_[last_idx].Stored(count - in_first);
92   }
93 }
94 
95 uptr StackStore::Pack(Compression type) {
96   uptr res = 0;
97   for (BlockInfo &b : blocks_) res += b.Pack(type);
98   return res;
99 }
100 
101 void StackStore::TestOnlyUnmap() {
102   for (BlockInfo &b : blocks_) b.TestOnlyUnmap();
103   internal_memset(this, 0, sizeof(*this));
104 }
105 
106 uptr *StackStore::BlockInfo::Get() const {
107   // Idiomatic double-checked locking uses memory_order_acquire here. But
108   // relaxed is find for us, justification is similar to
109   // TwoLevelMap::GetOrCreate.
110   return reinterpret_cast<uptr *>(atomic_load_relaxed(&data_));
111 }
112 
113 uptr *StackStore::BlockInfo::Create() {
114   SpinMutexLock l(&mtx_);
115   uptr *ptr = Get();
116   if (!ptr) {
117     ptr = reinterpret_cast<uptr *>(
118         MmapNoReserveOrDie(kBlockSizeBytes, "StackStore"));
119     atomic_store(&data_, reinterpret_cast<uptr>(ptr), memory_order_release);
120   }
121   return ptr;
122 }
123 
124 uptr *StackStore::BlockInfo::GetOrCreate() {
125   uptr *ptr = Get();
126   if (LIKELY(ptr))
127     return ptr;
128   return Create();
129 }
130 
131 uptr *StackStore::BlockInfo::GetOrUnpack() {
132   SpinMutexLock l(&mtx_);
133   switch (state) {
134     case State::Storing:
135       state = State::Unpacked;
136       FALLTHROUGH;
137     case State::Unpacked:
138       return Get();
139     case State::Packed:
140       break;
141   }
142 
143   uptr *ptr = Get();
144   CHECK_NE(nullptr, ptr);
145   // Fake unpacking.
146   for (uptr i = 0; i < kBlockSizeFrames; ++i) ptr[i] = ~ptr[i];
147   state = State::Unpacked;
148   return Get();
149 }
150 
151 uptr StackStore::BlockInfo::Pack(Compression type) {
152   if (type == Compression::None)
153     return 0;
154 
155   SpinMutexLock l(&mtx_);
156   switch (state) {
157     case State::Unpacked:
158     case State::Packed:
159       return 0;
160     case State::Storing:
161       break;
162   }
163 
164   uptr *ptr = Get();
165   if (!ptr || !Stored(0))
166     return 0;
167 
168   // Fake packing.
169   for (uptr i = 0; i < kBlockSizeFrames; ++i) ptr[i] = ~ptr[i];
170   state = State::Packed;
171   return kBlockSizeBytes - kBlockSizeBytes / 10;
172 }
173 
174 uptr StackStore::BlockInfo::Allocated() const {
175   SpinMutexLock l(&mtx_);
176   switch (state) {
177     case State::Packed:
178       return kBlockSizeBytes / 10;
179     case State::Unpacked:
180     case State::Storing:
181       return kBlockSizeBytes;
182   }
183 }
184 
185 void StackStore::BlockInfo::TestOnlyUnmap() {
186   if (uptr *ptr = Get())
187     UnmapOrDie(ptr, StackStore::kBlockSizeBytes);
188 }
189 
190 bool StackStore::BlockInfo::Stored(uptr n) {
191   return n + atomic_fetch_add(&stored_, n, memory_order_release) ==
192          kBlockSizeFrames;
193 }
194 
195 bool StackStore::BlockInfo::IsPacked() const {
196   SpinMutexLock l(&mtx_);
197   return state == State::Packed;
198 }
199 
200 }  // namespace __sanitizer
201