Skip to content

Commit f7a3405

Browse files
committed
Use mmap(2) MAP_STACK to allocate stacks on OpenBSD
Since OpenBSD 6.4 (https://www.openbsd.org/64.html), the stack pointer must point to MAP_STACK memory, or the kernel may kill the process with a signal. All stack allocators must pass MAP_STACK to mmap(2). I took inspiration from boostorg/context@7e14ab9 for this diff.
1 parent 3537b31 commit f7a3405

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

include/boost/coroutine/detail/config.hpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,9 @@
3838
#define BOOST_COROUTINES_UNIDIRECT
3939
#define BOOST_COROUTINES_SYMMETRIC
4040

41+
#if defined(__OpenBSD__)
42+
// stacks need mmap(2) with MAP_STACK
43+
# define BOOST_COROUTINES_USE_MAP_STACK
44+
#endif
45+
4146
#endif // BOOST_COROUTINES_DETAIL_CONFIG_H

include/boost/coroutine/standard_stack_allocator.hpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@
2222
#include <boost/coroutine/stack_context.hpp>
2323
#include <boost/coroutine/stack_traits.hpp>
2424

25+
#if defined(BOOST_COROUTINES_USE_MAP_STACK)
26+
extern "C" {
27+
#include <sys/mman.h>
28+
}
29+
#endif
30+
2531
#ifdef BOOST_HAS_ABI_HEADERS
2632
# include BOOST_ABI_PREFIX
2733
#endif
@@ -39,8 +45,13 @@ struct basic_standard_stack_allocator
3945
BOOST_ASSERT( traits_type::minimum_size() <= size);
4046
BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= size) );
4147

48+
#if defined(BOOST_COROUTINES_USE_MAP_STACK)
49+
void * limit = ::mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
50+
if ( limit == MAP_FAILED ) throw std::bad_alloc();
51+
#else
4252
void * limit = std::malloc( size);
4353
if ( ! limit) throw std::bad_alloc();
54+
#endif
4455

4556
ctx.size = size;
4657
ctx.sp = static_cast< char * >( limit) + ctx.size;
@@ -60,7 +71,11 @@ struct basic_standard_stack_allocator
6071
#endif
6172

6273
void * limit = static_cast< char * >( ctx.sp) - ctx.size;
74+
#if defined(BOOST_COROUTINES_USE_MAP_STACK)
75+
munmap(limit, ctx.size);
76+
#else
6377
std::free( limit);
78+
#endif
6479
}
6580
};
6681

0 commit comments

Comments
 (0)