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 "tests/scudo_unit_test.h"
10 
11 #include "allocator_config.h"
12 #include "combined.h"
13 
14 #include <condition_variable>
15 #include <memory>
16 #include <mutex>
17 #include <set>
18 #include <stdlib.h>
19 #include <thread>
20 #include <vector>
21 
22 static constexpr scudo::Chunk::Origin Origin = scudo::Chunk::Origin::Malloc;
23 static constexpr scudo::uptr MinAlignLog = FIRST_32_SECOND_64(3U, 4U);
24 
25 // Fuchsia complains that the function is not used.
26 UNUSED static void disableDebuggerdMaybe() {
27 #if SCUDO_ANDROID
28   // Disable the debuggerd signal handler on Android, without this we can end
29   // up spending a significant amount of time creating tombstones.
30   signal(SIGSEGV, SIG_DFL);
31 #endif
32 }
33 
34 template <class AllocatorT>
35 bool isPrimaryAllocation(scudo::uptr Size, scudo::uptr Alignment) {
36   const scudo::uptr MinAlignment = 1UL << SCUDO_MIN_ALIGNMENT_LOG;
37   if (Alignment < MinAlignment)
38     Alignment = MinAlignment;
39   const scudo::uptr NeededSize =
40       scudo::roundUpTo(Size, MinAlignment) +
41       ((Alignment > MinAlignment) ? Alignment : scudo::Chunk::getHeaderSize());
42   return AllocatorT::PrimaryT::canAllocate(NeededSize);
43 }
44 
45 template <class AllocatorT>
46 void checkMemoryTaggingMaybe(AllocatorT *Allocator, void *P, scudo::uptr Size,
47                              scudo::uptr Alignment) {
48   const scudo::uptr MinAlignment = 1UL << SCUDO_MIN_ALIGNMENT_LOG;
49   Size = scudo::roundUpTo(Size, MinAlignment);
50   if (Allocator->useMemoryTaggingTestOnly())
51     EXPECT_DEATH(
52         {
53           disableDebuggerdMaybe();
54           reinterpret_cast<char *>(P)[-1] = 0xaa;
55         },
56         "");
57   if (isPrimaryAllocation<AllocatorT>(Size, Alignment)
58           ? Allocator->useMemoryTaggingTestOnly()
59           : Alignment == MinAlignment) {
60     EXPECT_DEATH(
61         {
62           disableDebuggerdMaybe();
63           reinterpret_cast<char *>(P)[Size] = 0xaa;
64         },
65         "");
66   }
67 }
68 
69 template <typename Config> struct TestAllocator : scudo::Allocator<Config> {
70   TestAllocator() {
71     this->reset();
72     this->initThreadMaybe();
73     if (scudo::archSupportsMemoryTagging() &&
74         !scudo::systemDetectsMemoryTagFaultsTestOnly())
75       this->disableMemoryTagging();
76   }
77   ~TestAllocator() { this->unmapTestOnly(); }
78 
79   void *operator new(size_t size) {
80     void *p = nullptr;
81     EXPECT_EQ(0, posix_memalign(&p, alignof(TestAllocator), size));
82     return p;
83   }
84 
85   void operator delete(void *ptr) { free(ptr); }
86 };
87 
88 template <class TypeParam> struct ScudoCombinedTest : public Test {
89   ScudoCombinedTest() {
90     UseQuarantine = std::is_same<TypeParam, scudo::AndroidConfig>::value;
91     Allocator = std::make_unique<AllocatorT>();
92   }
93   ~ScudoCombinedTest() {
94     Allocator->releaseToOS();
95     UseQuarantine = true;
96   }
97 
98   void RunTest();
99 
100   void BasicTest(scudo::uptr SizeLogMin, scudo::uptr SizeLogMax);
101 
102   using AllocatorT = TestAllocator<TypeParam>;
103   std::unique_ptr<AllocatorT> Allocator;
104 };
105 
106 #if SCUDO_FUCHSIA
107 #define SCUDO_TYPED_TEST_ALL_TYPES(FIXTURE, NAME)                              \
108   SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, AndroidSvelteConfig)                    \
109   SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, FuchsiaConfig)
110 #else
111 #define SCUDO_TYPED_TEST_ALL_TYPES(FIXTURE, NAME)                              \
112   SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, AndroidSvelteConfig)                    \
113   SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, DefaultConfig)                          \
114   SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, AndroidConfig)
115 #endif
116 
117 #define SCUDO_TYPED_TEST_TYPE(FIXTURE, NAME, TYPE)                             \
118   using FIXTURE##NAME##_##TYPE = FIXTURE##NAME<scudo::TYPE>;                   \
119   TEST_F(FIXTURE##NAME##_##TYPE, NAME) { Run(); }
120 
121 #define SCUDO_TYPED_TEST(FIXTURE, NAME)                                        \
122   template <class TypeParam>                                                   \
123   struct FIXTURE##NAME : public FIXTURE<TypeParam> {                           \
124     void Run();                                                                \
125   };                                                                           \
126   SCUDO_TYPED_TEST_ALL_TYPES(FIXTURE, NAME)                                    \
127   template <class TypeParam> void FIXTURE##NAME<TypeParam>::Run()
128 
129 SCUDO_TYPED_TEST(ScudoCombinedTest, IsOwned) {
130   auto *Allocator = this->Allocator.get();
131   static scudo::u8 StaticBuffer[scudo::Chunk::getHeaderSize() + 1];
132   EXPECT_FALSE(
133       Allocator->isOwned(&StaticBuffer[scudo::Chunk::getHeaderSize()]));
134 
135   scudo::u8 StackBuffer[scudo::Chunk::getHeaderSize() + 1];
136   for (scudo::uptr I = 0; I < sizeof(StackBuffer); I++)
137     StackBuffer[I] = 0x42U;
138   EXPECT_FALSE(Allocator->isOwned(&StackBuffer[scudo::Chunk::getHeaderSize()]));
139   for (scudo::uptr I = 0; I < sizeof(StackBuffer); I++)
140     EXPECT_EQ(StackBuffer[I], 0x42U);
141 }
142 
143 template <class Config>
144 void ScudoCombinedTest<Config>::BasicTest(scudo::uptr SizeLogMin,
145                                           scudo::uptr SizeLogMax) {
146   auto *Allocator = this->Allocator.get();
147 
148   // This allocates and deallocates a bunch of chunks, with a wide range of
149   // sizes and alignments, with a focus on sizes that could trigger weird
150   // behaviors (plus or minus a small delta of a power of two for example).
151   for (scudo::uptr SizeLog = SizeLogMin; SizeLog <= SizeLogMax; SizeLog++) {
152     for (scudo::uptr AlignLog = MinAlignLog; AlignLog <= 16U; AlignLog++) {
153       const scudo::uptr Align = 1U << AlignLog;
154       for (scudo::sptr Delta = -32; Delta <= 32; Delta++) {
155         if (static_cast<scudo::sptr>(1U << SizeLog) + Delta <= 0)
156           continue;
157         const scudo::uptr Size = (1U << SizeLog) + Delta;
158         void *P = Allocator->allocate(Size, Origin, Align);
159         EXPECT_NE(P, nullptr);
160         EXPECT_TRUE(Allocator->isOwned(P));
161         EXPECT_TRUE(scudo::isAligned(reinterpret_cast<scudo::uptr>(P), Align));
162         EXPECT_LE(Size, Allocator->getUsableSize(P));
163         memset(P, 0xaa, Size);
164         checkMemoryTaggingMaybe(Allocator, P, Size, Align);
165         Allocator->deallocate(P, Origin, Size);
166       }
167     }
168   }
169 }
170 
171 SCUDO_TYPED_TEST(ScudoCombinedTest, BasicCombined0) { this->BasicTest(0, 16); }
172 SCUDO_TYPED_TEST(ScudoCombinedTest, BasicCombined1) { this->BasicTest(17, 18); }
173 SCUDO_TYPED_TEST(ScudoCombinedTest, BasicCombined2) { this->BasicTest(19, 19); }
174 SCUDO_TYPED_TEST(ScudoCombinedTest, BasicCombined3) { this->BasicTest(20, 20); }
175 
176 SCUDO_TYPED_TEST(ScudoCombinedTest, ZeroContents) {
177   auto *Allocator = this->Allocator.get();
178 
179   // Ensure that specifying ZeroContents returns a zero'd out block.
180   for (scudo::uptr SizeLog = 0U; SizeLog <= 20U; SizeLog++) {
181     for (scudo::uptr Delta = 0U; Delta <= 4U; Delta++) {
182       const scudo::uptr Size = (1U << SizeLog) + Delta * 128U;
183       void *P = Allocator->allocate(Size, Origin, 1U << MinAlignLog, true);
184       EXPECT_NE(P, nullptr);
185       for (scudo::uptr I = 0; I < Size; I++)
186         ASSERT_EQ((reinterpret_cast<char *>(P))[I], 0);
187       memset(P, 0xaa, Size);
188       Allocator->deallocate(P, Origin, Size);
189     }
190   }
191 }
192 
193 SCUDO_TYPED_TEST(ScudoCombinedTest, ZeroFill) {
194   auto *Allocator = this->Allocator.get();
195 
196   // Ensure that specifying ZeroContents returns a zero'd out block.
197   Allocator->setFillContents(scudo::ZeroFill);
198   for (scudo::uptr SizeLog = 0U; SizeLog <= 20U; SizeLog++) {
199     for (scudo::uptr Delta = 0U; Delta <= 4U; Delta++) {
200       const scudo::uptr Size = (1U << SizeLog) + Delta * 128U;
201       void *P = Allocator->allocate(Size, Origin, 1U << MinAlignLog, false);
202       EXPECT_NE(P, nullptr);
203       for (scudo::uptr I = 0; I < Size; I++)
204         ASSERT_EQ((reinterpret_cast<char *>(P))[I], 0);
205       memset(P, 0xaa, Size);
206       Allocator->deallocate(P, Origin, Size);
207     }
208   }
209 }
210 
211 SCUDO_TYPED_TEST(ScudoCombinedTest, PatternOrZeroFill) {
212   auto *Allocator = this->Allocator.get();
213 
214   // Ensure that specifying PatternOrZeroFill returns a pattern or zero filled
215   // block. The primary allocator only produces pattern filled blocks if MTE
216   // is disabled, so we only require pattern filled blocks in that case.
217   Allocator->setFillContents(scudo::PatternOrZeroFill);
218   for (scudo::uptr SizeLog = 0U; SizeLog <= 20U; SizeLog++) {
219     for (scudo::uptr Delta = 0U; Delta <= 4U; Delta++) {
220       const scudo::uptr Size = (1U << SizeLog) + Delta * 128U;
221       void *P = Allocator->allocate(Size, Origin, 1U << MinAlignLog, false);
222       EXPECT_NE(P, nullptr);
223       for (scudo::uptr I = 0; I < Size; I++) {
224         unsigned char V = (reinterpret_cast<unsigned char *>(P))[I];
225         if (isPrimaryAllocation<TestAllocator<TypeParam>>(Size,
226                                                           1U << MinAlignLog) &&
227             !Allocator->useMemoryTaggingTestOnly())
228           ASSERT_EQ(V, scudo::PatternFillByte);
229         else
230           ASSERT_TRUE(V == scudo::PatternFillByte || V == 0);
231       }
232       memset(P, 0xaa, Size);
233       Allocator->deallocate(P, Origin, Size);
234     }
235   }
236 }
237 
238 SCUDO_TYPED_TEST(ScudoCombinedTest, BlockReuse) {
239   auto *Allocator = this->Allocator.get();
240 
241   // Verify that a chunk will end up being reused, at some point.
242   const scudo::uptr NeedleSize = 1024U;
243   void *NeedleP = Allocator->allocate(NeedleSize, Origin);
244   Allocator->deallocate(NeedleP, Origin);
245   bool Found = false;
246   for (scudo::uptr I = 0; I < 1024U && !Found; I++) {
247     void *P = Allocator->allocate(NeedleSize, Origin);
248     if (Allocator->getHeaderTaggedPointer(P) ==
249         Allocator->getHeaderTaggedPointer(NeedleP))
250       Found = true;
251     Allocator->deallocate(P, Origin);
252   }
253   EXPECT_TRUE(Found);
254 }
255 
256 SCUDO_TYPED_TEST(ScudoCombinedTest, ReallocateLarge) {
257   auto *Allocator = this->Allocator.get();
258 
259   // Reallocate a large chunk all the way down to a byte, verifying that we
260   // preserve the data in the process.
261   scudo::uptr Size = TypeParam::Primary::SizeClassMap::MaxSize * 2;
262   const scudo::uptr DataSize = 2048U;
263   void *P = Allocator->allocate(Size, Origin);
264   const char Marker = 0xab;
265   memset(P, Marker, scudo::Min(Size, DataSize));
266   while (Size > 1U) {
267     Size /= 2U;
268     void *NewP = Allocator->reallocate(P, Size);
269     EXPECT_NE(NewP, nullptr);
270     for (scudo::uptr J = 0; J < scudo::Min(Size, DataSize); J++)
271       EXPECT_EQ((reinterpret_cast<char *>(NewP))[J], Marker);
272     P = NewP;
273   }
274   Allocator->deallocate(P, Origin);
275 }
276 
277 SCUDO_TYPED_TEST(ScudoCombinedTest, ReallocateSame) {
278   auto *Allocator = this->Allocator.get();
279 
280   // Check that reallocating a chunk to a slightly smaller or larger size
281   // returns the same chunk. This requires that all the sizes we iterate on use
282   // the same block size, but that should be the case for MaxSize - 64 with our
283   // default class size maps.
284   constexpr scudo::uptr ReallocSize =
285       TypeParam::Primary::SizeClassMap::MaxSize - 64;
286   void *P = Allocator->allocate(ReallocSize, Origin);
287   const char Marker = 0xab;
288   memset(P, Marker, ReallocSize);
289   for (scudo::sptr Delta = -32; Delta < 32; Delta += 8) {
290     const scudo::uptr NewSize = ReallocSize + Delta;
291     void *NewP = Allocator->reallocate(P, NewSize);
292     EXPECT_EQ(NewP, P);
293     for (scudo::uptr I = 0; I < ReallocSize - 32; I++)
294       EXPECT_EQ((reinterpret_cast<char *>(NewP))[I], Marker);
295     checkMemoryTaggingMaybe(Allocator, NewP, NewSize, 0);
296   }
297   Allocator->deallocate(P, Origin);
298 }
299 
300 SCUDO_TYPED_TEST(ScudoCombinedTest, IterateOverChunks) {
301   auto *Allocator = this->Allocator.get();
302   // Allocates a bunch of chunks, then iterate over all the chunks, ensuring
303   // they are the ones we allocated. This requires the allocator to not have any
304   // other allocated chunk at this point (eg: won't work with the Quarantine).
305   // FIXME: Make it work with UseQuarantine and tagging enabled. Internals of
306   // iterateOverChunks reads header by tagged and non-tagger pointers so one of
307   // them will fail.
308   if (!UseQuarantine) {
309     std::vector<void *> V;
310     for (scudo::uptr I = 0; I < 64U; I++)
311       V.push_back(Allocator->allocate(
312           rand() % (TypeParam::Primary::SizeClassMap::MaxSize / 2U), Origin));
313     Allocator->disable();
314     Allocator->iterateOverChunks(
315         0U, static_cast<scudo::uptr>(SCUDO_MMAP_RANGE_SIZE - 1),
316         [](uintptr_t Base, size_t Size, void *Arg) {
317           std::vector<void *> *V = reinterpret_cast<std::vector<void *> *>(Arg);
318           void *P = reinterpret_cast<void *>(Base);
319           EXPECT_NE(std::find(V->begin(), V->end(), P), V->end());
320         },
321         reinterpret_cast<void *>(&V));
322     Allocator->enable();
323     for (auto P : V)
324       Allocator->deallocate(P, Origin);
325   }
326 }
327 
328 SCUDO_TYPED_TEST(ScudoCombinedTest, UseAfterFree) {
329   auto *Allocator = this->Allocator.get();
330 
331   // Check that use-after-free is detected.
332   for (scudo::uptr SizeLog = 0U; SizeLog <= 20U; SizeLog++) {
333     const scudo::uptr Size = 1U << SizeLog;
334     if (!Allocator->useMemoryTaggingTestOnly())
335       continue;
336     EXPECT_DEATH(
337         {
338           disableDebuggerdMaybe();
339           void *P = Allocator->allocate(Size, Origin);
340           Allocator->deallocate(P, Origin);
341           reinterpret_cast<char *>(P)[0] = 0xaa;
342         },
343         "");
344     EXPECT_DEATH(
345         {
346           disableDebuggerdMaybe();
347           void *P = Allocator->allocate(Size, Origin);
348           Allocator->deallocate(P, Origin);
349           reinterpret_cast<char *>(P)[Size - 1] = 0xaa;
350         },
351         "");
352   }
353 }
354 
355 SCUDO_TYPED_TEST(ScudoCombinedTest, DisableMemoryTagging) {
356   auto *Allocator = this->Allocator.get();
357 
358   if (Allocator->useMemoryTaggingTestOnly()) {
359     // Check that disabling memory tagging works correctly.
360     void *P = Allocator->allocate(2048, Origin);
361     EXPECT_DEATH(reinterpret_cast<char *>(P)[2048] = 0xaa, "");
362     scudo::disableMemoryTagChecksTestOnly();
363     Allocator->disableMemoryTagging();
364     reinterpret_cast<char *>(P)[2048] = 0xaa;
365     Allocator->deallocate(P, Origin);
366 
367     P = Allocator->allocate(2048, Origin);
368     EXPECT_EQ(scudo::untagPointer(P), P);
369     reinterpret_cast<char *>(P)[2048] = 0xaa;
370     Allocator->deallocate(P, Origin);
371 
372     Allocator->releaseToOS();
373 
374     // Disabling memory tag checks may interfere with subsequent tests.
375     // Re-enable them now.
376     scudo::enableMemoryTagChecksTestOnly();
377   }
378 }
379 
380 SCUDO_TYPED_TEST(ScudoCombinedTest, Stats) {
381   auto *Allocator = this->Allocator.get();
382 
383   scudo::uptr BufferSize = 8192;
384   std::vector<char> Buffer(BufferSize);
385   scudo::uptr ActualSize = Allocator->getStats(Buffer.data(), BufferSize);
386   while (ActualSize > BufferSize) {
387     BufferSize = ActualSize + 1024;
388     Buffer.resize(BufferSize);
389     ActualSize = Allocator->getStats(Buffer.data(), BufferSize);
390   }
391   std::string Stats(Buffer.begin(), Buffer.end());
392   // Basic checks on the contents of the statistics output, which also allows us
393   // to verify that we got it all.
394   EXPECT_NE(Stats.find("Stats: SizeClassAllocator"), std::string::npos);
395   EXPECT_NE(Stats.find("Stats: MapAllocator"), std::string::npos);
396   EXPECT_NE(Stats.find("Stats: Quarantine"), std::string::npos);
397 }
398 
399 SCUDO_TYPED_TEST(ScudoCombinedTest, CacheDrain) {
400   auto *Allocator = this->Allocator.get();
401 
402   std::vector<void *> V;
403   for (scudo::uptr I = 0; I < 64U; I++)
404     V.push_back(Allocator->allocate(
405         rand() % (TypeParam::Primary::SizeClassMap::MaxSize / 2U), Origin));
406   for (auto P : V)
407     Allocator->deallocate(P, Origin);
408 
409   bool UnlockRequired;
410   auto *TSD = Allocator->getTSDRegistry()->getTSDAndLock(&UnlockRequired);
411   EXPECT_TRUE(!TSD->Cache.isEmpty());
412   TSD->Cache.drain();
413   EXPECT_TRUE(TSD->Cache.isEmpty());
414   if (UnlockRequired)
415     TSD->unlock();
416 }
417 
418 SCUDO_TYPED_TEST(ScudoCombinedTest, ThreadedCombined) {
419   std::mutex Mutex;
420   std::condition_variable Cv;
421   bool Ready = false;
422   auto *Allocator = this->Allocator.get();
423   std::thread Threads[32];
424   for (scudo::uptr I = 0; I < ARRAY_SIZE(Threads); I++)
425     Threads[I] = std::thread([&]() {
426       {
427         std::unique_lock<std::mutex> Lock(Mutex);
428         while (!Ready)
429           Cv.wait(Lock);
430       }
431       std::vector<std::pair<void *, scudo::uptr>> V;
432       for (scudo::uptr I = 0; I < 256U; I++) {
433         const scudo::uptr Size = std::rand() % 4096U;
434         void *P = Allocator->allocate(Size, Origin);
435         // A region could have ran out of memory, resulting in a null P.
436         if (P)
437           V.push_back(std::make_pair(P, Size));
438       }
439       while (!V.empty()) {
440         auto Pair = V.back();
441         Allocator->deallocate(Pair.first, Origin, Pair.second);
442         V.pop_back();
443       }
444     });
445   {
446     std::unique_lock<std::mutex> Lock(Mutex);
447     Ready = true;
448     Cv.notify_all();
449   }
450   for (auto &T : Threads)
451     T.join();
452   Allocator->releaseToOS();
453 }
454 
455 #if SCUDO_FUCHSIA
456 #define SKIP_ON_FUCHSIA(T) DISABLED_##T
457 #else
458 #define SKIP_ON_FUCHSIA(T) T
459 #endif
460 
461 // Test that multiple instantiations of the allocator have not messed up the
462 // process's signal handlers (GWP-ASan used to do this).
463 TEST(ScudoCombinedTest, SKIP_ON_FUCHSIA(testSEGV)) {
464   const scudo::uptr Size = 4 * scudo::getPageSizeCached();
465   scudo::MapPlatformData Data = {};
466   void *P = scudo::map(nullptr, Size, "testSEGV", MAP_NOACCESS, &Data);
467   EXPECT_NE(P, nullptr);
468   EXPECT_DEATH(memset(P, 0xaa, Size), "");
469   scudo::unmap(P, Size, UNMAP_ALL, &Data);
470 }
471 
472 struct DeathSizeClassConfig {
473   static const scudo::uptr NumBits = 1;
474   static const scudo::uptr MinSizeLog = 10;
475   static const scudo::uptr MidSizeLog = 10;
476   static const scudo::uptr MaxSizeLog = 13;
477   static const scudo::u32 MaxNumCachedHint = 4;
478   static const scudo::uptr MaxBytesCachedLog = 12;
479 };
480 
481 static const scudo::uptr DeathRegionSizeLog = 20U;
482 struct DeathConfig {
483   static const bool MaySupportMemoryTagging = false;
484 
485   // Tiny allocator, its Primary only serves chunks of four sizes.
486   using SizeClassMap = scudo::FixedSizeClassMap<DeathSizeClassConfig>;
487   typedef scudo::SizeClassAllocator64<DeathConfig> Primary;
488   static const scudo::uptr PrimaryRegionSizeLog = DeathRegionSizeLog;
489   static const scudo::s32 PrimaryMinReleaseToOsIntervalMs = INT32_MIN;
490   static const scudo::s32 PrimaryMaxReleaseToOsIntervalMs = INT32_MAX;
491   typedef scudo::uptr PrimaryCompactPtrT;
492   static const scudo::uptr PrimaryCompactPtrScale = 0;
493 
494   typedef scudo::MapAllocatorNoCache SecondaryCache;
495   template <class A> using TSDRegistryT = scudo::TSDRegistrySharedT<A, 1U, 1U>;
496 };
497 
498 TEST(ScudoCombinedTest, DeathCombined) {
499   using AllocatorT = TestAllocator<DeathConfig>;
500   auto Allocator = std::unique_ptr<AllocatorT>(new AllocatorT());
501 
502   const scudo::uptr Size = 1000U;
503   void *P = Allocator->allocate(Size, Origin);
504   EXPECT_NE(P, nullptr);
505 
506   // Invalid sized deallocation.
507   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size + 8U), "");
508 
509   // Misaligned pointer. Potentially unused if EXPECT_DEATH isn't available.
510   UNUSED void *MisalignedP =
511       reinterpret_cast<void *>(reinterpret_cast<scudo::uptr>(P) | 1U);
512   EXPECT_DEATH(Allocator->deallocate(MisalignedP, Origin, Size), "");
513   EXPECT_DEATH(Allocator->reallocate(MisalignedP, Size * 2U), "");
514 
515   // Header corruption.
516   scudo::u64 *H =
517       reinterpret_cast<scudo::u64 *>(scudo::Chunk::getAtomicHeader(P));
518   *H ^= 0x42U;
519   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
520   *H ^= 0x420042U;
521   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
522   *H ^= 0x420000U;
523 
524   // Invalid chunk state.
525   Allocator->deallocate(P, Origin, Size);
526   EXPECT_DEATH(Allocator->deallocate(P, Origin, Size), "");
527   EXPECT_DEATH(Allocator->reallocate(P, Size * 2U), "");
528   EXPECT_DEATH(Allocator->getUsableSize(P), "");
529 }
530 
531 // Ensure that releaseToOS can be called prior to any other allocator
532 // operation without issue.
533 TEST(ScudoCombinedTest, ReleaseToOS) {
534   using AllocatorT = TestAllocator<DeathConfig>;
535   auto Allocator = std::unique_ptr<AllocatorT>(new AllocatorT());
536 
537   Allocator->releaseToOS();
538 }
539 
540 // Verify that when a region gets full, the allocator will still manage to
541 // fulfill the allocation through a larger size class.
542 TEST(ScudoCombinedTest, FullRegion) {
543   using AllocatorT = TestAllocator<DeathConfig>;
544   auto Allocator = std::unique_ptr<AllocatorT>(new AllocatorT());
545 
546   std::vector<void *> V;
547   scudo::uptr FailedAllocationsCount = 0;
548   for (scudo::uptr ClassId = 1U;
549        ClassId <= DeathConfig::SizeClassMap::LargestClassId; ClassId++) {
550     const scudo::uptr Size =
551         DeathConfig::SizeClassMap::getSizeByClassId(ClassId);
552     // Allocate enough to fill all of the regions above this one.
553     const scudo::uptr MaxNumberOfChunks =
554         ((1U << DeathRegionSizeLog) / Size) *
555         (DeathConfig::SizeClassMap::LargestClassId - ClassId + 1);
556     void *P;
557     for (scudo::uptr I = 0; I <= MaxNumberOfChunks; I++) {
558       P = Allocator->allocate(Size - 64U, Origin);
559       if (!P)
560         FailedAllocationsCount++;
561       else
562         V.push_back(P);
563     }
564     while (!V.empty()) {
565       Allocator->deallocate(V.back(), Origin);
566       V.pop_back();
567     }
568   }
569   EXPECT_EQ(FailedAllocationsCount, 0U);
570 }
571 
572 TEST(ScudoCombinedTest, OddEven) {
573   using AllocatorT = TestAllocator<scudo::AndroidConfig>;
574   using SizeClassMap = AllocatorT::PrimaryT::SizeClassMap;
575   auto Allocator = std::unique_ptr<AllocatorT>(new AllocatorT());
576 
577   if (!Allocator->useMemoryTaggingTestOnly())
578     return;
579 
580   auto CheckOddEven = [](scudo::uptr P1, scudo::uptr P2) {
581     scudo::uptr Tag1 = scudo::extractTag(scudo::loadTag(P1));
582     scudo::uptr Tag2 = scudo::extractTag(scudo::loadTag(P2));
583     EXPECT_NE(Tag1 % 2, Tag2 % 2);
584   };
585 
586   for (scudo::uptr ClassId = 1U; ClassId <= SizeClassMap::LargestClassId;
587        ClassId++) {
588     const scudo::uptr Size = SizeClassMap::getSizeByClassId(ClassId);
589 
590     std::set<scudo::uptr> Ptrs;
591     bool Found = false;
592     for (unsigned I = 0; I != 65536; ++I) {
593       scudo::uptr P = scudo::untagPointer(reinterpret_cast<scudo::uptr>(
594           Allocator->allocate(Size - scudo::Chunk::getHeaderSize(), Origin)));
595       if (Ptrs.count(P - Size)) {
596         Found = true;
597         CheckOddEven(P, P - Size);
598         break;
599       }
600       if (Ptrs.count(P + Size)) {
601         Found = true;
602         CheckOddEven(P, P + Size);
603         break;
604       }
605       Ptrs.insert(P);
606     }
607     EXPECT_TRUE(Found);
608   }
609 }
610 
611 TEST(ScudoCombinedTest, DisableMemInit) {
612   using AllocatorT = TestAllocator<scudo::AndroidConfig>;
613   using SizeClassMap = AllocatorT::PrimaryT::SizeClassMap;
614   auto Allocator = std::unique_ptr<AllocatorT>(new AllocatorT());
615 
616   std::vector<void *> Ptrs(65536, nullptr);
617 
618   Allocator->setOption(scudo::Option::ThreadDisableMemInit, 1);
619 
620   constexpr scudo::uptr MinAlignLog = FIRST_32_SECOND_64(3U, 4U);
621 
622   // Test that if mem-init is disabled on a thread, calloc should still work as
623   // expected. This is tricky to ensure when MTE is enabled, so this test tries
624   // to exercise the relevant code on our MTE path.
625   for (scudo::uptr ClassId = 1U; ClassId <= 8; ClassId++) {
626     const scudo::uptr Size =
627         SizeClassMap::getSizeByClassId(ClassId) - scudo::Chunk::getHeaderSize();
628     if (Size < 8)
629       continue;
630     for (unsigned I = 0; I != Ptrs.size(); ++I) {
631       Ptrs[I] = Allocator->allocate(Size, Origin);
632       memset(Ptrs[I], 0xaa, Size);
633     }
634     for (unsigned I = 0; I != Ptrs.size(); ++I)
635       Allocator->deallocate(Ptrs[I], Origin, Size);
636     for (unsigned I = 0; I != Ptrs.size(); ++I) {
637       Ptrs[I] = Allocator->allocate(Size - 8, Origin);
638       memset(Ptrs[I], 0xbb, Size - 8);
639     }
640     for (unsigned I = 0; I != Ptrs.size(); ++I)
641       Allocator->deallocate(Ptrs[I], Origin, Size - 8);
642     for (unsigned I = 0; I != Ptrs.size(); ++I) {
643       Ptrs[I] = Allocator->allocate(Size, Origin, 1U << MinAlignLog, true);
644       for (scudo::uptr J = 0; J < Size; ++J)
645         ASSERT_EQ((reinterpret_cast<char *>(Ptrs[I]))[J], 0);
646     }
647   }
648 
649   Allocator->setOption(scudo::Option::ThreadDisableMemInit, 0);
650 }
651