1 //===-- primary_test.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 "tests/scudo_unit_test.h"
10 
11 #include "primary32.h"
12 #include "primary64.h"
13 #include "size_class_map.h"
14 
15 #include <condition_variable>
16 #include <mutex>
17 #include <thread>
18 #include <vector>
19 
20 // Note that with small enough regions, the SizeClassAllocator64 also works on
21 // 32-bit architectures. It's not something we want to encourage, but we still
22 // should ensure the tests pass.
23 
24 template <typename Primary> static void testPrimary() {
25   const scudo::uptr NumberOfAllocations = 32U;
26   auto Deleter = [](Primary *P) {
27     P->unmapTestOnly();
28     delete P;
29   };
30   std::unique_ptr<Primary, decltype(Deleter)> Allocator(new Primary, Deleter);
31   Allocator->init(/*ReleaseToOsInterval=*/-1);
32   typename Primary::CacheT Cache;
33   Cache.init(nullptr, Allocator.get());
34   for (scudo::uptr I = 0; I <= 16U; I++) {
35     const scudo::uptr Size = 1UL << I;
36     if (!Primary::canAllocate(Size))
37       continue;
38     const scudo::uptr ClassId = Primary::SizeClassMap::getClassIdBySize(Size);
39     void *Pointers[NumberOfAllocations];
40     for (scudo::uptr J = 0; J < NumberOfAllocations; J++) {
41       void *P = Cache.allocate(ClassId);
42       memset(P, 'B', Size);
43       Pointers[J] = P;
44     }
45     for (scudo::uptr J = 0; J < NumberOfAllocations; J++)
46       Cache.deallocate(ClassId, Pointers[J]);
47   }
48   Cache.destroy(nullptr);
49   Allocator->releaseToOS();
50   scudo::ScopedString Str(1024);
51   Allocator->getStats(&Str);
52   Str.output();
53 }
54 
55 template <typename SizeClassMapT> struct TestConfig1 {
56   using SizeClassMap = SizeClassMapT;
57   static const scudo::uptr PrimaryRegionSizeLog = 18U;
58   static const scudo::s32 PrimaryMinReleaseToOsIntervalMs = INT32_MIN;
59   static const scudo::s32 PrimaryMaxReleaseToOsIntervalMs = INT32_MAX;
60   static const bool MaySupportMemoryTagging = false;
61 };
62 
63 template <typename SizeClassMapT> struct TestConfig2 {
64   using SizeClassMap = SizeClassMapT;
65   static const scudo::uptr PrimaryRegionSizeLog = 24U;
66   static const scudo::s32 PrimaryMinReleaseToOsIntervalMs = INT32_MIN;
67   static const scudo::s32 PrimaryMaxReleaseToOsIntervalMs = INT32_MAX;
68   static const bool MaySupportMemoryTagging = false;
69 };
70 
71 template <typename SizeClassMapT> struct TestConfig3 {
72   using SizeClassMap = SizeClassMapT;
73   static const scudo::uptr PrimaryRegionSizeLog = 24U;
74   static const scudo::s32 PrimaryMinReleaseToOsIntervalMs = INT32_MIN;
75   static const scudo::s32 PrimaryMaxReleaseToOsIntervalMs = INT32_MAX;
76   static const bool MaySupportMemoryTagging = true;
77 };
78 
79 TEST(ScudoPrimaryTest, BasicPrimary) {
80   using SizeClassMap = scudo::DefaultSizeClassMap;
81 #if !SCUDO_FUCHSIA
82   testPrimary<scudo::SizeClassAllocator32<TestConfig1<SizeClassMap>>>();
83 #endif
84   testPrimary<scudo::SizeClassAllocator64<TestConfig2<SizeClassMap>>>();
85   testPrimary<scudo::SizeClassAllocator64<TestConfig3<SizeClassMap>>>();
86 }
87 
88 struct SmallRegionsConfig {
89   using SizeClassMap = scudo::DefaultSizeClassMap;
90   static const scudo::uptr PrimaryRegionSizeLog = 20U;
91   static const scudo::s32 PrimaryMinReleaseToOsIntervalMs = INT32_MIN;
92   static const scudo::s32 PrimaryMaxReleaseToOsIntervalMs = INT32_MAX;
93   static const bool MaySupportMemoryTagging = false;
94 };
95 
96 // The 64-bit SizeClassAllocator can be easily OOM'd with small region sizes.
97 // For the 32-bit one, it requires actually exhausting memory, so we skip it.
98 TEST(ScudoPrimaryTest, Primary64OOM) {
99   using Primary = scudo::SizeClassAllocator64<SmallRegionsConfig>;
100   using TransferBatch = Primary::CacheT::TransferBatch;
101   Primary Allocator;
102   Allocator.init(/*ReleaseToOsInterval=*/-1);
103   typename Primary::CacheT Cache;
104   scudo::GlobalStats Stats;
105   Stats.init();
106   Cache.init(&Stats, &Allocator);
107   bool AllocationFailed = false;
108   std::vector<TransferBatch *> Batches;
109   const scudo::uptr ClassId = Primary::SizeClassMap::LargestClassId;
110   const scudo::uptr Size = Primary::getSizeByClassId(ClassId);
111   for (scudo::uptr I = 0; I < 10000U; I++) {
112     TransferBatch *B = Allocator.popBatch(&Cache, ClassId);
113     if (!B) {
114       AllocationFailed = true;
115       break;
116     }
117     for (scudo::u32 J = 0; J < B->getCount(); J++)
118       memset(B->get(J), 'B', Size);
119     Batches.push_back(B);
120   }
121   while (!Batches.empty()) {
122     Allocator.pushBatch(ClassId, Batches.back());
123     Batches.pop_back();
124   }
125   Cache.destroy(nullptr);
126   Allocator.releaseToOS();
127   scudo::ScopedString Str(1024);
128   Allocator.getStats(&Str);
129   Str.output();
130   EXPECT_EQ(AllocationFailed, true);
131   Allocator.unmapTestOnly();
132 }
133 
134 template <typename Primary> static void testIteratePrimary() {
135   auto Deleter = [](Primary *P) {
136     P->unmapTestOnly();
137     delete P;
138   };
139   std::unique_ptr<Primary, decltype(Deleter)> Allocator(new Primary, Deleter);
140   Allocator->init(/*ReleaseToOsInterval=*/-1);
141   typename Primary::CacheT Cache;
142   Cache.init(nullptr, Allocator.get());
143   std::vector<std::pair<scudo::uptr, void *>> V;
144   for (scudo::uptr I = 0; I < 64U; I++) {
145     const scudo::uptr Size = std::rand() % Primary::SizeClassMap::MaxSize;
146     const scudo::uptr ClassId = Primary::SizeClassMap::getClassIdBySize(Size);
147     void *P = Cache.allocate(ClassId);
148     V.push_back(std::make_pair(ClassId, P));
149   }
150   scudo::uptr Found = 0;
151   auto Lambda = [V, &Found](scudo::uptr Block) {
152     for (const auto &Pair : V) {
153       if (Pair.second == reinterpret_cast<void *>(Block))
154         Found++;
155     }
156   };
157   Allocator->disable();
158   Allocator->iterateOverBlocks(Lambda);
159   Allocator->enable();
160   EXPECT_EQ(Found, V.size());
161   while (!V.empty()) {
162     auto Pair = V.back();
163     Cache.deallocate(Pair.first, Pair.second);
164     V.pop_back();
165   }
166   Cache.destroy(nullptr);
167   Allocator->releaseToOS();
168   scudo::ScopedString Str(1024);
169   Allocator->getStats(&Str);
170   Str.output();
171 }
172 
173 TEST(ScudoPrimaryTest, PrimaryIterate) {
174   using SizeClassMap = scudo::DefaultSizeClassMap;
175 #if !SCUDO_FUCHSIA
176   testIteratePrimary<scudo::SizeClassAllocator32<TestConfig1<SizeClassMap>>>();
177 #endif
178   testIteratePrimary<scudo::SizeClassAllocator64<TestConfig2<SizeClassMap>>>();
179   testIteratePrimary<scudo::SizeClassAllocator64<TestConfig3<SizeClassMap>>>();
180 }
181 
182 static std::mutex Mutex;
183 static std::condition_variable Cv;
184 static bool Ready;
185 
186 template <typename Primary> static void performAllocations(Primary *Allocator) {
187   static thread_local typename Primary::CacheT Cache;
188   Cache.init(nullptr, Allocator);
189   std::vector<std::pair<scudo::uptr, void *>> V;
190   {
191     std::unique_lock<std::mutex> Lock(Mutex);
192     while (!Ready)
193       Cv.wait(Lock);
194   }
195   for (scudo::uptr I = 0; I < 256U; I++) {
196     const scudo::uptr Size = std::rand() % Primary::SizeClassMap::MaxSize / 4;
197     const scudo::uptr ClassId = Primary::SizeClassMap::getClassIdBySize(Size);
198     void *P = Cache.allocate(ClassId);
199     if (P)
200       V.push_back(std::make_pair(ClassId, P));
201   }
202   while (!V.empty()) {
203     auto Pair = V.back();
204     Cache.deallocate(Pair.first, Pair.second);
205     V.pop_back();
206   }
207   Cache.destroy(nullptr);
208 }
209 
210 template <typename Primary> static void testPrimaryThreaded() {
211   Ready = false;
212   auto Deleter = [](Primary *P) {
213     P->unmapTestOnly();
214     delete P;
215   };
216   std::unique_ptr<Primary, decltype(Deleter)> Allocator(new Primary, Deleter);
217   Allocator->init(/*ReleaseToOsInterval=*/-1);
218   std::thread Threads[32];
219   for (scudo::uptr I = 0; I < ARRAY_SIZE(Threads); I++)
220     Threads[I] = std::thread(performAllocations<Primary>, Allocator.get());
221   {
222     std::unique_lock<std::mutex> Lock(Mutex);
223     Ready = true;
224     Cv.notify_all();
225   }
226   for (auto &T : Threads)
227     T.join();
228   Allocator->releaseToOS();
229   scudo::ScopedString Str(1024);
230   Allocator->getStats(&Str);
231   Str.output();
232 }
233 
234 TEST(ScudoPrimaryTest, PrimaryThreaded) {
235   using SizeClassMap = scudo::SvelteSizeClassMap;
236 #if !SCUDO_FUCHSIA
237   testPrimaryThreaded<scudo::SizeClassAllocator32<TestConfig1<SizeClassMap>>>();
238 #endif
239   testPrimaryThreaded<scudo::SizeClassAllocator64<TestConfig2<SizeClassMap>>>();
240   testPrimaryThreaded<scudo::SizeClassAllocator64<TestConfig3<SizeClassMap>>>();
241 }
242 
243 // Through a simple allocation that spans two pages, verify that releaseToOS
244 // actually releases some bytes (at least one page worth). This is a regression
245 // test for an error in how the release criteria were computed.
246 template <typename Primary> static void testReleaseToOS() {
247   auto Deleter = [](Primary *P) {
248     P->unmapTestOnly();
249     delete P;
250   };
251   std::unique_ptr<Primary, decltype(Deleter)> Allocator(new Primary, Deleter);
252   Allocator->init(/*ReleaseToOsInterval=*/-1);
253   typename Primary::CacheT Cache;
254   Cache.init(nullptr, Allocator.get());
255   const scudo::uptr Size = scudo::getPageSizeCached() * 2;
256   EXPECT_TRUE(Primary::canAllocate(Size));
257   const scudo::uptr ClassId = Primary::SizeClassMap::getClassIdBySize(Size);
258   void *P = Cache.allocate(ClassId);
259   EXPECT_NE(P, nullptr);
260   Cache.deallocate(ClassId, P);
261   Cache.destroy(nullptr);
262   EXPECT_GT(Allocator->releaseToOS(), 0U);
263 }
264 
265 TEST(ScudoPrimaryTest, ReleaseToOS) {
266   using SizeClassMap = scudo::DefaultSizeClassMap;
267 #if !SCUDO_FUCHSIA
268   testReleaseToOS<scudo::SizeClassAllocator32<TestConfig1<SizeClassMap>>>();
269 #endif
270   testReleaseToOS<scudo::SizeClassAllocator64<TestConfig2<SizeClassMap>>>();
271   testReleaseToOS<scudo::SizeClassAllocator64<TestConfig3<SizeClassMap>>>();
272 }
273