about summary refs log tree commit diff homepage
path: root/unittests/KDAlloc/sample.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'unittests/KDAlloc/sample.cpp')
-rw-r--r--unittests/KDAlloc/sample.cpp68
1 files changed, 68 insertions, 0 deletions
diff --git a/unittests/KDAlloc/sample.cpp b/unittests/KDAlloc/sample.cpp
new file mode 100644
index 00000000..d4bed00b
--- /dev/null
+++ b/unittests/KDAlloc/sample.cpp
@@ -0,0 +1,68 @@
+//===-- sample.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>
+
+#if defined(USE_GTEST_INSTEAD_OF_MAIN)
+int 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) << 40, 0);
+  klee::kdalloc::Allocator allocator = factory.makeAllocator();
+
+  // let us create an integer
+  void *ptr = allocator.allocate(sizeof(int));
+  int *my_int = static_cast<int *>(ptr);
+  *my_int = 42;
+  assert(*my_int == 42 &&
+         "While we can use the addresses, this is not the point of kdalloc");
+
+  {
+    auto allocator2 = factory.makeAllocator();
+    int *my_second_int = static_cast<int *>(allocator2.allocate(sizeof(int)));
+    assert(reinterpret_cast<std::uintptr_t>(my_int) ==
+               reinterpret_cast<std::uintptr_t>(my_second_int) &&
+           "kdalloc is intended to produce reproducible addresses");
+    allocator2.free(my_second_int, sizeof(int));
+    assert(*my_int == 42 &&
+           "The original allocation (from allocator) is still valid");
+  }
+
+  // now let us clone the allocator state
+  {
+    auto allocator2 = allocator;
+    int *my_second_int = static_cast<int *>(allocator2.allocate(sizeof(int)));
+    assert(reinterpret_cast<std::uintptr_t>(my_int) !=
+               reinterpret_cast<std::uintptr_t>(my_second_int) &&
+           "the new address must be different, as allocator2 also contains the "
+           "previous allocation");
+    allocator2.free(my_second_int, sizeof(int));
+    assert(*my_int == 42 &&
+           "The original allocation (from allocator) is still valid");
+  }
+
+  // there is no need to return allocated memory, so we omit
+  // `allocator.free(my_int, sizeof(int));`
+  exit(0);
+}
+
+#if defined(USE_GTEST_INSTEAD_OF_MAIN)
+TEST(KDAllocDeathTest, Sample) {
+  ASSERT_EXIT(sample_test(), ::testing::ExitedWithCode(0), "");
+}
+#endif