1//===-- secondary.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#ifndef SCUDO_SECONDARY_H_
10#define SCUDO_SECONDARY_H_
11
12#ifndef __STDC_FORMAT_MACROS
13// Ensure PRId64 macro is available
14#define __STDC_FORMAT_MACROS 1
15#endif
16#include <inttypes.h>
17
18#include "chunk.h"
19#include "common.h"
20#include "list.h"
21#include "mem_map.h"
22#include "memtag.h"
23#include "mutex.h"
24#include "options.h"
25#include "stats.h"
26#include "string_utils.h"
27#include "thread_annotations.h"
28#include "tracing.h"
29#include "vector.h"
30
31namespace scudo {
32
33// This allocator wraps the platform allocation primitives, and as such is on
34// the slower side and should preferably be used for larger sized allocations.
35// Blocks allocated will be preceded and followed by a guard page, and hold
36// their own header that is not checksummed: the guard pages and the Combined
37// header should be enough for our purpose.
38
39namespace LargeBlock {
40
41struct alignas(Max<uptr>(A: archSupportsMemoryTagging()
42 ? archMemoryTagGranuleSize()
43 : 1,
44 B: 1U << SCUDO_MIN_ALIGNMENT_LOG)) Header {
45 LargeBlock::Header *Prev;
46 LargeBlock::Header *Next;
47 uptr CommitBase;
48 uptr CommitSize;
49 MemMapT MemMap;
50};
51
52static_assert(sizeof(Header) % (1U << SCUDO_MIN_ALIGNMENT_LOG) == 0, "");
53static_assert(!archSupportsMemoryTagging() ||
54 sizeof(Header) % archMemoryTagGranuleSize() == 0,
55 "");
56
57constexpr uptr getHeaderSize() { return sizeof(Header); }
58
59template <typename Config> uptr addHeaderTag(uptr Ptr) {
60 if (allocatorSupportsMemoryTagging<Config>())
61 return addFixedTag(Ptr, Tag: 1);
62 return Ptr;
63}
64
65template <typename Config> Header *getHeader(uptr Ptr) {
66 return reinterpret_cast<Header *>(addHeaderTag<Config>(Ptr)) - 1;
67}
68
69template <typename Config> Header *getHeader(const void *Ptr) {
70 return getHeader<Config>(reinterpret_cast<uptr>(Ptr));
71}
72
73} // namespace LargeBlock
74
75static inline void unmap(MemMapT &MemMap) { MemMap.unmap(); }
76
77namespace {
78
79struct CachedBlock {
80 static constexpr u16 CacheIndexMax = UINT16_MAX;
81 static constexpr u16 EndOfListVal = CacheIndexMax;
82
83 // We allow a certain amount of fragmentation and part of the fragmented bytes
84 // will be released by `releaseAndZeroPagesToOS()`. This increases the chance
85 // of cache hit rate and reduces the overhead to the RSS at the same time. See
86 // more details in the `MapAllocatorCache::retrieve()` section.
87 //
88 // We arrived at this default value after noticing that mapping in larger
89 // memory regions performs better than releasing memory and forcing a cache
90 // hit. According to the data, it suggests that beyond 4 pages, the release
91 // execution time is longer than the map execution time. In this way,
92 // the default is dependent on the platform.
93 static constexpr uptr MaxReleasedCachePages = 4U;
94
95 uptr CommitBase = 0;
96 uptr CommitSize = 0;
97 uptr BlockBegin = 0;
98 MemMapT MemMap = {};
99 u64 Time = 0;
100 u16 Next = 0;
101 u16 Prev = 0;
102
103 enum CacheFlags : u16 {
104 None = 0,
105 NoAccess = 0x1,
106 };
107 CacheFlags Flags = CachedBlock::None;
108
109 bool isValid() { return CommitBase != 0; }
110
111 void invalidate() { CommitBase = 0; }
112};
113} // namespace
114
115template <typename Config> class MapAllocatorNoCache {
116public:
117 void init(UNUSED s32 ReleaseToOsInterval) {}
118 CachedBlock retrieve(UNUSED uptr MaxAllowedFragmentedBytes, UNUSED uptr Size,
119 UNUSED uptr Alignment, UNUSED uptr HeadersSize,
120 UNUSED uptr &EntryHeaderPos) {
121 return {};
122 }
123 void store(UNUSED Options Options, UNUSED uptr CommitBase,
124 UNUSED uptr CommitSize, UNUSED uptr BlockBegin,
125 UNUSED MemMapT MemMap) {
126 // This should never be called since canCache always returns false.
127 UNREACHABLE(
128 "It is not valid to call store on MapAllocatorNoCache objects.");
129 }
130
131 bool canCache(UNUSED uptr Size) { return false; }
132 void disable() {}
133 void enable() {}
134 void releaseToOS(ReleaseToOS) {}
135 void disableMemoryTagging() {}
136 void unmapTestOnly() {}
137 bool setOption(Option O, UNUSED sptr Value) {
138 if (O == Option::ReleaseInterval || O == Option::MaxCacheEntriesCount ||
139 O == Option::MaxCacheEntrySize || O == Option::MaxCacheResidentBytes)
140 return false;
141 // Not supported by the Secondary Cache, but not an error either.
142 return true;
143 }
144
145 uptr getMaxResidentBytesTestOnly() const { return 0; }
146 uptr getCurrentResidentBytesTestOnly() const { return 0; }
147
148 void getStats(UNUSED ScopedString *Str) {
149 Str->append(Format: "Secondary Cache Disabled\n");
150 }
151};
152
153static const uptr MaxUnreleasedCachePages = 4U;
154
155template <typename Config>
156bool mapSecondary(const Options &Options, uptr CommitBase, uptr CommitSize,
157 uptr AllocPos, uptr Flags, MemMapT &MemMap) {
158 Flags |= MAP_RESIZABLE;
159 Flags |= MAP_ALLOWNOMEM;
160
161 const uptr PageSize = getPageSizeCached();
162 if (SCUDO_TRUSTY) {
163 /*
164 * On Trusty we need AllocPos to be usable for shared memory, which cannot
165 * cross multiple mappings. This means we need to split around AllocPos
166 * and not over it. We can only do this if the address is page-aligned.
167 */
168 const uptr TaggedSize = AllocPos - CommitBase;
169 if (useMemoryTagging<Config>(Options) && isAligned(X: TaggedSize, Alignment: PageSize)) {
170 DCHECK_GT(TaggedSize, 0);
171 return MemMap.remap(Addr: CommitBase, Size: TaggedSize, Name: "scudo:secondary",
172 MAP_MEMTAG | Flags) &&
173 MemMap.remap(Addr: AllocPos, Size: CommitSize - TaggedSize, Name: "scudo:secondary",
174 Flags);
175 } else {
176 const uptr RemapFlags =
177 (useMemoryTagging<Config>(Options) ? MAP_MEMTAG : 0) | Flags;
178 return MemMap.remap(Addr: CommitBase, Size: CommitSize, Name: "scudo:secondary",
179 Flags: RemapFlags);
180 }
181 }
182
183 // AllocPos is assumed to be page-aligned when memory tagging is enabled.
184 // Therefore the page right before AllocPos is MTE-tagged and the header
185 // resides in this MTE-tagged page.
186 if (useMemoryTagging<Config>(Options)) {
187 const uptr PageSize = getPageSizeCached();
188 const uptr MteStart = AllocPos - PageSize;
189
190 DCHECK(AllocPos % PageSize == 0U);
191 DCHECK(MteStart % PageSize == 0U);
192
193 DCHECK_GE(MteStart, CommitBase);
194 DCHECK_LE(AllocPos, CommitBase + CommitSize);
195 return MemMap.remap(Addr: MteStart, Size: PageSize, Name: "scudo:secondary",
196 MAP_MEMTAG | Flags) &&
197 MemMap.remap(Addr: AllocPos, Size: CommitBase + CommitSize - AllocPos,
198 Name: "scudo:secondary", Flags);
199 } else {
200 const uptr RemapFlags =
201 (useMemoryTagging<Config>(Options) ? MAP_MEMTAG : 0) | Flags;
202 return MemMap.remap(Addr: CommitBase, Size: CommitSize, Name: "scudo:secondary", Flags: RemapFlags);
203 }
204}
205
206// Template specialization to avoid producing zero-length array
207template <typename T, size_t Size> class NonZeroLengthArray {
208public:
209 T &operator[](uptr Idx) { return values[Idx]; }
210
211private:
212 T values[Size];
213};
214template <typename T> class NonZeroLengthArray<T, 0> {
215public:
216 T &operator[](uptr UNUSED Idx) { UNREACHABLE("Unsupported!"); }
217};
218
219// The default unmap callback is simply scudo::unmap.
220// In testing, a different unmap callback is used to
221// record information about unmaps in the cache
222template <typename Config, void (*unmapCallBack)(MemMapT &) = unmap>
223class MapAllocatorCache {
224public:
225 void getStats(ScopedString *Str) {
226 ScopedLock L(Mutex);
227 Str->append(Format: "Config Stats Secondary: ");
228 Config::getConfigValues(Str);
229 uptr Integral;
230 uptr Fractional;
231 computePercentage(Numerator: SuccessfulRetrieves, Denominator: CallsToRetrieve, Integral: &Integral,
232 Fractional: &Fractional);
233 const s32 Interval = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
234 Str->append(
235 Format: "Stats: MapAllocatorCache: EntriesCount: %zu, "
236 "MaxEntriesCount: %u, MaxEntrySize: %zu, ReleaseToOsSkips: "
237 "%zu, ReleaseToOsIntervalMs = %d, Unmapped due to eviction: %u, "
238 "MaxResidentBytes: %zu, CurrentResidentBytes: %zu\n",
239 LRUEntries.size(), atomic_load_relaxed(A: &MaxEntriesCount),
240 atomic_load_relaxed(A: &MaxEntrySize),
241 atomic_load_relaxed(A: &ReleaseToOsSkips), Interval >= 0 ? Interval : -1,
242 EvictedCount, MaxResidentBytes, CurrentResidentBytes);
243 Str->append(Format: "Stats: CacheRetrievalStats: SuccessRate: %u/%u "
244 "(%zu.%02zu%%)\n",
245 SuccessfulRetrieves, CallsToRetrieve, Integral, Fractional);
246 Str->append(Format: "Cache Entry Info (Most Recent -> Least Recent):\n");
247
248 for (CachedBlock &Entry : LRUEntries) {
249 Str->append(Format: " StartBlockAddress: 0x%zx, EndBlockAddress: 0x%zx, "
250 "BlockSize: %zu%s, Flags: %s",
251 Entry.CommitBase, Entry.CommitBase + Entry.CommitSize,
252 Entry.CommitSize, Entry.Time == 0 ? " [R]" : "",
253 Entry.Flags & CachedBlock::NoAccess ? "NoAccess" : "None");
254 const s64 ResidentPages =
255 Entry.MemMap.getResidentPages(From: Entry.CommitBase, Size: Entry.CommitSize);
256
257 if (ResidentPages >= 0) {
258 Str->append(Format: ", Resident Pages: %" PRId64 "/%zu", ResidentPages,
259 Entry.CommitSize / getPageSizeCached());
260 }
261 Str->append(Format: "\n");
262 }
263 }
264
265 // Ensure the default maximum specified fits the array.
266 static_assert(Config::getDefaultMaxEntriesCount() <=
267 Config::getEntriesArraySize(),
268 "");
269 // Ensure the cache entry array size fits in the LRU list Next and Prev
270 // index fields
271 static_assert(Config::getEntriesArraySize() <= CachedBlock::CacheIndexMax,
272 "Cache entry array is too large to be indexed.");
273
274 void init(s32 ReleaseToOsInterval) NO_THREAD_SAFETY_ANALYSIS {
275 DCHECK_EQ(LRUEntries.size(), 0U);
276 setOption(O: Option::MaxCacheEntriesCount,
277 Value: static_cast<sptr>(Config::getDefaultMaxEntriesCount()));
278 setOption(O: Option::MaxCacheEntrySize,
279 Value: static_cast<sptr>(Config::getDefaultMaxEntrySize()));
280 setOption(O: Option::MaxCacheResidentBytes,
281 Value: static_cast<sptr>(Config::getDefaultMaxCacheResidentBytes()));
282 // The default value in the cache config has the higher priority.
283 if (Config::getDefaultReleaseToOsIntervalMs() != INT32_MIN)
284 ReleaseToOsInterval = Config::getDefaultReleaseToOsIntervalMs();
285 setOption(O: Option::ReleaseInterval, Value: static_cast<sptr>(ReleaseToOsInterval));
286
287 LRUEntries.clear();
288 LRUEntries.init(Base: Entries, BaseSize: sizeof(Entries));
289 OldestPresentEntry = nullptr;
290
291 AvailEntries.clear();
292 AvailEntries.init(Base: Entries, BaseSize: sizeof(Entries));
293 for (u32 I = 0; I < Config::getEntriesArraySize(); I++)
294 AvailEntries.push_back(X: &Entries[I]);
295 }
296
297 void store(const Options &Options, uptr CommitBase, uptr CommitSize,
298 uptr BlockBegin, MemMapT MemMap) EXCLUDES(Mutex) {
299 DCHECK(canCache(CommitSize));
300
301 const s32 Interval = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
302 u64 Time;
303 CachedBlock Entry;
304
305 Entry.CommitBase = CommitBase;
306 Entry.CommitSize = CommitSize;
307 Entry.BlockBegin = BlockBegin;
308 Entry.MemMap = MemMap;
309 Entry.Time = UINT64_MAX;
310 Entry.Flags = CachedBlock::None;
311
312 bool MemoryTaggingEnabled = useMemoryTagging<Config>(Options);
313 if (MemoryTaggingEnabled) {
314 if (Interval == 0 && !SCUDO_FUCHSIA) {
315 Entry.Time = 0;
316 Entry.MemMap.releaseAndZeroPagesToOS(From: Entry.CommitBase,
317 Size: Entry.CommitSize);
318 }
319 // MAP_NOACCESS or PROT_NONE does not strip PROT_MTE.
320 Entry.MemMap.setMemoryPermission(Addr: Entry.CommitBase, Size: Entry.CommitSize,
321 MAP_NOACCESS);
322 Entry.Flags = CachedBlock::NoAccess;
323 }
324
325 // Usually only one entry will be evicted from the cache.
326 // Only in the rare event that the cache shrinks in real-time
327 // due to a decrease in the configurable value MaxEntriesCount
328 // will more than one cache entry be evicted.
329 // The vector is used to save the MemMaps of evicted entries so
330 // that the unmap call can be performed outside the lock
331 Vector<MemMapT, 1U> EvictionMemMaps;
332
333 do {
334 ScopedLock L(Mutex);
335
336 // Time must be computed under the lock to ensure
337 // that the LRU cache remains sorted with respect to
338 // time in a multithreaded environment
339 Time = getMonotonicTimeFast();
340 if (Entry.Time != 0)
341 Entry.Time = Time;
342
343 if (MemoryTaggingEnabled && !useMemoryTagging<Config>(Options)) {
344 // If we get here then memory tagging was disabled in between when we
345 // read Options and when we locked Mutex. We can't insert our entry into
346 // the quarantine or the cache because the permissions would be wrong so
347 // just unmap it.
348 unmapCallBack(Entry.MemMap);
349 break;
350 }
351
352 if (!Config::getQuarantineDisabled() && Config::getQuarantineSize()) {
353 QuarantinePos =
354 (QuarantinePos + 1) % Max(Config::getQuarantineSize(), 1u);
355 if (!Quarantine[QuarantinePos].isValid()) {
356 Quarantine[QuarantinePos] = Entry;
357 return;
358 }
359 CachedBlock PrevEntry = Quarantine[QuarantinePos];
360 Quarantine[QuarantinePos] = Entry;
361 Entry = PrevEntry;
362 }
363
364 // All excess entries are evicted from the cache. Note that when
365 // `MaxEntriesCount` is zero, cache storing shouldn't happen and it's
366 // guarded by the `DCHECK(canCache(CommitSize))` above. As a result, we
367 // won't try to pop `LRUEntries` when it's empty.
368 while (LRUEntries.size() >= atomic_load_relaxed(A: &MaxEntriesCount)) {
369 // Save MemMaps of evicted entries to perform unmap outside of lock
370 CachedBlock *Entry = LRUEntries.back();
371 EvictedCount++;
372 EvictionMemMaps.push_back(Element: Entry->MemMap);
373 remove(Entry);
374 }
375
376 insert(Entry);
377 trimResidentBytes(MaxResidentBytesLimit: atomic_load_relaxed(A: &MaxCacheResidentBytes));
378 } while (0);
379
380 for (MemMapT &EvictMemMap : EvictionMemMaps)
381 unmapCallBack(EvictMemMap);
382
383 if (Interval >= 0) {
384 // It is very likely that multiple threads trying to do a release at the
385 // same time will not actually release any extra elements. Therefore,
386 // let any other thread continue, skipping the release.
387 if (Mutex.tryLock()) {
388 SCUDO_SCOPED_TRACE(
389 GetSecondaryReleaseToOSTraceName(ReleaseToOS::Normal));
390
391 releaseOlderThan(ReleaseTime: Time - static_cast<u64>(Interval) * 1000000);
392 Mutex.unlock();
393 } else
394 atomic_fetch_add(A: &ReleaseToOsSkips, V: 1U, MO: memory_order_relaxed);
395 }
396 }
397
398 CachedBlock retrieve(uptr MaxAllowedFragmentedPages, uptr Size,
399 uptr Alignment, uptr HeadersSize, uptr &EntryHeaderPos)
400 EXCLUDES(Mutex) {
401 const uptr PageSize = getPageSizeCached();
402 // 10% of the requested size proved to be the optimal choice for
403 // retrieving cached blocks after testing several options.
404 constexpr u32 FragmentedBytesDivisor = 10;
405 CachedBlock Entry;
406 EntryHeaderPos = 0;
407 {
408 ScopedLock L(Mutex);
409 CallsToRetrieve++;
410 if (LRUEntries.size() == 0)
411 return {};
412 CachedBlock *RetrievedEntry = nullptr;
413 uptr MinDiff = UINTPTR_MAX;
414
415 // Since allocation sizes don't always match cached memory chunk sizes
416 // we allow some memory to be unused (called fragmented bytes). The
417 // amount of unused bytes is exactly EntryHeaderPos - CommitBase.
418 //
419 // CommitBase CommitBase + CommitSize
420 // V V
421 // +---+------------+-----------------+---+
422 // | | | | |
423 // +---+------------+-----------------+---+
424 // ^ ^ ^
425 // Guard EntryHeaderPos Guard-page-end
426 // page-begin
427 //
428 // [EntryHeaderPos, CommitBase + CommitSize) contains the user data as
429 // well as the header metadata. If EntryHeaderPos - CommitBase exceeds
430 // MaxAllowedFragmentedPages * PageSize, the cached memory chunk is
431 // not considered valid for retrieval.
432 for (CachedBlock &Entry : LRUEntries) {
433 const uptr CommitBase = Entry.CommitBase;
434 const uptr CommitSize = Entry.CommitSize;
435 const uptr AllocPos =
436 roundDown(X: CommitBase + CommitSize - Size, Boundary: Alignment);
437 const uptr HeaderPos = AllocPos - HeadersSize;
438 const uptr MaxAllowedFragmentedBytes =
439 MaxAllowedFragmentedPages * PageSize;
440 if (HeaderPos > CommitBase + CommitSize)
441 continue;
442 // TODO: Remove AllocPos > CommitBase + MaxAllowedFragmentedBytes
443 // and replace with Diff > MaxAllowedFragmentedBytes
444 if (HeaderPos < CommitBase ||
445 AllocPos > CommitBase + MaxAllowedFragmentedBytes) {
446 continue;
447 }
448
449 const uptr Diff = roundDown(X: HeaderPos, Boundary: PageSize) - CommitBase;
450
451 // Keep track of the smallest cached block
452 // that is greater than (AllocSize + HeaderSize)
453 if (Diff >= MinDiff)
454 continue;
455
456 MinDiff = Diff;
457 RetrievedEntry = &Entry;
458 EntryHeaderPos = HeaderPos;
459
460 // Immediately use a cached block if its size is close enough to the
461 // requested size
462 const uptr OptimalFitThesholdBytes =
463 (CommitBase + CommitSize - HeaderPos) / FragmentedBytesDivisor;
464 if (Diff <= OptimalFitThesholdBytes)
465 break;
466 }
467
468 if (RetrievedEntry != nullptr) {
469 Entry = *RetrievedEntry;
470 remove(Entry: RetrievedEntry);
471 SuccessfulRetrieves++;
472 }
473 }
474
475 // The difference between the retrieved memory chunk and the request
476 // size is at most MaxAllowedFragmentedPages
477 //
478 // +- MaxAllowedFragmentedPages * PageSize -+
479 // +--------------------------+-------------+
480 // | | |
481 // +--------------------------+-------------+
482 // \ Bytes to be released / ^
483 // |
484 // (may or may not be committed)
485 //
486 // The maximum number of bytes released to the OS is capped by
487 // MaxReleasedCachePages
488 //
489 // TODO : Consider making MaxReleasedCachePages configurable since
490 // the release to OS API can vary across systems.
491 if (Entry.Time != 0) {
492 const uptr FragmentedBytes =
493 roundDown(X: EntryHeaderPos, Boundary: PageSize) - Entry.CommitBase;
494 const uptr MaxUnreleasedCacheBytes = MaxUnreleasedCachePages * PageSize;
495 if (FragmentedBytes > MaxUnreleasedCacheBytes) {
496 const uptr MaxReleasedCacheBytes =
497 CachedBlock::MaxReleasedCachePages * PageSize;
498 uptr BytesToRelease =
499 roundUp(X: Min<uptr>(A: MaxReleasedCacheBytes,
500 B: FragmentedBytes - MaxUnreleasedCacheBytes),
501 Boundary: PageSize);
502 Entry.MemMap.releaseAndZeroPagesToOS(From: Entry.CommitBase, Size: BytesToRelease);
503 }
504 }
505
506 return Entry;
507 }
508
509 bool canCache(uptr Size) {
510 return atomic_load_relaxed(A: &MaxEntriesCount) != 0U &&
511 Size <= atomic_load_relaxed(A: &MaxEntrySize);
512 }
513
514 bool setOption(Option O, sptr Value) {
515 if (O == Option::ReleaseInterval) {
516 const s32 Interval = Max(
517 Min(static_cast<s32>(Value), Config::getMaxReleaseToOsIntervalMs()),
518 Config::getMinReleaseToOsIntervalMs());
519 atomic_store_relaxed(A: &ReleaseToOsIntervalMs, V: Interval);
520 if (Interval >= 0) {
521 // Always trigger a trim if the interval is not being disabled.
522 ScopedLock L(Mutex);
523 trimResidentBytes(MaxResidentBytesLimit: atomic_load_relaxed(A: &MaxCacheResidentBytes));
524 }
525 return true;
526 }
527 if (O == Option::MaxCacheEntriesCount) {
528 if (Value < 0)
529 return false;
530 atomic_store_relaxed(
531 &MaxEntriesCount,
532 Min<u32>(static_cast<u32>(Value), Config::getEntriesArraySize()));
533 return true;
534 }
535 if (O == Option::MaxCacheEntrySize) {
536 atomic_store_relaxed(A: &MaxEntrySize, V: static_cast<uptr>(Value));
537 return true;
538 }
539 if (O == Option::MaxCacheResidentBytes) {
540 if (Value < 0)
541 return false;
542 const uptr NewMaxResidentBytes = static_cast<uptr>(Value);
543 atomic_store_relaxed(A: &MaxCacheResidentBytes, V: NewMaxResidentBytes);
544 if (NewMaxResidentBytes != 0) {
545 ScopedLock L(Mutex);
546 trimResidentBytes(MaxResidentBytesLimit: NewMaxResidentBytes);
547 }
548 return true;
549 }
550 // Not supported by the Secondary Cache, but not an error either.
551 return true;
552 }
553
554 void releaseToOS([[maybe_unused]] ReleaseToOS ReleaseType) EXCLUDES(Mutex) {
555 SCUDO_SCOPED_TRACE(GetSecondaryReleaseToOSTraceName(ReleaseType));
556
557 if (ReleaseType == ReleaseToOS::ForceFast) {
558 // Never wait for the lock, always move on if there is already
559 // a release operation in progress.
560 if (Mutex.tryLock()) {
561 releaseOlderThan(UINT64_MAX);
562 Mutex.unlock();
563 }
564 } else {
565 // Since this is a request to release everything, always wait for the
566 // lock so that we guarantee all entries are released after this call.
567 ScopedLock L(Mutex);
568 releaseOlderThan(UINT64_MAX);
569 }
570 }
571
572 void disableMemoryTagging() EXCLUDES(Mutex) {
573 if (Config::getQuarantineDisabled())
574 return;
575
576 ScopedLock L(Mutex);
577 for (u32 I = 0; I != Config::getQuarantineSize(); ++I) {
578 if (Quarantine[I].isValid()) {
579 MemMapT &MemMap = Quarantine[I].MemMap;
580 unmapCallBack(MemMap);
581 Quarantine[I].invalidate();
582 }
583 }
584 QuarantinePos = -1U;
585 }
586
587 void disable() NO_THREAD_SAFETY_ANALYSIS { Mutex.lock(); }
588
589 void enable() NO_THREAD_SAFETY_ANALYSIS { Mutex.unlock(); }
590
591 uptr getMaxResidentBytesTestOnly() {
592 ScopedLock L(Mutex);
593 return MaxResidentBytes;
594 }
595
596 uptr getCurrentResidentBytesTestOnly() {
597 ScopedLock L(Mutex);
598 return CurrentResidentBytes;
599 }
600
601 void unmapTestOnly() { empty(); }
602
603 void releaseOlderThanTestOnly(u64 ReleaseTime) {
604 ScopedLock L(Mutex);
605 releaseOlderThan(ReleaseTime);
606 }
607
608private:
609 void insert(const CachedBlock &Entry) REQUIRES(Mutex) {
610 CachedBlock *AvailEntry = AvailEntries.front();
611 AvailEntries.pop_front();
612
613 *AvailEntry = Entry;
614 LRUEntries.push_front(X: AvailEntry);
615 if (OldestPresentEntry == nullptr && AvailEntry->Time != 0)
616 OldestPresentEntry = AvailEntry;
617 if (AvailEntry->Time != 0) {
618 CurrentResidentBytes += Entry.CommitSize;
619 if (CurrentResidentBytes > MaxResidentBytes)
620 MaxResidentBytes = CurrentResidentBytes;
621 }
622 }
623
624 void remove(CachedBlock *Entry) REQUIRES(Mutex) {
625 DCHECK(Entry->isValid());
626 if (OldestPresentEntry == Entry) {
627 OldestPresentEntry = LRUEntries.getPrev(X: Entry);
628 DCHECK(OldestPresentEntry == nullptr || OldestPresentEntry->Time != 0);
629 }
630 LRUEntries.remove(X: Entry);
631 if (Entry->Time != 0)
632 CurrentResidentBytes -= Entry->CommitSize;
633 Entry->invalidate();
634 AvailEntries.push_front(X: Entry);
635 }
636
637 ALWAYS_INLINE void trimResidentBytes(uptr MaxResidentBytesLimit)
638 REQUIRES(Mutex) {
639 if (MaxResidentBytesLimit == 0 ||
640 atomic_load_relaxed(A: &ReleaseToOsIntervalMs) < 0)
641 return;
642 while (CurrentResidentBytes > MaxResidentBytesLimit &&
643 OldestPresentEntry != nullptr) {
644 CachedBlock *Entry = OldestPresentEntry;
645 OldestPresentEntry = LRUEntries.getPrev(X: Entry);
646 Entry->MemMap.releaseAndZeroPagesToOS(From: Entry->CommitBase,
647 Size: Entry->CommitSize);
648 CurrentResidentBytes -= Entry->CommitSize;
649 Entry->Time = 0;
650 }
651 }
652
653 void empty() {
654 MemMapT MapInfo[Config::getEntriesArraySize()];
655 uptr N = 0;
656 {
657 ScopedLock L(Mutex);
658
659 for (CachedBlock &Entry : LRUEntries)
660 MapInfo[N++] = Entry.MemMap;
661 LRUEntries.clear();
662 OldestPresentEntry = nullptr;
663 CurrentResidentBytes = 0;
664 }
665 for (uptr I = 0; I < N; I++) {
666 MemMapT &MemMap = MapInfo[I];
667 unmapCallBack(MemMap);
668 }
669 }
670
671 void releaseOlderThan(u64 ReleaseTime) REQUIRES(Mutex) {
672 SCUDO_SCOPED_TRACE(GetSecondaryReleaseOlderThanTraceName());
673
674 if (!Config::getQuarantineDisabled()) {
675 for (uptr I = 0; I < Config::getQuarantineSize(); I++) {
676 auto &Entry = Quarantine[I];
677 if (!Entry.isValid() || Entry.Time == 0 || Entry.Time > ReleaseTime)
678 continue;
679 Entry.MemMap.releaseAndZeroPagesToOS(Entry.CommitBase,
680 Entry.CommitSize);
681 Entry.Time = 0;
682 }
683 }
684
685 for (CachedBlock *Entry = OldestPresentEntry; Entry != nullptr;
686 Entry = LRUEntries.getPrev(X: Entry)) {
687 DCHECK(Entry->isValid());
688 DCHECK(Entry->Time != 0);
689
690 if (Entry->Time > ReleaseTime) {
691 // All entries are newer than this, so no need to keep scanning.
692 OldestPresentEntry = Entry;
693 return;
694 }
695
696 Entry->MemMap.releaseAndZeroPagesToOS(From: Entry->CommitBase,
697 Size: Entry->CommitSize);
698 CurrentResidentBytes -= Entry->CommitSize;
699 Entry->Time = 0;
700 }
701 OldestPresentEntry = nullptr;
702 }
703
704 HybridMutex Mutex;
705 u32 QuarantinePos GUARDED_BY(Mutex) = 0;
706 atomic_u32 MaxEntriesCount = {};
707 atomic_uptr MaxEntrySize = {};
708 atomic_uptr MaxCacheResidentBytes = {};
709 atomic_s32 ReleaseToOsIntervalMs = {};
710 u32 CallsToRetrieve GUARDED_BY(Mutex) = 0;
711 u32 SuccessfulRetrieves GUARDED_BY(Mutex) = 0;
712 u32 EvictedCount GUARDED_BY(Mutex) = 0;
713 uptr CurrentResidentBytes GUARDED_BY(Mutex) = 0;
714 uptr MaxResidentBytes GUARDED_BY(Mutex) = 0;
715 atomic_uptr ReleaseToOsSkips = {};
716
717 CachedBlock Entries[Config::getEntriesArraySize()] GUARDED_BY(Mutex) = {};
718 NonZeroLengthArray<CachedBlock, Config::getQuarantineSize()>
719 Quarantine GUARDED_BY(Mutex) = {};
720
721 // The oldest entry in the LRUEntries that has Time non-zero.
722 CachedBlock *OldestPresentEntry GUARDED_BY(Mutex) = nullptr;
723 // Cached blocks stored in LRU order
724 DoublyLinkedList<CachedBlock> LRUEntries GUARDED_BY(Mutex);
725 // The unused Entries
726 SinglyLinkedList<CachedBlock> AvailEntries GUARDED_BY(Mutex);
727};
728
729template <typename Config> class MapAllocator {
730public:
731 void init(GlobalStats *S,
732 s32 ReleaseToOsInterval = -1) NO_THREAD_SAFETY_ANALYSIS {
733 DCHECK_EQ(AllocatedBytes, 0U);
734 DCHECK_EQ(FreedBytes, 0U);
735 Cache.init(ReleaseToOsInterval);
736 Stats.init();
737 if (LIKELY(S))
738 S->link(S: &Stats);
739 }
740
741 void *allocate(const Options &Options, uptr Size, uptr AlignmentHint = 0,
742 uptr *BlockEnd = nullptr,
743 FillContentsMode FillContents = NoFill);
744
745 void deallocate(const Options &Options, void *Ptr);
746
747 void *tryAllocateFromCache(const Options &Options, uptr Size, uptr Alignment,
748 uptr *BlockEndPtr, FillContentsMode FillContents);
749
750 static uptr getBlockEnd(void *Ptr) {
751 auto *B = LargeBlock::getHeader<Config>(Ptr);
752 return B->CommitBase + B->CommitSize;
753 }
754
755 static uptr getBlockSize(void *Ptr) {
756 return getBlockEnd(Ptr) - reinterpret_cast<uptr>(Ptr);
757 }
758
759 static uptr getGuardPageSize() {
760 if (Config::getEnableGuardPages())
761 return getPageSizeCached();
762 return 0U;
763 }
764
765 static constexpr uptr getHeadersSize() {
766 return Chunk::getHeaderSize() + LargeBlock::getHeaderSize();
767 }
768
769 void disable() NO_THREAD_SAFETY_ANALYSIS {
770 Mutex.lock();
771 Cache.disable();
772 }
773
774 void enable() NO_THREAD_SAFETY_ANALYSIS {
775 Cache.enable();
776 Mutex.unlock();
777 }
778
779 template <typename F> void iterateOverBlocks(F Callback) const {
780 Mutex.assertHeld();
781
782 for (const auto &H : InUseBlocks) {
783 uptr Ptr = reinterpret_cast<uptr>(&H) + LargeBlock::getHeaderSize();
784 if (allocatorSupportsMemoryTagging<Config>())
785 Ptr = untagPointer(Ptr);
786 Callback(Ptr);
787 }
788 }
789
790 bool canCache(uptr Size) { return Cache.canCache(Size); }
791
792 bool setOption(Option O, sptr Value) { return Cache.setOption(O, Value); }
793
794 void releaseToOS(ReleaseToOS ReleaseType) { Cache.releaseToOS(ReleaseType); }
795
796 void disableMemoryTagging() { Cache.disableMemoryTagging(); }
797
798 void unmapTestOnly() { Cache.unmapTestOnly(); }
799
800 uptr getMaxResidentBytesTestOnly() {
801 return Cache.getMaxResidentBytesTestOnly();
802 }
803
804 uptr getCurrentResidentBytesTestOnly() {
805 return Cache.getCurrentResidentBytesTestOnly();
806 }
807
808 void getStats(ScopedString *Str);
809
810private:
811 typename Config::template CacheT<typename Config::CacheConfig> Cache;
812
813 mutable HybridMutex Mutex;
814 DoublyLinkedList<LargeBlock::Header> InUseBlocks GUARDED_BY(Mutex);
815 uptr AllocatedBytes GUARDED_BY(Mutex) = 0;
816 uptr FreedBytes GUARDED_BY(Mutex) = 0;
817 uptr FragmentedBytes GUARDED_BY(Mutex) = 0;
818 uptr LargestSize GUARDED_BY(Mutex) = 0;
819 u32 UncacheableUnmaps GUARDED_BY(Mutex) = 0;
820 u32 NumberOfAllocs GUARDED_BY(Mutex) = 0;
821 u32 NumberOfFrees GUARDED_BY(Mutex) = 0;
822 LocalStats Stats GUARDED_BY(Mutex);
823};
824
825template <typename Config>
826void *
827MapAllocator<Config>::tryAllocateFromCache(const Options &Options, uptr Size,
828 uptr Alignment, uptr *BlockEndPtr,
829 FillContentsMode FillContents) {
830 CachedBlock Entry;
831 uptr EntryHeaderPos;
832 uptr MaxAllowedFragmentedPages = MaxUnreleasedCachePages;
833
834 if (LIKELY(!useMemoryTagging<Config>(Options))) {
835 MaxAllowedFragmentedPages += CachedBlock::MaxReleasedCachePages;
836 } else {
837 // TODO: Enable MaxReleasedCachePages may result in pages for an entry being
838 // partially released and it erases the tag of those pages as well. To
839 // support this feature for MTE, we need to tag those pages again.
840 DCHECK_EQ(MaxAllowedFragmentedPages, MaxUnreleasedCachePages);
841 }
842
843 Entry = Cache.retrieve(MaxAllowedFragmentedPages, Size, Alignment,
844 getHeadersSize(), EntryHeaderPos);
845 if (!Entry.isValid())
846 return nullptr;
847
848 LargeBlock::Header *H = reinterpret_cast<LargeBlock::Header *>(
849 LargeBlock::addHeaderTag<Config>(EntryHeaderPos));
850 bool Zeroed = Entry.Time == 0;
851
852 if (UNLIKELY(Entry.Flags & CachedBlock::NoAccess)) {
853 // NOTE: Flags set to 0 actually restores read-write.
854 Entry.MemMap.setMemoryPermission(Addr: Entry.CommitBase, Size: Entry.CommitSize,
855 /*Flags=*/Flags: 0);
856 }
857
858 if (useMemoryTagging<Config>(Options)) {
859 const uptr PageSize = getPageSizeCached();
860 const uptr OldAllocPos =
861 untagPointer(Ptr: Entry.BlockBegin) + Chunk::getHeaderSize();
862 const uptr NewAllocPos = untagPointer(Ptr: roundUp(X: EntryHeaderPos, Boundary: Alignment));
863 DCHECK_GE(Alignment, PageSize);
864
865 const uptr OldHeaderPage = OldAllocPos - PageSize;
866 const uptr NewHeaderPage = NewAllocPos - PageSize;
867
868 // Enabling or disabling memory tagging at runtime is unsupported.
869 // If MTE is enabled now, the cached entry was also allocated with MTE
870 // enabled, guaranteeing that both OldAllocPos and NewAllocPos are
871 // page-aligned.
872 CHECK(OldAllocPos % PageSize == 0U);
873 DCHECK(NewAllocPos % PageSize == 0U);
874
875 if (NewAllocPos != OldAllocPos) {
876 // The shift distance must be a multiple of PageSize
877 DCHECK_EQ((NewAllocPos > OldAllocPos ? NewAllocPos - OldAllocPos
878 : OldAllocPos - NewAllocPos) %
879 PageSize,
880 0U);
881
882 const uptr MappingFlags = MAP_RESIZABLE | MAP_ALLOWNOMEM;
883
884 if (!Entry.MemMap.remap(Addr: NewHeaderPage, Size: PageSize, Name: "scudo:secondary",
885 MAP_MEMTAG | MappingFlags)) {
886 unmap(MemMap&: Entry.MemMap);
887 return nullptr;
888 }
889 // Since PROT_MTE is sticky, setting memory permissions to MAP_NOACCESS
890 // (PROT_NONE) when caching the block does not clear the PROT_MTE flag
891 // from the kernel VMA. When we make the block RW again, the old header
892 // page still has MTE enabled. If the allocation shifted, we must
893 // explicitly remap the old header page without MAP_MEMTAG to disable MTE,
894 // as this page may now be part of the user payload or padding.
895 if (!Entry.MemMap.remap(Addr: OldHeaderPage, Size: PageSize, Name: "scudo:secondary",
896 Flags: MappingFlags)) {
897 unmap(MemMap&: Entry.MemMap);
898 return nullptr;
899 }
900 }
901
902 uptr NewBlockBegin = reinterpret_cast<uptr>(H + 1);
903 storeTags(Begin: reinterpret_cast<uptr>(H), End: NewBlockBegin);
904 }
905
906 H->CommitBase = Entry.CommitBase;
907 H->CommitSize = Entry.CommitSize;
908 H->MemMap = Entry.MemMap;
909
910 const uptr BlockEnd = H->CommitBase + H->CommitSize;
911 if (BlockEndPtr)
912 *BlockEndPtr = BlockEnd;
913 uptr HInt = reinterpret_cast<uptr>(H);
914 if (allocatorSupportsMemoryTagging<Config>())
915 HInt = untagPointer(Ptr: HInt);
916 const uptr PtrInt = HInt + LargeBlock::getHeaderSize();
917 void *Ptr = reinterpret_cast<void *>(PtrInt);
918 if (FillContents && !Zeroed)
919 memset(s: Ptr, c: FillContents == ZeroFill ? 0 : PatternFillByte,
920 n: BlockEnd - PtrInt);
921 {
922 ScopedLock L(Mutex);
923 InUseBlocks.push_back(X: H);
924 AllocatedBytes += H->CommitSize;
925 FragmentedBytes += H->MemMap.getCapacity() - H->CommitSize;
926 NumberOfAllocs++;
927 Stats.add(I: StatAllocated, V: H->CommitSize);
928 Stats.add(I: StatMapped, V: H->MemMap.getCapacity());
929 }
930 return Ptr;
931}
932// As with the Primary, the size passed to this function includes any desired
933// alignment, so that the frontend can align the user allocation. The hint
934// parameter allows us to unmap spurious memory when dealing with larger
935// (greater than a page) alignments on 32-bit platforms.
936// Due to the sparsity of address space available on those platforms, requesting
937// an allocation from the Secondary with a large alignment would end up wasting
938// VA space (even though we are not committing the whole thing), hence the need
939// to trim off some of the reserved space.
940// For allocations requested with an alignment greater than or equal to a page,
941// the committed memory will amount to something close to Size - AlignmentHint
942// (pending rounding and headers).
943template <typename Config>
944void *MapAllocator<Config>::allocate(const Options &Options, uptr Size,
945 uptr Alignment, uptr *BlockEndPtr,
946 FillContentsMode FillContents) {
947 if (Options.get(Opt: OptionBit::AddLargeAllocationSlack))
948 Size += 1UL << SCUDO_MIN_ALIGNMENT_LOG;
949 Alignment = Max(A: Alignment, B: uptr(1U) << SCUDO_MIN_ALIGNMENT_LOG);
950 const uptr PageSize = getPageSizeCached();
951
952 if (useMemoryTagging<Config>(Options))
953 Alignment = Max(A: Alignment, B: PageSize);
954
955 // Note that cached blocks may have aligned address already. Thus we simply
956 // pass the required size (`Size` + `getHeadersSize()`) to do cache look up.
957 const uptr MinNeededSizeForCache = roundUp(X: Size + getHeadersSize(), Boundary: PageSize);
958
959 if (Alignment <= PageSize && Cache.canCache(MinNeededSizeForCache)) {
960 void *Ptr = tryAllocateFromCache(Options, Size, Alignment, BlockEndPtr,
961 FillContents);
962 if (Ptr != nullptr)
963 return Ptr;
964 }
965
966 uptr RoundedSize =
967 roundUp(X: roundUp(X: Size, Boundary: Alignment) + getHeadersSize(), Boundary: PageSize);
968 if (UNLIKELY(Alignment > PageSize))
969 RoundedSize += Alignment - PageSize;
970
971 ReservedMemoryT ReservedMemory;
972 const uptr MapSize = RoundedSize + 2 * getGuardPageSize();
973 if (UNLIKELY(!ReservedMemory.create(/*Addr=*/0U, MapSize, nullptr,
974 MAP_ALLOWNOMEM))) {
975 return nullptr;
976 }
977
978 // Take the entire ownership of reserved region.
979 MemMapT MemMap = ReservedMemory.dispatch(Addr: ReservedMemory.getBase(),
980 Size: ReservedMemory.getCapacity());
981 uptr MapBase = MemMap.getBase();
982 uptr CommitBase = MapBase + getGuardPageSize();
983 uptr MapEnd = MapBase + MapSize;
984
985 // In the unlikely event of alignments larger than a page, adjust the amount
986 // of memory we want to commit, and trim the extra memory.
987 if (UNLIKELY(Alignment >= PageSize)) {
988 // For alignments greater than or equal to a page, the user pointer (eg:
989 // the pointer that is returned by the C or C++ allocation APIs) ends up
990 // on a page boundary , and our headers will live in the preceding page.
991 CommitBase =
992 roundUp(X: MapBase + getGuardPageSize() + 1, Boundary: Alignment) - PageSize;
993 // We only trim the extra memory on 32-bit platforms: 64-bit platforms
994 // are less constrained memory wise, and that saves us two syscalls.
995 if (SCUDO_WORDSIZE == 32U) {
996 const uptr NewMapBase = CommitBase - getGuardPageSize();
997 DCHECK_GE(NewMapBase, MapBase);
998 if (NewMapBase != MapBase) {
999 MemMap.unmap(Addr: MapBase, Size: NewMapBase - MapBase);
1000 MapBase = NewMapBase;
1001 }
1002 // CommitBase is past the first guard page, but this computation needs
1003 // to include a page where the header lives.
1004 const uptr NewMapEnd =
1005 CommitBase + PageSize + roundUp(X: Size, Boundary: PageSize) + getGuardPageSize();
1006 DCHECK_LE(NewMapEnd, MapEnd);
1007 if (NewMapEnd != MapEnd) {
1008 MemMap.unmap(Addr: NewMapEnd, Size: MapEnd - NewMapEnd);
1009 MapEnd = NewMapEnd;
1010 }
1011 }
1012 }
1013
1014 const uptr CommitSize = MapEnd - getGuardPageSize() - CommitBase;
1015 const uptr AllocPos = roundDown(X: CommitBase + CommitSize - Size, Boundary: Alignment);
1016 if (!mapSecondary<Config>(Options, CommitBase, CommitSize, AllocPos, 0,
1017 MemMap)) {
1018 MemMap.unmap();
1019 return nullptr;
1020 }
1021 const uptr HeaderPos = AllocPos - getHeadersSize();
1022 // Make sure that the header is not in the guard page or before the base.
1023 DCHECK_GE(HeaderPos, MapBase + getGuardPageSize());
1024 LargeBlock::Header *H = reinterpret_cast<LargeBlock::Header *>(
1025 LargeBlock::addHeaderTag<Config>(HeaderPos));
1026 if (useMemoryTagging<Config>(Options))
1027 storeTags(Begin: reinterpret_cast<uptr>(H), End: reinterpret_cast<uptr>(H + 1));
1028 H->CommitBase = CommitBase;
1029 H->CommitSize = CommitSize;
1030 H->MemMap = MemMap;
1031 if (BlockEndPtr)
1032 *BlockEndPtr = CommitBase + CommitSize;
1033 {
1034 ScopedLock L(Mutex);
1035 InUseBlocks.push_back(X: H);
1036 AllocatedBytes += CommitSize;
1037 FragmentedBytes += H->MemMap.getCapacity() - CommitSize;
1038 if (LargestSize < CommitSize)
1039 LargestSize = CommitSize;
1040 NumberOfAllocs++;
1041 Stats.add(I: StatAllocated, V: CommitSize);
1042 Stats.add(I: StatMapped, V: H->MemMap.getCapacity());
1043 }
1044 return reinterpret_cast<void *>(HeaderPos + LargeBlock::getHeaderSize());
1045}
1046
1047template <typename Config>
1048void MapAllocator<Config>::deallocate(const Options &Options, void *Ptr)
1049 EXCLUDES(Mutex) {
1050 LargeBlock::Header *H = LargeBlock::getHeader<Config>(Ptr);
1051 const uptr CommitSize = H->CommitSize;
1052 {
1053 ScopedLock L(Mutex);
1054 InUseBlocks.remove(X: H);
1055 FreedBytes += CommitSize;
1056 FragmentedBytes -= H->MemMap.getCapacity() - CommitSize;
1057 NumberOfFrees++;
1058 Stats.sub(I: StatAllocated, V: CommitSize);
1059 Stats.sub(I: StatMapped, V: H->MemMap.getCapacity());
1060 }
1061
1062 if (Cache.canCache(H->CommitSize)) {
1063 Cache.store(Options, H->CommitBase, H->CommitSize,
1064 reinterpret_cast<uptr>(H + 1), H->MemMap);
1065 } else {
1066 // Note that the `H->MemMap` is stored on the pages managed by itself. Take
1067 // over the ownership before unmap() so that any operation along with
1068 // unmap() won't touch inaccessible pages.
1069 MemMapT MemMap = H->MemMap;
1070 unmap(MemMap);
1071 ScopedLock L(Mutex);
1072 UncacheableUnmaps++;
1073 }
1074}
1075
1076template <typename Config>
1077void MapAllocator<Config>::getStats(ScopedString *Str) EXCLUDES(Mutex) {
1078 ScopedLock L(Mutex);
1079 Str->append(
1080 Format: "Stats: MapAllocator: allocated %u times (%zuK), freed %u times (%zuK), "
1081 "remains %u (%zuK) max %zuM, Fragmented %zuK, Uncacheable unmaps: %u\n",
1082 NumberOfAllocs, AllocatedBytes >> 10, NumberOfFrees, FreedBytes >> 10,
1083 NumberOfAllocs - NumberOfFrees, (AllocatedBytes - FreedBytes) >> 10,
1084 LargestSize >> 20, FragmentedBytes >> 10, UncacheableUnmaps);
1085 Cache.getStats(Str);
1086}
1087
1088} // namespace scudo
1089
1090#endif // SCUDO_SECONDARY_H_
1091