continuation_fcontext.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Copyright Oliver Kowalke 2017.
  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_CONTINUATION_H
  6. #define BOOST_CONTEXT_CONTINUATION_H
  7. #include <boost/context/detail/config.hpp>
  8. #include <algorithm>
  9. #include <cstddef>
  10. #include <cstdint>
  11. #include <cstdlib>
  12. #include <exception>
  13. #include <functional>
  14. #include <memory>
  15. #include <ostream>
  16. #include <tuple>
  17. #include <utility>
  18. #include <boost/assert.hpp>
  19. #include <boost/config.hpp>
  20. #include <boost/intrusive_ptr.hpp>
  21. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  22. #include <boost/context/detail/exchange.hpp>
  23. #endif
  24. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  25. #include <boost/context/detail/invoke.hpp>
  26. #endif
  27. #include <boost/context/detail/disable_overload.hpp>
  28. #include <boost/context/detail/exception.hpp>
  29. #include <boost/context/detail/fcontext.hpp>
  30. #include <boost/context/detail/tuple.hpp>
  31. #include <boost/context/fixedsize_stack.hpp>
  32. #include <boost/context/flags.hpp>
  33. #include <boost/context/preallocated.hpp>
  34. #include <boost/context/segmented_stack.hpp>
  35. #include <boost/context/stack_context.hpp>
  36. #ifdef BOOST_HAS_ABI_HEADERS
  37. # include BOOST_ABI_PREFIX
  38. #endif
  39. #if defined(__CET__) && defined(__unix__)
  40. # include <cet.h>
  41. # include <sys/mman.h>
  42. # define SHSTK_ENABLED (__CET__ & 0x2)
  43. # define BOOST_CONTEXT_SHADOW_STACK (SHSTK_ENABLED && SHADOW_STACK_SYSCALL)
  44. # define __NR_map_shadow_stack 451
  45. #ifndef SHADOW_STACK_SET_TOKEN
  46. # define SHADOW_STACK_SET_TOKEN 0x1
  47. #endif
  48. #endif
  49. #if defined(BOOST_MSVC)
  50. # pragma warning(push)
  51. # pragma warning(disable: 4702)
  52. #endif
  53. namespace boost {
  54. namespace context {
  55. namespace detail {
  56. inline
  57. transfer_t context_unwind( transfer_t t) {
  58. throw forced_unwind( t.fctx);
  59. return { nullptr, nullptr };
  60. }
  61. template< typename Rec >
  62. transfer_t context_exit( transfer_t t) noexcept {
  63. Rec * rec = static_cast< Rec * >( t.data);
  64. #if BOOST_CONTEXT_SHADOW_STACK
  65. // destory shadow stack
  66. std::size_t ss_size = *((unsigned long*)(reinterpret_cast< uintptr_t >( rec)- 16));
  67. long unsigned int ss_base = *((unsigned long*)(reinterpret_cast< uintptr_t >( rec)- 8));
  68. munmap((void *)ss_base, ss_size);
  69. #endif
  70. // destroy context stack
  71. rec->deallocate();
  72. return { nullptr, nullptr };
  73. }
  74. template< typename Rec >
  75. void context_entry( transfer_t t) noexcept {
  76. // transfer control structure to the context-stack
  77. Rec * rec = static_cast< Rec * >( t.data);
  78. BOOST_ASSERT( nullptr != t.fctx);
  79. BOOST_ASSERT( nullptr != rec);
  80. try {
  81. // jump back to `create_context()`
  82. t = jump_fcontext( t.fctx, nullptr);
  83. // start executing
  84. t.fctx = rec->run( t.fctx);
  85. } catch ( forced_unwind const& ex) {
  86. t = { ex.fctx, nullptr };
  87. }
  88. BOOST_ASSERT( nullptr != t.fctx);
  89. // destroy context-stack of `this`context on next context
  90. ontop_fcontext( t.fctx, rec, context_exit< Rec >);
  91. BOOST_ASSERT_MSG( false, "context already terminated");
  92. }
  93. template< typename Ctx, typename Fn >
  94. transfer_t context_ontop( transfer_t t) {
  95. auto p = static_cast< std::tuple< Fn > * >( t.data);
  96. BOOST_ASSERT( nullptr != p);
  97. typename std::decay< Fn >::type fn = std::get< 0 >( * p);
  98. t.data = nullptr;
  99. Ctx c{ t.fctx };
  100. // execute function, pass continuation via reference
  101. c = fn( std::move( c) );
  102. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  103. return { exchange( c.fctx_, nullptr), nullptr };
  104. #else
  105. return { std::exchange( c.fctx_, nullptr), nullptr };
  106. #endif
  107. }
  108. template< typename Ctx, typename StackAlloc, typename Fn >
  109. class record {
  110. private:
  111. stack_context sctx_;
  112. typename std::decay< StackAlloc >::type salloc_;
  113. typename std::decay< Fn >::type fn_;
  114. static void destroy( record * p) noexcept {
  115. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  116. stack_context sctx = p->sctx_;
  117. // deallocate record
  118. p->~record();
  119. // destroy stack with stack allocator
  120. salloc.deallocate( sctx);
  121. }
  122. public:
  123. record( stack_context sctx, StackAlloc && salloc,
  124. Fn && fn) noexcept :
  125. sctx_( sctx),
  126. salloc_( std::forward< StackAlloc >( salloc)),
  127. fn_( std::forward< Fn >( fn) ) {
  128. }
  129. record( record const&) = delete;
  130. record & operator=( record const&) = delete;
  131. void deallocate() noexcept {
  132. destroy( this);
  133. }
  134. fcontext_t run( fcontext_t fctx) {
  135. Ctx c{ fctx };
  136. // invoke context-function
  137. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  138. c = boost::context::detail::invoke( fn_, std::move( c) );
  139. #else
  140. c = std::invoke( fn_, std::move( c) );
  141. #endif
  142. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  143. return exchange( c.fctx_, nullptr);
  144. #else
  145. return std::exchange( c.fctx_, nullptr);
  146. #endif
  147. }
  148. };
  149. template< typename Record, typename StackAlloc, typename Fn >
  150. fcontext_t create_context1( StackAlloc && salloc, Fn && fn) {
  151. auto sctx = salloc.allocate();
  152. // reserve space for control structure
  153. void * storage = reinterpret_cast< void * >(
  154. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( Record) ) )
  155. & ~static_cast< uintptr_t >( 0xff) );
  156. // placment new for control structure on context stack
  157. Record * record = new ( storage) Record{
  158. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  159. // 64byte gab between control structure and stack top
  160. // should be 16byte aligned
  161. void * stack_top = reinterpret_cast< void * >(
  162. reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) );
  163. void * stack_bottom = reinterpret_cast< void * >(
  164. reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) );
  165. // create fast-context
  166. const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom);
  167. #if BOOST_CONTEXT_SHADOW_STACK
  168. std::size_t ss_size = size >> 5;
  169. // align shadow stack to 8 bytes.
  170. ss_size = (ss_size + 7) & ~7;
  171. // Todo: shadow stack occupies at least 4KB
  172. ss_size = (ss_size > 4096) ? size : 4096;
  173. // create shadow stack
  174. void *ss_base = (void *)syscall(__NR_map_shadow_stack, 0, ss_size, SHADOW_STACK_SET_TOKEN);
  175. BOOST_ASSERT(ss_base != -1);
  176. unsigned long ss_sp = (unsigned long)ss_base + ss_size;
  177. /* pass the shadow stack pointer to make_fcontext
  178. i.e., link the new shadow stack with the new fcontext
  179. TODO should be a better way? */
  180. *((unsigned long*)(reinterpret_cast< uintptr_t >( stack_top)- 8)) = ss_sp;
  181. /* Todo: place shadow stack info in 64byte gap */
  182. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 8)) = (unsigned long) ss_base;
  183. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 16)) = ss_size;
  184. #endif
  185. const fcontext_t fctx = make_fcontext( stack_top, size, & context_entry< Record >);
  186. BOOST_ASSERT( nullptr != fctx);
  187. // transfer control structure to context-stack
  188. return jump_fcontext( fctx, record).fctx;
  189. }
  190. template< typename Record, typename StackAlloc, typename Fn >
  191. fcontext_t create_context2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  192. // reserve space for control structure
  193. void * storage = reinterpret_cast< void * >(
  194. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( Record) ) )
  195. & ~ static_cast< uintptr_t >( 0xff) );
  196. // placment new for control structure on context-stack
  197. Record * record = new ( storage) Record{
  198. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  199. // 64byte gab between control structure and stack top
  200. void * stack_top = reinterpret_cast< void * >(
  201. reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) );
  202. void * stack_bottom = reinterpret_cast< void * >(
  203. reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) );
  204. // create fast-context
  205. const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom);
  206. #if BOOST_CONTEXT_SHADOW_STACK
  207. std::size_t ss_size = size >> 5;
  208. // align shadow stack to 8 bytes.
  209. ss_size = (ss_size + 7) & ~7;
  210. // Todo: shadow stack occupies at least 4KB
  211. ss_size = (ss_size > 4096) ? size : 4096;
  212. // create shadow stack
  213. void *ss_base = (void *)syscall(__NR_map_shadow_stack, 0, ss_size, SHADOW_STACK_SET_TOKEN);
  214. BOOST_ASSERT(ss_base != -1);
  215. unsigned long ss_sp = (unsigned long)ss_base + ss_size;
  216. /* pass the shadow stack pointer to make_fcontext
  217. i.e., link the new shadow stack with the new fcontext
  218. TODO should be a better way? */
  219. *((unsigned long*)(reinterpret_cast< uintptr_t >( stack_top)- 8)) = ss_sp;
  220. /* Todo: place shadow stack info in 64byte gap */
  221. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 8)) = (unsigned long) ss_base;
  222. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 16)) = ss_size;
  223. #endif
  224. const fcontext_t fctx = make_fcontext( stack_top, size, & context_entry< Record >);
  225. BOOST_ASSERT( nullptr != fctx);
  226. // transfer control structure to context-stack
  227. return jump_fcontext( fctx, record).fctx;
  228. }
  229. }
  230. class continuation {
  231. private:
  232. template< typename Ctx, typename StackAlloc, typename Fn >
  233. friend class detail::record;
  234. template< typename Ctx, typename Fn >
  235. friend detail::transfer_t
  236. detail::context_ontop( detail::transfer_t);
  237. template< typename StackAlloc, typename Fn >
  238. friend continuation
  239. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  240. template< typename StackAlloc, typename Fn >
  241. friend continuation
  242. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  243. detail::fcontext_t fctx_{ nullptr };
  244. continuation( detail::fcontext_t fctx) noexcept :
  245. fctx_{ fctx } {
  246. }
  247. public:
  248. continuation() noexcept = default;
  249. ~continuation() {
  250. if ( BOOST_UNLIKELY( nullptr != fctx_) ) {
  251. detail::ontop_fcontext(
  252. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  253. detail::exchange( fctx_, nullptr),
  254. #else
  255. std::exchange( fctx_, nullptr),
  256. #endif
  257. nullptr,
  258. detail::context_unwind);
  259. }
  260. }
  261. continuation( continuation && other) noexcept {
  262. swap( other);
  263. }
  264. continuation & operator=( continuation && other) noexcept {
  265. if ( BOOST_LIKELY( this != & other) ) {
  266. continuation tmp = std::move( other);
  267. swap( tmp);
  268. }
  269. return * this;
  270. }
  271. continuation( continuation const& other) noexcept = delete;
  272. continuation & operator=( continuation const& other) noexcept = delete;
  273. continuation resume() & {
  274. return std::move( * this).resume();
  275. }
  276. continuation resume() && {
  277. BOOST_ASSERT( nullptr != fctx_);
  278. return { detail::jump_fcontext(
  279. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  280. detail::exchange( fctx_, nullptr),
  281. #else
  282. std::exchange( fctx_, nullptr),
  283. #endif
  284. nullptr).fctx };
  285. }
  286. template< typename Fn >
  287. continuation resume_with( Fn && fn) & {
  288. return std::move( * this).resume_with( std::forward< Fn >( fn) );
  289. }
  290. template< typename Fn >
  291. continuation resume_with( Fn && fn) && {
  292. BOOST_ASSERT( nullptr != fctx_);
  293. auto p = std::make_tuple( std::forward< Fn >( fn) );
  294. return { detail::ontop_fcontext(
  295. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  296. detail::exchange( fctx_, nullptr),
  297. #else
  298. std::exchange( fctx_, nullptr),
  299. #endif
  300. & p,
  301. detail::context_ontop< continuation, Fn >).fctx };
  302. }
  303. explicit operator bool() const noexcept {
  304. return nullptr != fctx_;
  305. }
  306. bool operator!() const noexcept {
  307. return nullptr == fctx_;
  308. }
  309. bool operator<( continuation const& other) const noexcept {
  310. return fctx_ < other.fctx_;
  311. }
  312. template< typename charT, class traitsT >
  313. friend std::basic_ostream< charT, traitsT > &
  314. operator<<( std::basic_ostream< charT, traitsT > & os, continuation const& other) {
  315. if ( nullptr != other.fctx_) {
  316. return os << other.fctx_;
  317. } else {
  318. return os << "{not-a-context}";
  319. }
  320. }
  321. void swap( continuation & other) noexcept {
  322. std::swap( fctx_, other.fctx_);
  323. }
  324. };
  325. template<
  326. typename Fn,
  327. typename = detail::disable_overload< continuation, Fn >
  328. >
  329. continuation
  330. callcc( Fn && fn) {
  331. return callcc(
  332. std::allocator_arg, fixedsize_stack(),
  333. std::forward< Fn >( fn) );
  334. }
  335. template< typename StackAlloc, typename Fn >
  336. continuation
  337. callcc( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) {
  338. using Record = detail::record< continuation, StackAlloc, Fn >;
  339. return continuation{
  340. detail::create_context1< Record >(
  341. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  342. }
  343. template< typename StackAlloc, typename Fn >
  344. continuation
  345. callcc( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) {
  346. using Record = detail::record< continuation, StackAlloc, Fn >;
  347. return continuation{
  348. detail::create_context2< Record >(
  349. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  350. }
  351. #if defined(BOOST_USE_SEGMENTED_STACKS)
  352. template< typename Fn >
  353. continuation
  354. callcc( std::allocator_arg_t, segmented_stack, Fn &&);
  355. template< typename StackAlloc, typename Fn >
  356. continuation
  357. callcc( std::allocator_arg_t, preallocated, segmented_stack, Fn &&);
  358. #endif
  359. inline
  360. void swap( continuation & l, continuation & r) noexcept {
  361. l.swap( r);
  362. }
  363. }}
  364. #if defined(BOOST_MSVC)
  365. # pragma warning(pop)
  366. #endif
  367. #ifdef BOOST_HAS_ABI_HEADERS
  368. # include BOOST_ABI_SUFFIX
  369. #endif
  370. #endif // BOOST_CONTEXT_CONTINUATION_H