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