From 51655c601b3246457e27cf296284c049641c470c Mon Sep 17 00:00:00 2001 From: Daniel Schemmel Date: Thu, 13 Oct 2022 14:25:08 +0100 Subject: Add some unit tests for KDAlloc --- unittests/KDAlloc/sample.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 unittests/KDAlloc/sample.cpp (limited to 'unittests/KDAlloc/sample.cpp') 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 + +#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(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(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(allocator2.allocate(sizeof(int))); + assert(reinterpret_cast(my_int) == + reinterpret_cast(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(allocator2.allocate(sizeof(int))); + assert(reinterpret_cast(my_int) != + reinterpret_cast(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 -- cgit 1.4.1