xref: /aosp_15_r20/external/scudo/standalone/tests/vector_test.cpp (revision 76559068c068bd27e82aff38fac3bfc865233bca)
1 //===-- vector_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 "vector.h"
12 
TEST(ScudoVectorTest,Basic)13 TEST(ScudoVectorTest, Basic) {
14   scudo::Vector<int, 64U> V;
15   EXPECT_EQ(V.size(), 0U);
16   V.push_back(42);
17   EXPECT_EQ(V.size(), 1U);
18   EXPECT_EQ(V[0], 42);
19   V.push_back(43);
20   EXPECT_EQ(V.size(), 2U);
21   EXPECT_EQ(V[0], 42);
22   EXPECT_EQ(V[1], 43);
23 }
24 
TEST(ScudoVectorTest,Stride)25 TEST(ScudoVectorTest, Stride) {
26   scudo::Vector<scudo::uptr, 32U> V;
27   for (scudo::uptr I = 0; I < 1000; I++) {
28     V.push_back(I);
29     EXPECT_EQ(V.size(), I + 1U);
30     EXPECT_EQ(V[I], I);
31   }
32   for (scudo::uptr I = 0; I < 1000; I++)
33     EXPECT_EQ(V[I], I);
34 }
35 
TEST(ScudoVectorTest,ResizeReduction)36 TEST(ScudoVectorTest, ResizeReduction) {
37   scudo::Vector<int, 64U> V;
38   V.push_back(0);
39   V.push_back(0);
40   EXPECT_EQ(V.size(), 2U);
41   V.resize(1);
42   EXPECT_EQ(V.size(), 1U);
43 }
44 
45 #if defined(__linux__)
46 
47 #include <sys/resource.h>
48 
49 // Verify that if the reallocate fails, nothing new is added.
TEST(ScudoVectorTest,ReallocateFails)50 TEST(ScudoVectorTest, ReallocateFails) {
51   scudo::Vector<char, 256U> V;
52   scudo::uptr capacity = V.capacity();
53 
54   // Get the current address space size.
55   rlimit Limit = {};
56   EXPECT_EQ(0, getrlimit(RLIMIT_AS, &Limit));
57 
58   rlimit EmptyLimit = {.rlim_cur = 0, .rlim_max = Limit.rlim_max};
59   EXPECT_EQ(0, setrlimit(RLIMIT_AS, &EmptyLimit));
60 
61   // qemu does not honor the setrlimit, so verify before proceeding.
62   scudo::MemMapT MemMap;
63   if (MemMap.map(/*Addr=*/0U, scudo::getPageSizeCached(), "scudo:test",
64                  MAP_ALLOWNOMEM)) {
65     MemMap.unmap();
66     setrlimit(RLIMIT_AS, &Limit);
67     TEST_SKIP("Limiting address space does not prevent mmap.");
68   }
69 
70   V.resize(capacity);
71   // Set the last element so we can check it later.
72   V.back() = '\0';
73 
74   // The reallocate should fail, so the capacity should not change.
75   V.reserve(capacity + 1000);
76   EXPECT_EQ(capacity, V.capacity());
77 
78   // Now try to do a push back and verify that the size does not change.
79   scudo::uptr Size = V.size();
80   V.push_back('2');
81   EXPECT_EQ(Size, V.size());
82   // Verify that the last element in the vector did not change.
83   EXPECT_EQ('\0', V.back());
84 
85   EXPECT_EQ(0, setrlimit(RLIMIT_AS, &Limit));
86 }
87 #endif
88