fixedsize_stack.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright Oliver Kowalke 2014.
  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_CONTEXT_FIXEDSIZE_H
  6. #define BOOST_CONTEXT_FIXEDSIZE_H
  7. #include <cstddef>
  8. #include <cstdlib>
  9. #include <new>
  10. #include <boost/assert.hpp>
  11. #include <boost/config.hpp>
  12. #include <boost/context/detail/config.hpp>
  13. #include <boost/context/stack_context.hpp>
  14. #include <boost/context/stack_traits.hpp>
  15. #if defined(BOOST_CONTEXT_USE_MAP_STACK)
  16. extern "C" {
  17. #include <sys/mman.h>
  18. }
  19. #endif
  20. #if defined(BOOST_USE_VALGRIND)
  21. #include <valgrind/valgrind.h>
  22. #endif
  23. #ifdef BOOST_HAS_ABI_HEADERS
  24. # include BOOST_ABI_PREFIX
  25. #endif
  26. namespace boost {
  27. namespace context {
  28. template< typename traitsT >
  29. class basic_fixedsize_stack {
  30. private:
  31. std::size_t size_;
  32. public:
  33. typedef traitsT traits_type;
  34. basic_fixedsize_stack( std::size_t size = traits_type::default_size() ) BOOST_NOEXCEPT_OR_NOTHROW :
  35. size_( size) {
  36. }
  37. stack_context allocate() {
  38. #if defined(BOOST_CONTEXT_USE_MAP_STACK)
  39. void * vp = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
  40. if ( vp == MAP_FAILED) {
  41. throw std::bad_alloc();
  42. }
  43. #else
  44. void * vp = std::malloc( size_);
  45. if ( ! vp) {
  46. throw std::bad_alloc();
  47. }
  48. #endif
  49. stack_context sctx;
  50. sctx.size = size_;
  51. sctx.sp = static_cast< char * >( vp) + sctx.size;
  52. #if defined(BOOST_USE_VALGRIND)
  53. sctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( sctx.sp, vp);
  54. #endif
  55. return sctx;
  56. }
  57. void deallocate( stack_context & sctx) BOOST_NOEXCEPT_OR_NOTHROW {
  58. BOOST_ASSERT( sctx.sp);
  59. #if defined(BOOST_USE_VALGRIND)
  60. VALGRIND_STACK_DEREGISTER( sctx.valgrind_stack_id);
  61. #endif
  62. void * vp = static_cast< char * >( sctx.sp) - sctx.size;
  63. #if defined(BOOST_CONTEXT_USE_MAP_STACK)
  64. ::munmap( vp, sctx.size);
  65. #else
  66. std::free( vp);
  67. #endif
  68. }
  69. };
  70. typedef basic_fixedsize_stack< stack_traits > fixedsize_stack;
  71. # if ! defined(BOOST_USE_SEGMENTED_STACKS)
  72. typedef fixedsize_stack default_stack;
  73. # endif
  74. }}
  75. #ifdef BOOST_HAS_ABI_HEADERS
  76. # include BOOST_ABI_SUFFIX
  77. #endif
  78. #endif // BOOST_CONTEXT_FIXEDSIZE_H