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