2 // Copyright Oliver Kowalke 2009.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef BOOST_COROUTINES_PROTECTED_STACK_ALLOCATOR_H
8 #define BOOST_COROUTINES_PROTECTED_STACK_ALLOCATOR_H
17 #if defined(BOOST_USE_VALGRIND)
18 #include <valgrind/valgrind.h>
25 #include <boost/assert.hpp>
26 #include <boost/config.hpp>
28 #include <boost/coroutine/detail/config.hpp>
29 #include <boost/coroutine/stack_context.hpp>
30 #include <boost/coroutine/stack_traits.hpp>
32 #ifdef BOOST_HAS_ABI_HEADERS
33 # include BOOST_ABI_PREFIX
37 namespace coroutines {
39 template< typename traitsT >
40 struct basic_protected_stack_allocator
42 typedef traitsT traits_type;
44 void allocate( stack_context & ctx, std::size_t size = traits_type::minimum_size() )
46 BOOST_ASSERT( traits_type::minimum_size() <= size);
47 BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= size) );
49 // page at bottom will be used as guard-page
50 const std::size_t pages(
51 static_cast< std::size_t >(
53 static_cast< float >( size) / traits_type::page_size() ) ) );
54 BOOST_ASSERT_MSG( 2 <= pages, "at least two pages must fit into stack (one page is guard-page)");
55 const std::size_t size_( pages * traits_type::page_size() );
56 BOOST_ASSERT( 0 != size && 0 != size_);
57 BOOST_ASSERT( size_ <= size);
59 // conform to POSIX.4 (POSIX.1b-1993, _POSIX_C_SOURCE=199309L)
61 void * limit = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
63 void * limit = ::mmap( 0, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
65 if ( MAP_FAILED == limit) throw std::bad_alloc();
67 // conforming to POSIX.1-2001
68 #if defined(BOOST_DISABLE_ASSERTS)
69 ::mprotect( limit, traits_type::page_size(), PROT_NONE);
71 const int result( ::mprotect( limit, traits_type::page_size(), PROT_NONE) );
72 BOOST_ASSERT( 0 == result);
76 ctx.sp = static_cast< char * >( limit) + ctx.size;
77 #if defined(BOOST_USE_VALGRIND)
78 ctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( ctx.sp, limit);
82 void deallocate( stack_context & ctx)
84 BOOST_ASSERT( ctx.sp);
85 BOOST_ASSERT( traits_type::minimum_size() <= ctx.size);
86 BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= ctx.size) );
88 #if defined(BOOST_USE_VALGRIND)
89 VALGRIND_STACK_DEREGISTER( ctx.valgrind_stack_id);
91 void * limit = static_cast< char * >( ctx.sp) - ctx.size;
92 // conform to POSIX.4 (POSIX.1b-1993, _POSIX_C_SOURCE=199309L)
93 ::munmap( limit, ctx.size);
97 typedef basic_protected_stack_allocator< stack_traits > protected_stack_allocator;
101 #ifdef BOOST_HAS_ABI_HEADERS
102 # include BOOST_ABI_SUFFIX
105 #endif // BOOST_COROUTINES_PROTECTED_STACK_ALLOCATOR_H