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