standard_stack_allocator.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright Oliver Kowalke 2009.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_COROUTINES_STANDARD_STACK_ALLOCATOR_H
  6. #define BOOST_COROUTINES_STANDARD_STACK_ALLOCATOR_H
  7. #if defined(BOOST_USE_VALGRIND)
  8. #include <valgrind/valgrind.h>
  9. #endif
  10. #include <cstddef>
  11. #include <cstdlib>
  12. #include <new>
  13. #include <boost/assert.hpp>
  14. #include <boost/config.hpp>
  15. #include <boost/coroutine/detail/config.hpp>
  16. #include <boost/coroutine/stack_context.hpp>
  17. #include <boost/coroutine/stack_traits.hpp>
  18. #if defined(BOOST_COROUTINES_USE_MAP_STACK)
  19. extern "C" {
  20. #include <sys/mman.h>
  21. }
  22. #endif
  23. #ifdef BOOST_HAS_ABI_HEADERS
  24. # include BOOST_ABI_PREFIX
  25. #endif
  26. namespace boost {
  27. namespace coroutines {
  28. template< typename traitsT >
  29. struct basic_standard_stack_allocator
  30. {
  31. typedef traitsT traits_type;
  32. void allocate( stack_context & ctx, std::size_t size = traits_type::minimum_size() )
  33. {
  34. BOOST_ASSERT( traits_type::minimum_size() <= size);
  35. BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= size) );
  36. #if defined(BOOST_COROUTINES_USE_MAP_STACK)
  37. void * limit = ::mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
  38. if ( limit == MAP_FAILED ) throw std::bad_alloc();
  39. #else
  40. void * limit = std::malloc( size);
  41. if ( ! limit) throw std::bad_alloc();
  42. #endif
  43. ctx.size = size;
  44. ctx.sp = static_cast< char * >( limit) + ctx.size;
  45. #if defined(BOOST_USE_VALGRIND)
  46. ctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( ctx.sp, limit);
  47. #endif
  48. }
  49. void deallocate( stack_context & ctx)
  50. {
  51. BOOST_ASSERT( ctx.sp);
  52. BOOST_ASSERT( traits_type::minimum_size() <= ctx.size);
  53. BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= ctx.size) );
  54. #if defined(BOOST_USE_VALGRIND)
  55. VALGRIND_STACK_DEREGISTER( ctx.valgrind_stack_id);
  56. #endif
  57. void * limit = static_cast< char * >( ctx.sp) - ctx.size;
  58. #if defined(BOOST_COROUTINES_USE_MAP_STACK)
  59. munmap(limit, ctx.size);
  60. #else
  61. std::free( limit);
  62. #endif
  63. }
  64. };
  65. typedef basic_standard_stack_allocator< stack_traits > standard_stack_allocator;
  66. }}
  67. #ifdef BOOST_HAS_ABI_HEADERS
  68. # include BOOST_ABI_SUFFIX
  69. #endif
  70. #endif // BOOST_COROUTINES_STANDARD_STACK_ALLOCATOR_H