about summary refs log tree commit diff homepage
path: root/unittests/KDAlloc/allocate.cpp
blob: 895f82154d74452a9351afa86317baa5a1d3a841 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//===-- allocate.cpp ------------------------------------------------------===//
//
//                     The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "klee/KDAlloc/kdalloc.h"

#if defined(USE_GTEST_INSTEAD_OF_MAIN)
#include "gtest/gtest.h"
#endif

#include <cassert>
#include <deque>
#include <iomanip>
#include <iostream>

#if defined(USE_GTEST_INSTEAD_OF_MAIN)
int allocate_sample_test() {
#else
int main() {
#endif
  // initialize a factory and an associated allocator (using the location "0"
  // gives an OS-assigned location)
  klee::kdalloc::AllocatorFactory factory(static_cast<std::size_t>(1) << 20, 0);
  klee::kdalloc::Allocator allocator = factory.makeAllocator();

  std::deque<void *> allocations;
  for (std::size_t i = 0; i < 10; ++i) {
    auto p = allocator.allocate(4);
    allocations.emplace_back(p);
    std::cout << "Allocated     " << std::right << std::setw(64 / 4) << std::hex
              << (static_cast<char *>(p) -
                  static_cast<char *>(factory.getMapping().getBaseAddress()))
              << "\n";
  }

  {
    auto p = allocations[2];
    allocations.erase(allocations.begin() + 2);
    std::cout << "Freeing       " << std::right << std::setw(64 / 4) << std::hex
              << (static_cast<char *>(p) -
                  static_cast<char *>(factory.getMapping().getBaseAddress()))
              << "\n";
    allocator.free(p, 4);
  }

  for (auto p : allocations) {
    std::cout << "Freeing       " << std::right << std::setw(64 / 4) << std::hex
              << (static_cast<char *>(p) -
                  static_cast<char *>(factory.getMapping().getBaseAddress()))
              << "\n";
    allocator.free(p, 4);
  }

  exit(0);
}

#if defined(USE_GTEST_INSTEAD_OF_MAIN)
TEST(KDAllocDeathTest, AllocateSample) {
  ASSERT_EXIT(allocate_sample_test(), ::testing::ExitedWithCode(0), "");
}
#endif