sanitizer_quarantine.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. //===-- sanitizer_quarantine.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. // Memory quarantine for AddressSanitizer and potentially other tools.
  10. // Quarantine caches some specified amount of memory in per-thread caches,
  11. // then evicts to global FIFO queue. When the queue reaches specified threshold,
  12. // oldest memory is recycled.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef SANITIZER_QUARANTINE_H
  16. #define SANITIZER_QUARANTINE_H
  17. #include "sanitizer_internal_defs.h"
  18. #include "sanitizer_mutex.h"
  19. #include "sanitizer_list.h"
  20. namespace __sanitizer {
  21. template<typename Node> class QuarantineCache;
  22. struct QuarantineBatch {
  23. static const uptr kSize = 1021;
  24. QuarantineBatch *next;
  25. uptr size;
  26. uptr count;
  27. void *batch[kSize];
  28. void init(void *ptr, uptr size) {
  29. count = 1;
  30. batch[0] = ptr;
  31. this->size = size + sizeof(QuarantineBatch); // Account for the batch size.
  32. }
  33. // The total size of quarantined nodes recorded in this batch.
  34. uptr quarantined_size() const {
  35. return size - sizeof(QuarantineBatch);
  36. }
  37. void push_back(void *ptr, uptr size) {
  38. CHECK_LT(count, kSize);
  39. batch[count++] = ptr;
  40. this->size += size;
  41. }
  42. bool can_merge(const QuarantineBatch* const from) const {
  43. return count + from->count <= kSize;
  44. }
  45. void merge(QuarantineBatch* const from) {
  46. CHECK_LE(count + from->count, kSize);
  47. CHECK_GE(size, sizeof(QuarantineBatch));
  48. for (uptr i = 0; i < from->count; ++i)
  49. batch[count + i] = from->batch[i];
  50. count += from->count;
  51. size += from->quarantined_size();
  52. from->count = 0;
  53. from->size = sizeof(QuarantineBatch);
  54. }
  55. };
  56. COMPILER_CHECK(sizeof(QuarantineBatch) <= (1 << 13)); // 8Kb.
  57. template<typename Callback, typename Node>
  58. class Quarantine {
  59. public:
  60. typedef QuarantineCache<Callback> Cache;
  61. explicit Quarantine(LinkerInitialized)
  62. : cache_(LINKER_INITIALIZED) {
  63. }
  64. void Init(uptr size, uptr cache_size) {
  65. // Thread local quarantine size can be zero only when global quarantine size
  66. // is zero (it allows us to perform just one atomic read per Put() call).
  67. CHECK((size == 0 && cache_size == 0) || cache_size != 0);
  68. atomic_store_relaxed(&max_size_, size);
  69. atomic_store_relaxed(&min_size_, size / 10 * 9); // 90% of max size.
  70. atomic_store_relaxed(&max_cache_size_, cache_size);
  71. cache_mutex_.Init();
  72. recycle_mutex_.Init();
  73. }
  74. uptr GetMaxSize() const { return atomic_load_relaxed(&max_size_); }
  75. uptr GetMaxCacheSize() const { return atomic_load_relaxed(&max_cache_size_); }
  76. void Put(Cache *c, Callback cb, Node *ptr, uptr size) {
  77. uptr max_cache_size = GetMaxCacheSize();
  78. if (max_cache_size && size <= GetMaxSize()) {
  79. cb.PreQuarantine(ptr);
  80. c->Enqueue(cb, ptr, size);
  81. } else {
  82. // GetMaxCacheSize() == 0 only when GetMaxSize() == 0 (see Init).
  83. cb.RecyclePassThrough(ptr);
  84. }
  85. // Check cache size anyway to accommodate for runtime cache_size change.
  86. if (c->Size() > max_cache_size)
  87. Drain(c, cb);
  88. }
  89. void NOINLINE Drain(Cache *c, Callback cb) {
  90. {
  91. SpinMutexLock l(&cache_mutex_);
  92. cache_.Transfer(c);
  93. }
  94. if (cache_.Size() > GetMaxSize() && recycle_mutex_.TryLock())
  95. Recycle(atomic_load_relaxed(&min_size_), cb);
  96. }
  97. void NOINLINE DrainAndRecycle(Cache *c, Callback cb) {
  98. {
  99. SpinMutexLock l(&cache_mutex_);
  100. cache_.Transfer(c);
  101. }
  102. recycle_mutex_.Lock();
  103. Recycle(0, cb);
  104. }
  105. void PrintStats() const {
  106. // It assumes that the world is stopped, just as the allocator's PrintStats.
  107. Printf("Quarantine limits: global: %zdMb; thread local: %zdKb\n",
  108. GetMaxSize() >> 20, GetMaxCacheSize() >> 10);
  109. cache_.PrintStats();
  110. }
  111. private:
  112. // Read-only data.
  113. char pad0_[kCacheLineSize];
  114. atomic_uintptr_t max_size_;
  115. atomic_uintptr_t min_size_;
  116. atomic_uintptr_t max_cache_size_;
  117. char pad1_[kCacheLineSize];
  118. StaticSpinMutex cache_mutex_;
  119. StaticSpinMutex recycle_mutex_;
  120. Cache cache_;
  121. char pad2_[kCacheLineSize];
  122. void NOINLINE Recycle(uptr min_size, Callback cb)
  123. SANITIZER_REQUIRES(recycle_mutex_) SANITIZER_RELEASE(recycle_mutex_) {
  124. Cache tmp;
  125. {
  126. SpinMutexLock l(&cache_mutex_);
  127. // Go over the batches and merge partially filled ones to
  128. // save some memory, otherwise batches themselves (since the memory used
  129. // by them is counted against quarantine limit) can overcome the actual
  130. // user's quarantined chunks, which diminishes the purpose of the
  131. // quarantine.
  132. uptr cache_size = cache_.Size();
  133. uptr overhead_size = cache_.OverheadSize();
  134. CHECK_GE(cache_size, overhead_size);
  135. // Do the merge only when overhead exceeds this predefined limit (might
  136. // require some tuning). It saves us merge attempt when the batch list
  137. // quarantine is unlikely to contain batches suitable for merge.
  138. const uptr kOverheadThresholdPercents = 100;
  139. if (cache_size > overhead_size &&
  140. overhead_size * (100 + kOverheadThresholdPercents) >
  141. cache_size * kOverheadThresholdPercents) {
  142. cache_.MergeBatches(&tmp);
  143. }
  144. // Extract enough chunks from the quarantine to get below the max
  145. // quarantine size and leave some leeway for the newly quarantined chunks.
  146. while (cache_.Size() > min_size) {
  147. tmp.EnqueueBatch(cache_.DequeueBatch());
  148. }
  149. }
  150. recycle_mutex_.Unlock();
  151. DoRecycle(&tmp, cb);
  152. }
  153. void NOINLINE DoRecycle(Cache *c, Callback cb) {
  154. while (QuarantineBatch *b = c->DequeueBatch()) {
  155. const uptr kPrefetch = 16;
  156. CHECK(kPrefetch <= ARRAY_SIZE(b->batch));
  157. for (uptr i = 0; i < kPrefetch; i++)
  158. PREFETCH(b->batch[i]);
  159. for (uptr i = 0, count = b->count; i < count; i++) {
  160. if (i + kPrefetch < count)
  161. PREFETCH(b->batch[i + kPrefetch]);
  162. cb.Recycle((Node*)b->batch[i]);
  163. }
  164. cb.Deallocate(b);
  165. }
  166. }
  167. };
  168. // Per-thread cache of memory blocks.
  169. template<typename Callback>
  170. class QuarantineCache {
  171. public:
  172. explicit QuarantineCache(LinkerInitialized) {
  173. }
  174. QuarantineCache()
  175. : size_() {
  176. list_.clear();
  177. }
  178. // Total memory used, including internal accounting.
  179. uptr Size() const {
  180. return atomic_load_relaxed(&size_);
  181. }
  182. // Memory used for internal accounting.
  183. uptr OverheadSize() const {
  184. return list_.size() * sizeof(QuarantineBatch);
  185. }
  186. void Enqueue(Callback cb, void *ptr, uptr size) {
  187. if (list_.empty() || list_.back()->count == QuarantineBatch::kSize) {
  188. QuarantineBatch *b = (QuarantineBatch *)cb.Allocate(sizeof(*b));
  189. CHECK(b);
  190. b->init(ptr, size);
  191. EnqueueBatch(b);
  192. } else {
  193. list_.back()->push_back(ptr, size);
  194. SizeAdd(size);
  195. }
  196. }
  197. void Transfer(QuarantineCache *from_cache) {
  198. list_.append_back(&from_cache->list_);
  199. SizeAdd(from_cache->Size());
  200. atomic_store_relaxed(&from_cache->size_, 0);
  201. }
  202. void EnqueueBatch(QuarantineBatch *b) {
  203. list_.push_back(b);
  204. SizeAdd(b->size);
  205. }
  206. QuarantineBatch *DequeueBatch() {
  207. if (list_.empty())
  208. return nullptr;
  209. QuarantineBatch *b = list_.front();
  210. list_.pop_front();
  211. SizeSub(b->size);
  212. return b;
  213. }
  214. void MergeBatches(QuarantineCache *to_deallocate) {
  215. uptr extracted_size = 0;
  216. QuarantineBatch *current = list_.front();
  217. while (current && current->next) {
  218. if (current->can_merge(current->next)) {
  219. QuarantineBatch *extracted = current->next;
  220. // Move all the chunks into the current batch.
  221. current->merge(extracted);
  222. CHECK_EQ(extracted->count, 0);
  223. CHECK_EQ(extracted->size, sizeof(QuarantineBatch));
  224. // Remove the next batch from the list and account for its size.
  225. list_.extract(current, extracted);
  226. extracted_size += extracted->size;
  227. // Add it to deallocation list.
  228. to_deallocate->EnqueueBatch(extracted);
  229. } else {
  230. current = current->next;
  231. }
  232. }
  233. SizeSub(extracted_size);
  234. }
  235. void PrintStats() const {
  236. uptr batch_count = 0;
  237. uptr total_overhead_bytes = 0;
  238. uptr total_bytes = 0;
  239. uptr total_quarantine_chunks = 0;
  240. for (List::ConstIterator it = list_.begin(); it != list_.end(); ++it) {
  241. batch_count++;
  242. total_bytes += (*it).size;
  243. total_overhead_bytes += (*it).size - (*it).quarantined_size();
  244. total_quarantine_chunks += (*it).count;
  245. }
  246. uptr quarantine_chunks_capacity = batch_count * QuarantineBatch::kSize;
  247. int chunks_usage_percent = quarantine_chunks_capacity == 0 ?
  248. 0 : total_quarantine_chunks * 100 / quarantine_chunks_capacity;
  249. uptr total_quarantined_bytes = total_bytes - total_overhead_bytes;
  250. int memory_overhead_percent = total_quarantined_bytes == 0 ?
  251. 0 : total_overhead_bytes * 100 / total_quarantined_bytes;
  252. Printf("Global quarantine stats: batches: %zd; bytes: %zd (user: %zd); "
  253. "chunks: %zd (capacity: %zd); %d%% chunks used; %d%% memory overhead"
  254. "\n",
  255. batch_count, total_bytes, total_quarantined_bytes,
  256. total_quarantine_chunks, quarantine_chunks_capacity,
  257. chunks_usage_percent, memory_overhead_percent);
  258. }
  259. private:
  260. typedef IntrusiveList<QuarantineBatch> List;
  261. List list_;
  262. atomic_uintptr_t size_;
  263. void SizeAdd(uptr add) {
  264. atomic_store_relaxed(&size_, Size() + add);
  265. }
  266. void SizeSub(uptr sub) {
  267. atomic_store_relaxed(&size_, Size() - sub);
  268. }
  269. };
  270. } // namespace __sanitizer
  271. #endif // SANITIZER_QUARANTINE_H