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)
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 // The default value in the cache config has the higher priority.
281 if (Config::getDefaultReleaseToOsIntervalMs() != INT32_MIN)
282 ReleaseToOsInterval = Config::getDefaultReleaseToOsIntervalMs();
283 setOption(O: Option::ReleaseInterval, Value: static_cast<sptr>(ReleaseToOsInterval));
284
285 LRUEntries.clear();
286 LRUEntries.init(Base: Entries, BaseSize: sizeof(Entries));
287 OldestPresentEntry = nullptr;
288
289 AvailEntries.clear();
290 AvailEntries.init(Base: Entries, BaseSize: sizeof(Entries));
291 for (u32 I = 0; I < Config::getEntriesArraySize(); I++)
292 AvailEntries.push_back(X: &Entries[I]);
293 }
294
295 void store(const Options &Options, uptr CommitBase, uptr CommitSize,
296 uptr BlockBegin, MemMapT MemMap) EXCLUDES(Mutex) {
297 DCHECK(canCache(CommitSize));
298
299 const s32 Interval = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
300 u64 Time;
301 CachedBlock Entry;
302
303 Entry.CommitBase = CommitBase;
304 Entry.CommitSize = CommitSize;
305 Entry.BlockBegin = BlockBegin;
306 Entry.MemMap = MemMap;
307 Entry.Time = UINT64_MAX;
308 Entry.Flags = CachedBlock::None;
309
310 bool MemoryTaggingEnabled = useMemoryTagging<Config>(Options);
311 if (MemoryTaggingEnabled) {
312 if (Interval == 0 && !SCUDO_FUCHSIA) {
313 Entry.Time = 0;
314 Entry.MemMap.releaseAndZeroPagesToOS(From: Entry.CommitBase,
315 Size: Entry.CommitSize);
316 }
317 // MAP_NOACCESS or PROT_NONE does not strip PROT_MTE.
318 Entry.MemMap.setMemoryPermission(Addr: Entry.CommitBase, Size: Entry.CommitSize,
319 MAP_NOACCESS);
320 Entry.Flags = CachedBlock::NoAccess;
321 }
322
323 // Usually only one entry will be evicted from the cache.
324 // Only in the rare event that the cache shrinks in real-time
325 // due to a decrease in the configurable value MaxEntriesCount
326 // will more than one cache entry be evicted.
327 // The vector is used to save the MemMaps of evicted entries so
328 // that the unmap call can be performed outside the lock
329 Vector<MemMapT, 1U> EvictionMemMaps;
330
331 do {
332 ScopedLock L(Mutex);
333
334 // Time must be computed under the lock to ensure
335 // that the LRU cache remains sorted with respect to
336 // time in a multithreaded environment
337 Time = getMonotonicTimeFast();
338 if (Entry.Time != 0)
339 Entry.Time = Time;
340
341 if (MemoryTaggingEnabled && !useMemoryTagging<Config>(Options)) {
342 // If we get here then memory tagging was disabled in between when we
343 // read Options and when we locked Mutex. We can't insert our entry into
344 // the quarantine or the cache because the permissions would be wrong so
345 // just unmap it.
346 unmapCallBack(Entry.MemMap);
347 break;
348 }
349
350 if (!Config::getQuarantineDisabled() && Config::getQuarantineSize()) {
351 QuarantinePos =
352 (QuarantinePos + 1) % Max(Config::getQuarantineSize(), 1u);
353 if (!Quarantine[QuarantinePos].isValid()) {
354 Quarantine[QuarantinePos] = Entry;
355 return;
356 }
357 CachedBlock PrevEntry = Quarantine[QuarantinePos];
358 Quarantine[QuarantinePos] = Entry;
359 Entry = PrevEntry;
360 }
361
362 // All excess entries are evicted from the cache. Note that when
363 // `MaxEntriesCount` is zero, cache storing shouldn't happen and it's
364 // guarded by the `DCHECK(canCache(CommitSize))` above. As a result, we
365 // won't try to pop `LRUEntries` when it's empty.
366 while (LRUEntries.size() >= atomic_load_relaxed(A: &MaxEntriesCount)) {
367 // Save MemMaps of evicted entries to perform unmap outside of lock
368 CachedBlock *Entry = LRUEntries.back();
369 EvictedCount++;
370 EvictionMemMaps.push_back(Element: Entry->MemMap);
371 remove(Entry);
372 }
373
374 insert(Entry);
375 } while (0);
376
377 for (MemMapT &EvictMemMap : EvictionMemMaps)
378 unmapCallBack(EvictMemMap);
379
380 if (Interval >= 0) {
381 // It is very likely that multiple threads trying to do a release at the
382 // same time will not actually release any extra elements. Therefore,
383 // let any other thread continue, skipping the release.
384 if (Mutex.tryLock()) {
385 SCUDO_SCOPED_TRACE(
386 GetSecondaryReleaseToOSTraceName(ReleaseToOS::Normal));
387
388 releaseOlderThan(ReleaseTime: Time - static_cast<u64>(Interval) * 1000000);
389 Mutex.unlock();
390 } else
391 atomic_fetch_add(A: &ReleaseToOsSkips, V: 1U, MO: memory_order_relaxed);
392 }
393 }
394
395 CachedBlock retrieve(uptr MaxAllowedFragmentedPages, uptr Size,
396 uptr Alignment, uptr HeadersSize, uptr &EntryHeaderPos)
397 EXCLUDES(Mutex) {
398 const uptr PageSize = getPageSizeCached();
399 // 10% of the requested size proved to be the optimal choice for
400 // retrieving cached blocks after testing several options.
401 constexpr u32 FragmentedBytesDivisor = 10;
402 CachedBlock Entry;
403 EntryHeaderPos = 0;
404 {
405 ScopedLock L(Mutex);
406 CallsToRetrieve++;
407 if (LRUEntries.size() == 0)
408 return {};
409 CachedBlock *RetrievedEntry = nullptr;
410 uptr MinDiff = UINTPTR_MAX;
411
412 // Since allocation sizes don't always match cached memory chunk sizes
413 // we allow some memory to be unused (called fragmented bytes). The
414 // amount of unused bytes is exactly EntryHeaderPos - CommitBase.
415 //
416 // CommitBase CommitBase + CommitSize
417 // V V
418 // +---+------------+-----------------+---+
419 // | | | | |
420 // +---+------------+-----------------+---+
421 // ^ ^ ^
422 // Guard EntryHeaderPos Guard-page-end
423 // page-begin
424 //
425 // [EntryHeaderPos, CommitBase + CommitSize) contains the user data as
426 // well as the header metadata. If EntryHeaderPos - CommitBase exceeds
427 // MaxAllowedFragmentedPages * PageSize, the cached memory chunk is
428 // not considered valid for retrieval.
429 for (CachedBlock &Entry : LRUEntries) {
430 const uptr CommitBase = Entry.CommitBase;
431 const uptr CommitSize = Entry.CommitSize;
432 const uptr AllocPos =
433 roundDown(X: CommitBase + CommitSize - Size, Boundary: Alignment);
434 const uptr HeaderPos = AllocPos - HeadersSize;
435 const uptr MaxAllowedFragmentedBytes =
436 MaxAllowedFragmentedPages * PageSize;
437 if (HeaderPos > CommitBase + CommitSize)
438 continue;
439 // TODO: Remove AllocPos > CommitBase + MaxAllowedFragmentedBytes
440 // and replace with Diff > MaxAllowedFragmentedBytes
441 if (HeaderPos < CommitBase ||
442 AllocPos > CommitBase + MaxAllowedFragmentedBytes) {
443 continue;
444 }
445
446 const uptr Diff = roundDown(X: HeaderPos, Boundary: PageSize) - CommitBase;
447
448 // Keep track of the smallest cached block
449 // that is greater than (AllocSize + HeaderSize)
450 if (Diff >= MinDiff)
451 continue;
452
453 MinDiff = Diff;
454 RetrievedEntry = &Entry;
455 EntryHeaderPos = HeaderPos;
456
457 // Immediately use a cached block if its size is close enough to the
458 // requested size
459 const uptr OptimalFitThesholdBytes =
460 (CommitBase + CommitSize - HeaderPos) / FragmentedBytesDivisor;
461 if (Diff <= OptimalFitThesholdBytes)
462 break;
463 }
464
465 if (RetrievedEntry != nullptr) {
466 Entry = *RetrievedEntry;
467 remove(Entry: RetrievedEntry);
468 SuccessfulRetrieves++;
469 }
470 }
471
472 // The difference between the retrieved memory chunk and the request
473 // size is at most MaxAllowedFragmentedPages
474 //
475 // +- MaxAllowedFragmentedPages * PageSize -+
476 // +--------------------------+-------------+
477 // | | |
478 // +--------------------------+-------------+
479 // \ Bytes to be released / ^
480 // |
481 // (may or may not be committed)
482 //
483 // The maximum number of bytes released to the OS is capped by
484 // MaxReleasedCachePages
485 //
486 // TODO : Consider making MaxReleasedCachePages configurable since
487 // the release to OS API can vary across systems.
488 if (Entry.Time != 0) {
489 const uptr FragmentedBytes =
490 roundDown(X: EntryHeaderPos, Boundary: PageSize) - Entry.CommitBase;
491 const uptr MaxUnreleasedCacheBytes = MaxUnreleasedCachePages * PageSize;
492 if (FragmentedBytes > MaxUnreleasedCacheBytes) {
493 const uptr MaxReleasedCacheBytes =
494 CachedBlock::MaxReleasedCachePages * PageSize;
495 uptr BytesToRelease =
496 roundUp(X: Min<uptr>(A: MaxReleasedCacheBytes,
497 B: FragmentedBytes - MaxUnreleasedCacheBytes),
498 Boundary: PageSize);
499 Entry.MemMap.releaseAndZeroPagesToOS(From: Entry.CommitBase, Size: BytesToRelease);
500 }
501 }
502
503 return Entry;
504 }
505
506 bool canCache(uptr Size) {
507 return atomic_load_relaxed(A: &MaxEntriesCount) != 0U &&
508 Size <= atomic_load_relaxed(A: &MaxEntrySize);
509 }
510
511 bool setOption(Option O, sptr Value) {
512 if (O == Option::ReleaseInterval) {
513 const s32 Interval = Max(
514 Min(static_cast<s32>(Value), Config::getMaxReleaseToOsIntervalMs()),
515 Config::getMinReleaseToOsIntervalMs());
516 atomic_store_relaxed(A: &ReleaseToOsIntervalMs, V: Interval);
517 return true;
518 }
519 if (O == Option::MaxCacheEntriesCount) {
520 if (Value < 0)
521 return false;
522 atomic_store_relaxed(
523 &MaxEntriesCount,
524 Min<u32>(static_cast<u32>(Value), Config::getEntriesArraySize()));
525 return true;
526 }
527 if (O == Option::MaxCacheEntrySize) {
528 atomic_store_relaxed(A: &MaxEntrySize, V: static_cast<uptr>(Value));
529 return true;
530 }
531 // Not supported by the Secondary Cache, but not an error either.
532 return true;
533 }
534
535 void releaseToOS([[maybe_unused]] ReleaseToOS ReleaseType) EXCLUDES(Mutex) {
536 SCUDO_SCOPED_TRACE(GetSecondaryReleaseToOSTraceName(ReleaseType));
537
538 if (ReleaseType == ReleaseToOS::ForceFast) {
539 // Never wait for the lock, always move on if there is already
540 // a release operation in progress.
541 if (Mutex.tryLock()) {
542 releaseOlderThan(UINT64_MAX);
543 Mutex.unlock();
544 }
545 } else {
546 // Since this is a request to release everything, always wait for the
547 // lock so that we guarantee all entries are released after this call.
548 ScopedLock L(Mutex);
549 releaseOlderThan(UINT64_MAX);
550 }
551 }
552
553 void disableMemoryTagging() EXCLUDES(Mutex) {
554 if (Config::getQuarantineDisabled())
555 return;
556
557 ScopedLock L(Mutex);
558 for (u32 I = 0; I != Config::getQuarantineSize(); ++I) {
559 if (Quarantine[I].isValid()) {
560 MemMapT &MemMap = Quarantine[I].MemMap;
561 unmapCallBack(MemMap);
562 Quarantine[I].invalidate();
563 }
564 }
565 QuarantinePos = -1U;
566 }
567
568 void disable() NO_THREAD_SAFETY_ANALYSIS { Mutex.lock(); }
569
570 void enable() NO_THREAD_SAFETY_ANALYSIS { Mutex.unlock(); }
571
572 uptr getMaxResidentBytesTestOnly() {
573 ScopedLock L(Mutex);
574 return MaxResidentBytes;
575 }
576
577 uptr getCurrentResidentBytesTestOnly() {
578 ScopedLock L(Mutex);
579 return CurrentResidentBytes;
580 }
581
582 void unmapTestOnly() { empty(); }
583
584 void releaseOlderThanTestOnly(u64 ReleaseTime) {
585 ScopedLock L(Mutex);
586 releaseOlderThan(ReleaseTime);
587 }
588
589private:
590 void insert(const CachedBlock &Entry) REQUIRES(Mutex) {
591 CachedBlock *AvailEntry = AvailEntries.front();
592 AvailEntries.pop_front();
593
594 *AvailEntry = Entry;
595 LRUEntries.push_front(X: AvailEntry);
596 if (OldestPresentEntry == nullptr && AvailEntry->Time != 0)
597 OldestPresentEntry = AvailEntry;
598 if (AvailEntry->Time != 0) {
599 CurrentResidentBytes += Entry.CommitSize;
600 if (CurrentResidentBytes > MaxResidentBytes)
601 MaxResidentBytes = CurrentResidentBytes;
602 }
603 }
604
605 void remove(CachedBlock *Entry) REQUIRES(Mutex) {
606 DCHECK(Entry->isValid());
607 if (OldestPresentEntry == Entry) {
608 OldestPresentEntry = LRUEntries.getPrev(X: Entry);
609 DCHECK(OldestPresentEntry == nullptr || OldestPresentEntry->Time != 0);
610 }
611 LRUEntries.remove(X: Entry);
612 if (Entry->Time != 0)
613 CurrentResidentBytes -= Entry->CommitSize;
614 Entry->invalidate();
615 AvailEntries.push_front(X: Entry);
616 }
617
618 void empty() {
619 MemMapT MapInfo[Config::getEntriesArraySize()];
620 uptr N = 0;
621 {
622 ScopedLock L(Mutex);
623
624 for (CachedBlock &Entry : LRUEntries)
625 MapInfo[N++] = Entry.MemMap;
626 LRUEntries.clear();
627 OldestPresentEntry = nullptr;
628 CurrentResidentBytes = 0;
629 }
630 for (uptr I = 0; I < N; I++) {
631 MemMapT &MemMap = MapInfo[I];
632 unmapCallBack(MemMap);
633 }
634 }
635
636 void releaseOlderThan(u64 ReleaseTime) REQUIRES(Mutex) {
637 SCUDO_SCOPED_TRACE(GetSecondaryReleaseOlderThanTraceName());
638
639 if (!Config::getQuarantineDisabled()) {
640 for (uptr I = 0; I < Config::getQuarantineSize(); I++) {
641 auto &Entry = Quarantine[I];
642 if (!Entry.isValid() || Entry.Time == 0 || Entry.Time > ReleaseTime)
643 continue;
644 Entry.MemMap.releaseAndZeroPagesToOS(Entry.CommitBase,
645 Entry.CommitSize);
646 Entry.Time = 0;
647 }
648 }
649
650 for (CachedBlock *Entry = OldestPresentEntry; Entry != nullptr;
651 Entry = LRUEntries.getPrev(X: Entry)) {
652 DCHECK(Entry->isValid());
653 DCHECK(Entry->Time != 0);
654
655 if (Entry->Time > ReleaseTime) {
656 // All entries are newer than this, so no need to keep scanning.
657 OldestPresentEntry = Entry;
658 return;
659 }
660
661 Entry->MemMap.releaseAndZeroPagesToOS(From: Entry->CommitBase,
662 Size: Entry->CommitSize);
663 CurrentResidentBytes -= Entry->CommitSize;
664 Entry->Time = 0;
665 }
666 OldestPresentEntry = nullptr;
667 }
668
669 HybridMutex Mutex;
670 u32 QuarantinePos GUARDED_BY(Mutex) = 0;
671 atomic_u32 MaxEntriesCount = {};
672 atomic_uptr MaxEntrySize = {};
673 atomic_s32 ReleaseToOsIntervalMs = {};
674 u32 CallsToRetrieve GUARDED_BY(Mutex) = 0;
675 u32 SuccessfulRetrieves GUARDED_BY(Mutex) = 0;
676 u32 EvictedCount GUARDED_BY(Mutex) = 0;
677 uptr CurrentResidentBytes GUARDED_BY(Mutex) = 0;
678 uptr MaxResidentBytes GUARDED_BY(Mutex) = 0;
679 atomic_uptr ReleaseToOsSkips = {};
680
681 CachedBlock Entries[Config::getEntriesArraySize()] GUARDED_BY(Mutex) = {};
682 NonZeroLengthArray<CachedBlock, Config::getQuarantineSize()>
683 Quarantine GUARDED_BY(Mutex) = {};
684
685 // The oldest entry in the LRUEntries that has Time non-zero.
686 CachedBlock *OldestPresentEntry GUARDED_BY(Mutex) = nullptr;
687 // Cached blocks stored in LRU order
688 DoublyLinkedList<CachedBlock> LRUEntries GUARDED_BY(Mutex);
689 // The unused Entries
690 SinglyLinkedList<CachedBlock> AvailEntries GUARDED_BY(Mutex);
691};
692
693template <typename Config> class MapAllocator {
694public:
695 void init(GlobalStats *S,
696 s32 ReleaseToOsInterval = -1) NO_THREAD_SAFETY_ANALYSIS {
697 DCHECK_EQ(AllocatedBytes, 0U);
698 DCHECK_EQ(FreedBytes, 0U);
699 Cache.init(ReleaseToOsInterval);
700 Stats.init();
701 if (LIKELY(S))
702 S->link(S: &Stats);
703 }
704
705 void *allocate(const Options &Options, uptr Size, uptr AlignmentHint = 0,
706 uptr *BlockEnd = nullptr,
707 FillContentsMode FillContents = NoFill);
708
709 void deallocate(const Options &Options, void *Ptr);
710
711 void *tryAllocateFromCache(const Options &Options, uptr Size, uptr Alignment,
712 uptr *BlockEndPtr, FillContentsMode FillContents);
713
714 static uptr getBlockEnd(void *Ptr) {
715 auto *B = LargeBlock::getHeader<Config>(Ptr);
716 return B->CommitBase + B->CommitSize;
717 }
718
719 static uptr getBlockSize(void *Ptr) {
720 return getBlockEnd(Ptr) - reinterpret_cast<uptr>(Ptr);
721 }
722
723 static uptr getGuardPageSize() {
724 if (Config::getEnableGuardPages())
725 return getPageSizeCached();
726 return 0U;
727 }
728
729 static constexpr uptr getHeadersSize() {
730 return Chunk::getHeaderSize() + LargeBlock::getHeaderSize();
731 }
732
733 void disable() NO_THREAD_SAFETY_ANALYSIS {
734 Mutex.lock();
735 Cache.disable();
736 }
737
738 void enable() NO_THREAD_SAFETY_ANALYSIS {
739 Cache.enable();
740 Mutex.unlock();
741 }
742
743 template <typename F> void iterateOverBlocks(F Callback) const {
744 Mutex.assertHeld();
745
746 for (const auto &H : InUseBlocks) {
747 uptr Ptr = reinterpret_cast<uptr>(&H) + LargeBlock::getHeaderSize();
748 if (allocatorSupportsMemoryTagging<Config>())
749 Ptr = untagPointer(Ptr);
750 Callback(Ptr);
751 }
752 }
753
754 bool canCache(uptr Size) { return Cache.canCache(Size); }
755
756 bool setOption(Option O, sptr Value) { return Cache.setOption(O, Value); }
757
758 void releaseToOS(ReleaseToOS ReleaseType) { Cache.releaseToOS(ReleaseType); }
759
760 void disableMemoryTagging() { Cache.disableMemoryTagging(); }
761
762 void unmapTestOnly() { Cache.unmapTestOnly(); }
763
764 uptr getMaxResidentBytesTestOnly() {
765 return Cache.getMaxResidentBytesTestOnly();
766 }
767
768 uptr getCurrentResidentBytesTestOnly() {
769 return Cache.getCurrentResidentBytesTestOnly();
770 }
771
772 void getStats(ScopedString *Str);
773
774private:
775 typename Config::template CacheT<typename Config::CacheConfig> Cache;
776
777 mutable HybridMutex Mutex;
778 DoublyLinkedList<LargeBlock::Header> InUseBlocks GUARDED_BY(Mutex);
779 uptr AllocatedBytes GUARDED_BY(Mutex) = 0;
780 uptr FreedBytes GUARDED_BY(Mutex) = 0;
781 uptr FragmentedBytes GUARDED_BY(Mutex) = 0;
782 uptr LargestSize GUARDED_BY(Mutex) = 0;
783 u32 UncacheableUnmaps GUARDED_BY(Mutex) = 0;
784 u32 NumberOfAllocs GUARDED_BY(Mutex) = 0;
785 u32 NumberOfFrees GUARDED_BY(Mutex) = 0;
786 LocalStats Stats GUARDED_BY(Mutex);
787};
788
789template <typename Config>
790void *
791MapAllocator<Config>::tryAllocateFromCache(const Options &Options, uptr Size,
792 uptr Alignment, uptr *BlockEndPtr,
793 FillContentsMode FillContents) {
794 CachedBlock Entry;
795 uptr EntryHeaderPos;
796 uptr MaxAllowedFragmentedPages = MaxUnreleasedCachePages;
797
798 if (LIKELY(!useMemoryTagging<Config>(Options))) {
799 MaxAllowedFragmentedPages += CachedBlock::MaxReleasedCachePages;
800 } else {
801 // TODO: Enable MaxReleasedCachePages may result in pages for an entry being
802 // partially released and it erases the tag of those pages as well. To
803 // support this feature for MTE, we need to tag those pages again.
804 DCHECK_EQ(MaxAllowedFragmentedPages, MaxUnreleasedCachePages);
805 }
806
807 Entry = Cache.retrieve(MaxAllowedFragmentedPages, Size, Alignment,
808 getHeadersSize(), EntryHeaderPos);
809 if (!Entry.isValid())
810 return nullptr;
811
812 LargeBlock::Header *H = reinterpret_cast<LargeBlock::Header *>(
813 LargeBlock::addHeaderTag<Config>(EntryHeaderPos));
814 bool Zeroed = Entry.Time == 0;
815
816 if (UNLIKELY(Entry.Flags & CachedBlock::NoAccess)) {
817 // NOTE: Flags set to 0 actually restores read-write.
818 Entry.MemMap.setMemoryPermission(Addr: Entry.CommitBase, Size: Entry.CommitSize,
819 /*Flags=*/Flags: 0);
820 }
821
822 if (useMemoryTagging<Config>(Options)) {
823 const uptr PageSize = getPageSizeCached();
824 const uptr OldAllocPos =
825 untagPointer(Ptr: Entry.BlockBegin) + Chunk::getHeaderSize();
826 const uptr NewAllocPos = untagPointer(Ptr: roundUp(X: EntryHeaderPos, Boundary: Alignment));
827 DCHECK_GE(Alignment, PageSize);
828
829 const uptr OldHeaderPage = OldAllocPos - PageSize;
830 const uptr NewHeaderPage = NewAllocPos - PageSize;
831
832 // Enabling or disabling memory tagging at runtime is unsupported.
833 // If MTE is enabled now, the cached entry was also allocated with MTE
834 // enabled, guaranteeing that both OldAllocPos and NewAllocPos are
835 // page-aligned.
836 CHECK(OldAllocPos % PageSize == 0U);
837 DCHECK(NewAllocPos % PageSize == 0U);
838
839 if (NewAllocPos != OldAllocPos) {
840 // The shift distance must be a multiple of PageSize
841 DCHECK_EQ((NewAllocPos > OldAllocPos ? NewAllocPos - OldAllocPos
842 : OldAllocPos - NewAllocPos) %
843 PageSize,
844 0U);
845
846 const uptr MappingFlags = MAP_RESIZABLE | MAP_ALLOWNOMEM;
847
848 if (!Entry.MemMap.remap(Addr: NewHeaderPage, Size: PageSize, Name: "scudo:secondary",
849 MAP_MEMTAG | MappingFlags)) {
850 unmap(MemMap&: Entry.MemMap);
851 return nullptr;
852 }
853 // Since PROT_MTE is sticky, setting memory permissions to MAP_NOACCESS
854 // (PROT_NONE) when caching the block does not clear the PROT_MTE flag
855 // from the kernel VMA. When we make the block RW again, the old header
856 // page still has MTE enabled. If the allocation shifted, we must
857 // explicitly remap the old header page without MAP_MEMTAG to disable MTE,
858 // as this page may now be part of the user payload or padding.
859 if (!Entry.MemMap.remap(Addr: OldHeaderPage, Size: PageSize, Name: "scudo:secondary",
860 Flags: MappingFlags)) {
861 unmap(MemMap&: Entry.MemMap);
862 return nullptr;
863 }
864 }
865
866 uptr NewBlockBegin = reinterpret_cast<uptr>(H + 1);
867 storeTags(Begin: reinterpret_cast<uptr>(H), End: NewBlockBegin);
868 }
869
870 H->CommitBase = Entry.CommitBase;
871 H->CommitSize = Entry.CommitSize;
872 H->MemMap = Entry.MemMap;
873
874 const uptr BlockEnd = H->CommitBase + H->CommitSize;
875 if (BlockEndPtr)
876 *BlockEndPtr = BlockEnd;
877 uptr HInt = reinterpret_cast<uptr>(H);
878 if (allocatorSupportsMemoryTagging<Config>())
879 HInt = untagPointer(Ptr: HInt);
880 const uptr PtrInt = HInt + LargeBlock::getHeaderSize();
881 void *Ptr = reinterpret_cast<void *>(PtrInt);
882 if (FillContents && !Zeroed)
883 memset(s: Ptr, c: FillContents == ZeroFill ? 0 : PatternFillByte,
884 n: BlockEnd - PtrInt);
885 {
886 ScopedLock L(Mutex);
887 InUseBlocks.push_back(X: H);
888 AllocatedBytes += H->CommitSize;
889 FragmentedBytes += H->MemMap.getCapacity() - H->CommitSize;
890 NumberOfAllocs++;
891 Stats.add(I: StatAllocated, V: H->CommitSize);
892 Stats.add(I: StatMapped, V: H->MemMap.getCapacity());
893 }
894 return Ptr;
895}
896// As with the Primary, the size passed to this function includes any desired
897// alignment, so that the frontend can align the user allocation. The hint
898// parameter allows us to unmap spurious memory when dealing with larger
899// (greater than a page) alignments on 32-bit platforms.
900// Due to the sparsity of address space available on those platforms, requesting
901// an allocation from the Secondary with a large alignment would end up wasting
902// VA space (even though we are not committing the whole thing), hence the need
903// to trim off some of the reserved space.
904// For allocations requested with an alignment greater than or equal to a page,
905// the committed memory will amount to something close to Size - AlignmentHint
906// (pending rounding and headers).
907template <typename Config>
908void *MapAllocator<Config>::allocate(const Options &Options, uptr Size,
909 uptr Alignment, uptr *BlockEndPtr,
910 FillContentsMode FillContents) {
911 if (Options.get(Opt: OptionBit::AddLargeAllocationSlack))
912 Size += 1UL << SCUDO_MIN_ALIGNMENT_LOG;
913 Alignment = Max(A: Alignment, B: uptr(1U) << SCUDO_MIN_ALIGNMENT_LOG);
914 const uptr PageSize = getPageSizeCached();
915
916 if (useMemoryTagging<Config>(Options))
917 Alignment = Max(A: Alignment, B: PageSize);
918
919 // Note that cached blocks may have aligned address already. Thus we simply
920 // pass the required size (`Size` + `getHeadersSize()`) to do cache look up.
921 const uptr MinNeededSizeForCache = roundUp(X: Size + getHeadersSize(), Boundary: PageSize);
922
923 if (Alignment <= PageSize && Cache.canCache(MinNeededSizeForCache)) {
924 void *Ptr = tryAllocateFromCache(Options, Size, Alignment, BlockEndPtr,
925 FillContents);
926 if (Ptr != nullptr)
927 return Ptr;
928 }
929
930 uptr RoundedSize =
931 roundUp(X: roundUp(X: Size, Boundary: Alignment) + getHeadersSize(), Boundary: PageSize);
932 if (UNLIKELY(Alignment > PageSize))
933 RoundedSize += Alignment - PageSize;
934
935 ReservedMemoryT ReservedMemory;
936 const uptr MapSize = RoundedSize + 2 * getGuardPageSize();
937 if (UNLIKELY(!ReservedMemory.create(/*Addr=*/0U, MapSize, nullptr,
938 MAP_ALLOWNOMEM))) {
939 return nullptr;
940 }
941
942 // Take the entire ownership of reserved region.
943 MemMapT MemMap = ReservedMemory.dispatch(Addr: ReservedMemory.getBase(),
944 Size: ReservedMemory.getCapacity());
945 uptr MapBase = MemMap.getBase();
946 uptr CommitBase = MapBase + getGuardPageSize();
947 uptr MapEnd = MapBase + MapSize;
948
949 // In the unlikely event of alignments larger than a page, adjust the amount
950 // of memory we want to commit, and trim the extra memory.
951 if (UNLIKELY(Alignment >= PageSize)) {
952 // For alignments greater than or equal to a page, the user pointer (eg:
953 // the pointer that is returned by the C or C++ allocation APIs) ends up
954 // on a page boundary , and our headers will live in the preceding page.
955 CommitBase =
956 roundUp(X: MapBase + getGuardPageSize() + 1, Boundary: Alignment) - PageSize;
957 // We only trim the extra memory on 32-bit platforms: 64-bit platforms
958 // are less constrained memory wise, and that saves us two syscalls.
959 if (SCUDO_WORDSIZE == 32U) {
960 const uptr NewMapBase = CommitBase - getGuardPageSize();
961 DCHECK_GE(NewMapBase, MapBase);
962 if (NewMapBase != MapBase) {
963 MemMap.unmap(Addr: MapBase, Size: NewMapBase - MapBase);
964 MapBase = NewMapBase;
965 }
966 // CommitBase is past the first guard page, but this computation needs
967 // to include a page where the header lives.
968 const uptr NewMapEnd =
969 CommitBase + PageSize + roundUp(X: Size, Boundary: PageSize) + getGuardPageSize();
970 DCHECK_LE(NewMapEnd, MapEnd);
971 if (NewMapEnd != MapEnd) {
972 MemMap.unmap(Addr: NewMapEnd, Size: MapEnd - NewMapEnd);
973 MapEnd = NewMapEnd;
974 }
975 }
976 }
977
978 const uptr CommitSize = MapEnd - getGuardPageSize() - CommitBase;
979 const uptr AllocPos = roundDown(X: CommitBase + CommitSize - Size, Boundary: Alignment);
980 if (!mapSecondary<Config>(Options, CommitBase, CommitSize, AllocPos, 0,
981 MemMap)) {
982 MemMap.unmap();
983 return nullptr;
984 }
985 const uptr HeaderPos = AllocPos - getHeadersSize();
986 // Make sure that the header is not in the guard page or before the base.
987 DCHECK_GE(HeaderPos, MapBase + getGuardPageSize());
988 LargeBlock::Header *H = reinterpret_cast<LargeBlock::Header *>(
989 LargeBlock::addHeaderTag<Config>(HeaderPos));
990 if (useMemoryTagging<Config>(Options))
991 storeTags(Begin: reinterpret_cast<uptr>(H), End: reinterpret_cast<uptr>(H + 1));
992 H->CommitBase = CommitBase;
993 H->CommitSize = CommitSize;
994 H->MemMap = MemMap;
995 if (BlockEndPtr)
996 *BlockEndPtr = CommitBase + CommitSize;
997 {
998 ScopedLock L(Mutex);
999 InUseBlocks.push_back(X: H);
1000 AllocatedBytes += CommitSize;
1001 FragmentedBytes += H->MemMap.getCapacity() - CommitSize;
1002 if (LargestSize < CommitSize)
1003 LargestSize = CommitSize;
1004 NumberOfAllocs++;
1005 Stats.add(I: StatAllocated, V: CommitSize);
1006 Stats.add(I: StatMapped, V: H->MemMap.getCapacity());
1007 }
1008 return reinterpret_cast<void *>(HeaderPos + LargeBlock::getHeaderSize());
1009}
1010
1011template <typename Config>
1012void MapAllocator<Config>::deallocate(const Options &Options, void *Ptr)
1013 EXCLUDES(Mutex) {
1014 LargeBlock::Header *H = LargeBlock::getHeader<Config>(Ptr);
1015 const uptr CommitSize = H->CommitSize;
1016 {
1017 ScopedLock L(Mutex);
1018 InUseBlocks.remove(X: H);
1019 FreedBytes += CommitSize;
1020 FragmentedBytes -= H->MemMap.getCapacity() - CommitSize;
1021 NumberOfFrees++;
1022 Stats.sub(I: StatAllocated, V: CommitSize);
1023 Stats.sub(I: StatMapped, V: H->MemMap.getCapacity());
1024 }
1025
1026 if (Cache.canCache(H->CommitSize)) {
1027 Cache.store(Options, H->CommitBase, H->CommitSize,
1028 reinterpret_cast<uptr>(H + 1), H->MemMap);
1029 } else {
1030 // Note that the `H->MemMap` is stored on the pages managed by itself. Take
1031 // over the ownership before unmap() so that any operation along with
1032 // unmap() won't touch inaccessible pages.
1033 MemMapT MemMap = H->MemMap;
1034 unmap(MemMap);
1035 ScopedLock L(Mutex);
1036 UncacheableUnmaps++;
1037 }
1038}
1039
1040template <typename Config>
1041void MapAllocator<Config>::getStats(ScopedString *Str) EXCLUDES(Mutex) {
1042 ScopedLock L(Mutex);
1043 Str->append(
1044 Format: "Stats: MapAllocator: allocated %u times (%zuK), freed %u times (%zuK), "
1045 "remains %u (%zuK) max %zuM, Fragmented %zuK, Uncacheable unmaps: %u\n",
1046 NumberOfAllocs, AllocatedBytes >> 10, NumberOfFrees, FreedBytes >> 10,
1047 NumberOfAllocs - NumberOfFrees, (AllocatedBytes - FreedBytes) >> 10,
1048 LargestSize >> 20, FragmentedBytes >> 10, UncacheableUnmaps);
1049 Cache.getStats(Str);
1050}
1051
1052} // namespace scudo
1053
1054#endif // SCUDO_SECONDARY_H_
1055