libcopp  1.1.0
stack_allocator_malloc.cpp
Go to the documentation of this file.
1 #include <algorithm>
2 #include <assert.h>
3 #include <cstdlib>
4 #include <cstring>
5 #include <limits>
6 #include <memory>
7 #include <numeric>
8 
9 
13 
14 
15 #if defined(LIBCOPP_MACRO_USE_VALGRIND)
16 #include <valgrind/valgrind.h>
17 #endif
18 
19 #ifdef COPP_HAS_ABI_HEADERS
20 #include COPP_ABI_PREFIX
21 #endif
22 
23 namespace copp {
24  namespace allocator {
27 
28  void stack_allocator_malloc::allocate(stack_context &ctx, std::size_t size) UTIL_CONFIG_NOEXCEPT {
29  size = (std::max)(size, stack_traits::minimum_size());
30  size = (std::min)(size, stack_traits::maximum_size());
31 
32  std::size_t size_ = stack_traits::round_to_page_size(size);
33 
34  void *start_ptr = malloc(size_);
35 
36  if (!start_ptr) {
37  ctx.sp = NULL;
38  return;
39  }
40 
41  ctx.size = size_;
42  ctx.sp = static_cast<char *>(start_ptr) + ctx.size; // stack down
43 
44 #if defined(LIBCOPP_MACRO_USE_VALGRIND)
45  ctx.valgrind_stack_id = VALGRIND_STACK_REGISTER(ctx.sp, start_ptr);
46 #endif
47  }
48 
49  void stack_allocator_malloc::deallocate(stack_context &ctx) UTIL_CONFIG_NOEXCEPT {
50  assert(ctx.sp);
51  assert(stack_traits::minimum_size() <= ctx.size);
52  assert(stack_traits::is_unbounded() || (stack_traits::maximum_size() >= ctx.size));
53 
54 #if defined(LIBCOPP_MACRO_USE_VALGRIND)
55  VALGRIND_STACK_DEREGISTER(ctx.valgrind_stack_id);
56 #endif
57  void *start_ptr = static_cast<char *>(ctx.sp) - ctx.size;
58  free(start_ptr);
59  }
60  }
61 }
62 
63 #ifdef COPP_HAS_ABI_HEADERS
64 #include COPP_ABI_SUFFIX
65 #endif
void allocate(stack_context &ctx, std::size_t size) UTIL_CONFIG_NOEXCEPT
void deallocate(stack_context &ctx) UTIL_CONFIG_NOEXCEPT
static bool is_unbounded() COPP_MACRO_NOEXCEPT
static std::size_t maximum_size() COPP_MACRO_NOEXCEPT
static std::size_t minimum_size() COPP_MACRO_NOEXCEPT
static std::size_t round_to_page_size(std::size_t stacksize) COPP_MACRO_NOEXCEPT