1 //===-- combined_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 "allocator_config.h"
10 #include "combined.h"
11 
12 #include "gtest/gtest.h"
13 
14 #include <condition_variable>
15 #include <mutex>
16 #include <thread>
17 
18 static std::mutex Mutex;
19 static std::condition_variable Cv;
20 static bool Ready = false;
21 
22 static constexpr scudo::Chunk::Origin Origin = scudo::Chunk::Origin::Malloc;
23 
24 // This allows us to turn on the Quarantine for specific tests. The Quarantine
25 // parameters are on the low end, to avoid having to loop excessively in some
26 // tests.
27 static bool UseQuarantine = false;
28 extern "C" const char *__scudo_default_options() {
29   if (!UseQuarantine)
30     return "";
31   return "quarantine_size_kb=256:thread_local_quarantine_size_kb=128:"
32          "quarantine_max_chunk_size=1024";
33 }
34 
35 template <class Config> static void testAllocator() {
36   using AllocatorT = scudo::Allocator<Config>;
37   auto Deleter = [](AllocatorT *A) {
38     A->unmapTestOnly();
39     delete A;
40   };
41   std::unique_ptr<AllocatorT, decltype(Deleter)> Allocator(new AllocatorT,
42                                                            Deleter);
43   Allocator->reset();
44 
45   constexpr scudo::uptr MinAlignLog = FIRST_32_SECOND_64(3U, 4U);
46 
47   // This allocates and deallocates a bunch of chunks, with a wide range of
48   // sizes and alignments, with a focus on sizes that could trigger weird
49   // behaviors (plus or minus a small delta of a power of two for example).
50   for (scudo::uptr SizeLog = 0U; SizeLog <= 20U; SizeLog++) {
51     for (scudo::uptr AlignLog = MinAlignLog; AlignLog <= 16U; AlignLog++) {
52       const scudo::uptr Align = 1U << AlignLog;
53       for (scudo::sptr Delta = -32; Delta <= 32; Delta++) {
54         if (static_cast<scudo::sptr>(1U << SizeLog) + Delta <= 0)
55           continue;
56         const scudo::uptr Size = (1U << SizeLog) + Delta;
57         void *P = Allocator->allocate(Size, Origin, Align);
58         EXPECT_NE(P, nullptr);
59         EXPECT_TRUE(scudo::isAligned(reinterpret_cast<scudo::uptr>(P), Align));
60         EXPECT_LE(Size, Allocator->getUsableSize(P));
61         memset(P, 0xaa, Size);
62         Allocator->deallocate(P, Origin, Size);
63       }
64     }
65   }
66   Allocator->releaseToOS();
67 
68   // Verify that a chunk will end up being reused, at some point.
69   const scudo::uptr NeedleSize = 1024U;
70   void *NeedleP = Allocator->allocate(NeedleSize, Origin);
71   Allocator->deallocate(NeedleP, Origin);
72   bool Found = false;
73   for (scudo::uptr I = 0; I < 1024U && !Found; I++) {
74     void *P = Allocator->allocate(NeedleSize, Origin);
75     if (P == NeedleP)
76       Found = true;
77     Allocator->deallocate(P, Origin);
78   }
79   EXPECT_TRUE(Found);
80 
81   constexpr scudo::uptr MaxSize = Config::Primary::SizeClassMap::MaxSize;
82 
83   // Reallocate a large chunk all the way down to a byte, verifying that we
84   // preserve the data in the process.
85   scudo::uptr Size = MaxSize * 2;
86   const scudo::uptr DataSize = 2048U;
87   void *P = Allocator->allocate(Size, Origin);
88   const char Marker = 0xab;
89   memset(P, Marker, scudo::Min(Size, DataSize));
90   while (Size > 1U) {
91     Size /= 2U;
92     void *NewP = Allocator->reallocate(P, Size);
93     EXPECT_NE(NewP, nullptr);
94     for (scudo::uptr J = 0; J < scudo::Min(Size, DataSize); J++)
95       EXPECT_EQ((reinterpret_cast<char *>(NewP))[J], Marker);
96     P = NewP;
97   }
98   Allocator->deallocate(P, Origin);
99 
100   // Check that reallocating a chunk to a slightly smaller or larger size
101   // returns the same chunk. This requires that all the sizes we iterate on use
102   // the same block size, but that should be the case for 2048 with our default
103   // class size maps.
104   P = Allocator->allocate(DataSize, Origin);
105   memset(P, Marker, DataSize);
106   for (scudo::sptr Delta = -32; Delta < 32; Delta += 8) {
107     const scudo::uptr NewSize = DataSize + Delta;
108     void *NewP = Allocator->reallocate(P, NewSize);
109     EXPECT_EQ(NewP, P);
110     for (scudo::uptr I = 0; I < scudo::Min(DataSize, NewSize); I++)
111       EXPECT_EQ((reinterpret_cast<char *>(NewP))[I], Marker);
112   }
113   Allocator->deallocate(P, Origin);
114 
115   // Allocates a bunch of chunks, then iterate over all the chunks, ensuring
116   // they are the ones we allocated. This requires the allocator to not have any
117   // other allocated chunk at this point (eg: won't work with the Quarantine).
118   if (!UseQuarantine) {
119     std::vector<void *> V;
120     for (scudo::uptr I = 0; I < 64U; I++)
121       V.push_back(Allocator->allocate(rand() % (MaxSize / 2U), Origin));
122     Allocator->disable();
123     Allocator->iterateOverChunks(
124         0U, static_cast<scudo::uptr>(SCUDO_MMAP_RANGE_SIZE - 1),
125         [](uintptr_t Base, size_t Size, void *Arg) {
126           std::vector<void *> *V = reinterpret_cast<std::vector<void *> *>(Arg);
127           void *P = reinterpret_cast<void *>(Base);
128           EXPECT_NE(std::find(V->begin(), V->end(), P), V->end());
129         },
130         reinterpret_cast<void *>(&V));
131     Allocator->enable();
132     while (!V.empty()) {
133       Allocator->deallocate(V.back(), Origin);
134       V.pop_back();
135     }
136   }
137 
138   Allocator->releaseToOS();
139 
140   scudo::uptr BufferSize = 8192;
141   std::vector<char> Buffer(BufferSize);
142   scudo::uptr ActualSize = Allocator->getStats(Buffer.data(), BufferSize);
143   while (ActualSize > BufferSize) {
144     BufferSize = ActualSize + 1024;
145     Buffer.resize(BufferSize);
146     ActualSize = Allocator->getStats(Buffer.data(), BufferSize);
147   }
148   std::string Stats(Buffer.begin(), Buffer.end());
149   // Basic checks on the contents of the statistics output, which also allows us
150   // to verify that we got it all.
151   EXPECT_NE(Stats.find("Stats: SizeClassAllocator"), std::string::npos);
152   EXPECT_NE(Stats.find("Stats: MapAllocator"), std::string::npos);
153   EXPECT_NE(Stats.find("Stats: Quarantine"), std::string::npos);
154 }
155 
156 TEST(ScudoCombinedTest, BasicCombined) {
157   testAllocator<scudo::DefaultConfig>();
158 #if SCUDO_WORDSIZE == 64U
159   testAllocator<scudo::FuchsiaConfig>();
160 #endif
161   // The following configs should work on all platforms.
162   UseQuarantine = true;
163   testAllocator<scudo::AndroidConfig>();
164   UseQuarantine = false;
165   testAllocator<scudo::AndroidSvelteConfig>();
166 }
167 
168 template <typename AllocatorT> static void stressAllocator(AllocatorT *A) {
169   {
170     std::unique_lock<std::mutex> Lock(Mutex);
171     while (!Ready)
172       Cv.wait(Lock);
173   }
174   std::vector<std::pair<void *, scudo::uptr>> V;
175   for (scudo::uptr I = 0; I < 256U; I++) {
176     const scudo::uptr Size = std::rand() % 4096U;
177     void *P = A->allocate(Size, Origin);
178     // A region could have ran out of memory, resulting in a null P.
179     if (P)
180       V.push_back(std::make_pair(P, Size));
181   }
182   while (!V.empty()) {
183     auto Pair = V.back();
184     A->deallocate(Pair.first, Origin, Pair.second);
185     V.pop_back();
186   }
187 }
188 
189 template <class Config> static void testAllocatorThreaded() {
190   using AllocatorT = scudo::Allocator<Config>;
191   auto Deleter = [](AllocatorT *A) {
192     A->unmapTestOnly();
193     delete A;
194   };
195   std::unique_ptr<AllocatorT, decltype(Deleter)> Allocator(new AllocatorT,
196                                                            Deleter);
197   Allocator->reset();
198   std::thread Threads[32];
199   for (scudo::uptr I = 0; I < ARRAY_SIZE(Threads); I++)
200     Threads[I] = std::thread(stressAllocator<AllocatorT>, Allocator.get());
201   {
202     std::unique_lock<std::mutex> Lock(Mutex);
203     Ready = true;
204     Cv.notify_all();
205   }
206   for (auto &T : Threads)
207     T.join();
208   Allocator->releaseToOS();
209 }
210 
211 TEST(ScudoCombinedTest, ThreadedCombined) {
212   testAllocatorThreaded<scudo::DefaultConfig>();
213 #if SCUDO_WORDSIZE == 64U
214   testAllocatorThreaded<scudo::FuchsiaConfig>();
215 #endif
216   UseQuarantine = true;
217   testAllocatorThreaded<scudo::AndroidConfig>();
218   UseQuarantine = false;
219   testAllocatorThreaded<scudo::AndroidSvelteConfig>();
220 }
221 
222 struct DeathConfig {
223   // Tiny allocator, its Primary only serves chunks of 1024 bytes.
224   using DeathSizeClassMap = scudo::SizeClassMap<1U, 10U, 10U, 10U, 1U, 10U>;
225   typedef scudo::SizeClassAllocator32<DeathSizeClassMap, 18U> Primary;
226   typedef scudo::MapAllocator<0U> Secondary;
227   template <class A> using TSDRegistryT = scudo::TSDRegistrySharedT<A, 1U>;
228 };
229 
230 TEST(ScudoCombinedTest, DeathCombined) {
231   using AllocatorT = scudo::Allocator<DeathConfig>;
232   auto Deleter = [](AllocatorT *A) {
233     A->unmapTestOnly();
234     delete A;
235   };
236   std::unique_ptr<AllocatorT, decltype(Deleter)> Allocator(new AllocatorT,
237                                                            Deleter);
238   Allocator->reset();
239 
240   const scudo::uptr Size = 1000U;
241   void *P = Allocator->allocate(Size, Origin);
242   EXPECT_NE(P, nullptr);
243 
244   // Invalid sized deallocation.
245   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size + 8U), "");
246 
247   // Misaligned pointer.
248   void *MisalignedP =
249       reinterpret_cast<void *>(reinterpret_cast<scudo::uptr>(P) | 1U);
250   EXPECT_DEATH(Allocator->deallocate(MisalignedP, Origin, Size), "");
251   EXPECT_DEATH(Allocator->reallocate(MisalignedP, Size * 2U), "");
252 
253   // Header corruption.
254   scudo::u64 *H =
255       reinterpret_cast<scudo::u64 *>(scudo::Chunk::getAtomicHeader(P));
256   *H ^= 0x42U;
257   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
258   *H ^= 0x420042U;
259   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
260   *H ^= 0x420000U;
261 
262   // Invalid chunk state.
263   Allocator->deallocate(P, Origin, Size);
264   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
265   EXPECT_DEATH(Allocator->reallocate(P, Size * 2U), "");
266   EXPECT_DEATH(Allocator->getUsableSize(P), "");
267 }
268