File indexing completed on 2025-09-16 08:30:26
0001
0002
0003
0004
0005
0006
0007 #ifndef BOOST_COROUTINES_PROTECTED_STACK_ALLOCATOR_H
0008 #define BOOST_COROUTINES_PROTECTED_STACK_ALLOCATOR_H
0009
0010 extern "C" {
0011 #include <fcntl.h>
0012 #include <sys/mman.h>
0013 #include <sys/stat.h>
0014 #include <unistd.h>
0015 }
0016
0017 #if defined(BOOST_USE_VALGRIND)
0018 #include <valgrind/valgrind.h>
0019 #endif
0020
0021 #include <cmath>
0022 #include <cstddef>
0023 #include <new>
0024
0025 #include <boost/assert.hpp>
0026 #include <boost/config.hpp>
0027
0028 #include <boost/coroutine/detail/config.hpp>
0029 #include <boost/coroutine/stack_context.hpp>
0030 #include <boost/coroutine/stack_traits.hpp>
0031
0032 #ifdef BOOST_HAS_ABI_HEADERS
0033 # include BOOST_ABI_PREFIX
0034 #endif
0035
0036 namespace boost {
0037 namespace coroutines {
0038
0039 template< typename traitsT >
0040 struct basic_protected_stack_allocator
0041 {
0042 typedef traitsT traits_type;
0043
0044 void allocate( stack_context & ctx, std::size_t size = traits_type::minimum_size() )
0045 {
0046 BOOST_ASSERT( traits_type::minimum_size() <= size);
0047 BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= size) );
0048
0049
0050 const std::size_t pages(
0051 static_cast< std::size_t >(
0052 std::floor(
0053 static_cast< float >( size) / traits_type::page_size() ) ) );
0054 BOOST_ASSERT_MSG( 2 <= pages, "at least two pages must fit into stack (one page is guard-page)");
0055 const std::size_t size_( pages * traits_type::page_size() );
0056 BOOST_ASSERT( 0 != size && 0 != size_);
0057 BOOST_ASSERT( size_ <= size);
0058
0059
0060 #if defined(MAP_ANON)
0061 void * limit = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
0062 #else
0063 void * limit = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
0064 #endif
0065 if ( MAP_FAILED == limit) throw std::bad_alloc();
0066
0067
0068 BOOST_VERIFY( 0 == ::mprotect( limit, traits_type::page_size(), PROT_NONE));
0069
0070 ctx.size = size_;
0071 ctx.sp = static_cast< char * >( limit) + ctx.size;
0072 #if defined(BOOST_USE_VALGRIND)
0073 ctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( ctx.sp, limit);
0074 #endif
0075 }
0076
0077 void deallocate( stack_context & ctx)
0078 {
0079 BOOST_ASSERT( ctx.sp);
0080 BOOST_ASSERT( traits_type::minimum_size() <= ctx.size);
0081 BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= ctx.size) );
0082
0083 #if defined(BOOST_USE_VALGRIND)
0084 VALGRIND_STACK_DEREGISTER( ctx.valgrind_stack_id);
0085 #endif
0086 void * limit = static_cast< char * >( ctx.sp) - ctx.size;
0087
0088 ::munmap( limit, ctx.size);
0089 }
0090 };
0091
0092 typedef basic_protected_stack_allocator< stack_traits > protected_stack_allocator;
0093
0094 }}
0095
0096 #ifdef BOOST_HAS_ABI_HEADERS
0097 # include BOOST_ABI_SUFFIX
0098 #endif
0099
0100 #endif