xref: /openbsd-src/gnu/llvm/compiler-rt/lib/gwp_asan/tests/iterate.cpp (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 //===-- iterate.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 "gwp_asan/tests/harness.h"
10 
11 TEST_F(CustomGuardedPoolAllocator, Iterate) {
12   InitNumSlots(7);
13   std::vector<std::pair<void *, size_t>> Allocated;
14   auto alloc = [&](size_t size) {
15     Allocated.push_back({GPA.allocate(size), size});
16   };
17 
18   void *Ptr = GPA.allocate(5);
19   alloc(2);
20   alloc(1);
21   alloc(100);
22   GPA.deallocate(Ptr);
23   alloc(42);
24   std::sort(Allocated.begin(), Allocated.end());
25 
26   GPA.disable();
27   void *Base = Allocated[0].first;
28   size_t Size = reinterpret_cast<size_t>(Allocated.back().first) -
29                 reinterpret_cast<size_t>(Base) + 1;
30   std::vector<std::pair<void *, size_t>> Found;
31   GPA.iterate(
32       Base, Size,
33       [](uintptr_t Addr, size_t Size, void *Arg) {
34         reinterpret_cast<std::vector<std::pair<void *, size_t>> *>(Arg)
35             ->push_back({(void *)Addr, Size});
36       },
37       reinterpret_cast<void *>(&Found));
38   GPA.enable();
39 
40   std::sort(Found.begin(), Found.end());
41   EXPECT_EQ(Allocated, Found);
42 
43   // Now without the last allocation.
44   GPA.disable();
45   Size = reinterpret_cast<size_t>(Allocated.back().first) -
46          reinterpret_cast<size_t>(Base); // Allocated.back() is out of range.
47   Found.clear();
48   GPA.iterate(
49       Base, Size,
50       [](uintptr_t Addr, size_t Size, void *Arg) {
51         reinterpret_cast<std::vector<std::pair<void *, size_t>> *>(Arg)
52             ->push_back({(void *)Addr, Size});
53       },
54       reinterpret_cast<void *>(&Found));
55   GPA.enable();
56 
57   // We should have found every allocation but the last.
58   // Remove it and compare the rest.
59   std::sort(Found.begin(), Found.end());
60   GPA.deallocate(Allocated.back().first);
61   Allocated.pop_back();
62   EXPECT_EQ(Allocated, Found);
63 
64   for (auto PS : Allocated)
65     GPA.deallocate(PS.first);
66 }
67