[scudo] Fix EXPECT_DEATH tests

Put allocate/deallocate next to memory
access inside EXPECT_DEATH block.
This way we reduce probability that memory is not mapped
by unrelated code.

It's still not absolutely guaranty that mmap does not
happen so we repeat it few times to be sure.

Reviewed By: cryptoad

Differential Revision: https://reviews.llvm.org/D102886

GitOrigin-RevId: 96b760607f8e82e563dc8cac67b2d2dfb76d5d33
diff --git a/tests/map_test.cpp b/tests/map_test.cpp
index 7c40b73..149a704 100644
--- a/tests/map_test.cpp
+++ b/tests/map_test.cpp
@@ -31,11 +31,19 @@
 
 TEST(ScudoMapTest, MapUnmap) {
   const scudo::uptr Size = 4 * scudo::getPageSizeCached();
-  void *P = scudo::map(nullptr, Size, MappingName, 0, nullptr);
-  EXPECT_NE(P, nullptr);
-  memset(P, 0xaa, Size);
-  scudo::unmap(P, Size, 0, nullptr);
-  EXPECT_DEATH(memset(P, 0xbb, Size), "");
+  EXPECT_DEATH(
+      {
+        // Repeat few time to avoid missing crash if it's mmaped by unrelated
+        // code.
+        for (int i = 0; i < 10; ++i) {
+          void *P = scudo::map(nullptr, Size, MappingName, 0, nullptr);
+          if (!P)
+            continue;
+          scudo::unmap(P, Size, 0, nullptr);
+          memset(P, 0xbb, Size);
+        }
+      },
+      "");
 }
 
 TEST(ScudoMapTest, MapWithGuardUnmap) {
diff --git a/tests/secondary_test.cpp b/tests/secondary_test.cpp
index 9dcf52d..d5d1599 100644
--- a/tests/secondary_test.cpp
+++ b/tests/secondary_test.cpp
@@ -39,9 +39,20 @@
 // the test on arm32 until we can debug it further.
 #ifndef __arm__
   // If the Secondary can't cache that pointer, it will be unmapped.
-  if (!L->canCache(Size))
-    EXPECT_DEATH(memset(P, 'A', Size), "");
+  if (!L->canCache(Size)) {
+    EXPECT_DEATH(
+        {
+          // Repeat few time to avoid missing crash if it's mmaped by unrelated
+          // code.
+          for (int i = 0; i < 10; ++i) {
+            P = L->allocate(scudo::Options{}, Size);
+            L->deallocate(scudo::Options{}, P);
+            memset(P, 'A', Size);
+          }
+        },
+        "");
 #endif // __arm__
+  }
 
   const scudo::uptr Align = 1U << 16;
   P = L->allocate(scudo::Options{}, Size + Align, Align);