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   Allocator->printStats();
140 }
141 
142 TEST(ScudoCombinedTest, BasicCombined) {
143   testAllocator<scudo::DefaultConfig>();
144 #if SCUDO_WORDSIZE == 64U
145   testAllocator<scudo::FuchsiaConfig>();
146 #endif
147   // The following configs should work on all platforms.
148   UseQuarantine = true;
149   testAllocator<scudo::AndroidConfig>();
150   UseQuarantine = false;
151   testAllocator<scudo::AndroidSvelteConfig>();
152 }
153 
154 template <typename AllocatorT> static void stressAllocator(AllocatorT *A) {
155   {
156     std::unique_lock<std::mutex> Lock(Mutex);
157     while (!Ready)
158       Cv.wait(Lock);
159   }
160   std::vector<std::pair<void *, scudo::uptr>> V;
161   for (scudo::uptr I = 0; I < 256U; I++) {
162     const scudo::uptr Size = std::rand() % 4096U;
163     void *P = A->allocate(Size, Origin);
164     // A region could have ran out of memory, resulting in a null P.
165     if (P)
166       V.push_back(std::make_pair(P, Size));
167   }
168   while (!V.empty()) {
169     auto Pair = V.back();
170     A->deallocate(Pair.first, Origin, Pair.second);
171     V.pop_back();
172   }
173 }
174 
175 template <class Config> static void testAllocatorThreaded() {
176   using AllocatorT = scudo::Allocator<Config>;
177   auto Deleter = [](AllocatorT *A) {
178     A->unmapTestOnly();
179     delete A;
180   };
181   std::unique_ptr<AllocatorT, decltype(Deleter)> Allocator(new AllocatorT,
182                                                            Deleter);
183   Allocator->reset();
184   std::thread Threads[32];
185   for (scudo::uptr I = 0; I < ARRAY_SIZE(Threads); I++)
186     Threads[I] = std::thread(stressAllocator<AllocatorT>, Allocator.get());
187   {
188     std::unique_lock<std::mutex> Lock(Mutex);
189     Ready = true;
190     Cv.notify_all();
191   }
192   for (auto &T : Threads)
193     T.join();
194   Allocator->releaseToOS();
195 }
196 
197 TEST(ScudoCombinedTest, ThreadedCombined) {
198   testAllocatorThreaded<scudo::DefaultConfig>();
199 #if SCUDO_WORDSIZE == 64U
200   testAllocatorThreaded<scudo::FuchsiaConfig>();
201 #endif
202   UseQuarantine = true;
203   testAllocatorThreaded<scudo::AndroidConfig>();
204   UseQuarantine = false;
205   testAllocatorThreaded<scudo::AndroidSvelteConfig>();
206 }
207 
208 struct DeathConfig {
209   // Tiny allocator, its Primary only serves chunks of 1024 bytes.
210   using DeathSizeClassMap = scudo::SizeClassMap<1U, 10U, 10U, 10U, 1U, 10U>;
211   typedef scudo::SizeClassAllocator32<DeathSizeClassMap, 18U> Primary;
212   template <class A> using TSDRegistryT = scudo::TSDRegistrySharedT<A, 1U>;
213 };
214 
215 TEST(ScudoCombinedTest, DeathCombined) {
216   using AllocatorT = scudo::Allocator<DeathConfig>;
217   auto Deleter = [](AllocatorT *A) {
218     A->unmapTestOnly();
219     delete A;
220   };
221   std::unique_ptr<AllocatorT, decltype(Deleter)> Allocator(new AllocatorT,
222                                                            Deleter);
223   Allocator->reset();
224 
225   const scudo::uptr Size = 1000U;
226   void *P = Allocator->allocate(Size, Origin);
227   EXPECT_NE(P, nullptr);
228 
229   // Invalid sized deallocation.
230   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size + 8U), "");
231 
232   // Misaligned pointer.
233   void *MisalignedP =
234       reinterpret_cast<void *>(reinterpret_cast<scudo::uptr>(P) | 1U);
235   EXPECT_DEATH(Allocator->deallocate(MisalignedP, Origin, Size), "");
236   EXPECT_DEATH(Allocator->reallocate(MisalignedP, Size * 2U), "");
237 
238   // Header corruption.
239   scudo::u64 *H =
240       reinterpret_cast<scudo::u64 *>(scudo::Chunk::getAtomicHeader(P));
241   *H ^= 0x42U;
242   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
243   *H ^= 0x420042U;
244   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
245   *H ^= 0x420000U;
246 
247   // Invalid chunk state.
248   Allocator->deallocate(P, Origin, Size);
249   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
250   EXPECT_DEATH(Allocator->reallocate(P, Size * 2U), "");
251   EXPECT_DEATH(Allocator->getUsableSize(P), "");
252 }
253