brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.3 KiB · 010d29a Raw
79 lines · cpp
1//===-- slot_reuse.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-exception6//7//===----------------------------------------------------------------------===//8 9#include <set>10 11#include "gwp_asan/tests/harness.h"12 13namespace {14 15void singleByteGoodAllocDealloc(gwp_asan::GuardedPoolAllocator *GPA) {16  void *Ptr = GPA->allocate(1);17  EXPECT_NE(nullptr, Ptr);18  EXPECT_TRUE(GPA->pointerIsMine(Ptr));19  EXPECT_EQ(1u, GPA->getSize(Ptr));20  GPA->deallocate(Ptr);21}22 23TEST_F(CustomGuardedPoolAllocator, EnsureReuseOfQuarantine1) {24  InitNumSlots(1);25  for (unsigned i = 0; i < 128; ++i)26    singleByteGoodAllocDealloc(&GPA);27}28 29TEST_F(CustomGuardedPoolAllocator, EnsureReuseOfQuarantine2) {30  InitNumSlots(2);31  for (unsigned i = 0; i < 128; ++i)32    singleByteGoodAllocDealloc(&GPA);33}34 35TEST_F(CustomGuardedPoolAllocator, EnsureReuseOfQuarantine127) {36  InitNumSlots(127);37  for (unsigned i = 0; i < 128; ++i)38    singleByteGoodAllocDealloc(&GPA);39}40 41// This test ensures that our slots are not reused ahead of time. We increase42// the use-after-free detection by not reusing slots until all of them have been43// allocated. This is done by always using the slots from left-to-right in the44// pool before we used each slot once, at which point random selection takes45// over.46void runNoReuseBeforeNecessary(gwp_asan::GuardedPoolAllocator *GPA,47                               unsigned PoolSize) {48  std::set<void *> Ptrs;49  for (unsigned i = 0; i < PoolSize; ++i) {50    void *Ptr = GPA->allocate(1);51 52    EXPECT_TRUE(GPA->pointerIsMine(Ptr));53    EXPECT_EQ(0u, Ptrs.count(Ptr));54 55    Ptrs.insert(Ptr);56    GPA->deallocate(Ptr);57  }58}59 60TEST_F(CustomGuardedPoolAllocator, NoReuseBeforeNecessary2) {61  constexpr unsigned kPoolSize = 2;62  InitNumSlots(kPoolSize);63  runNoReuseBeforeNecessary(&GPA, kPoolSize);64}65 66TEST_F(CustomGuardedPoolAllocator, NoReuseBeforeNecessary128) {67  constexpr unsigned kPoolSize = 128;68  InitNumSlots(kPoolSize);69  runNoReuseBeforeNecessary(&GPA, kPoolSize);70}71 72TEST_F(CustomGuardedPoolAllocator, NoReuseBeforeNecessary129) {73  constexpr unsigned kPoolSize = 129;74  InitNumSlots(kPoolSize);75  runNoReuseBeforeNecessary(&GPA, kPoolSize);76}77 78} // namespace79