continuation_ucontext.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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/predef.h>
  8. #if BOOST_OS_MACOS
  9. #define _XOPEN_SOURCE 600
  10. #endif
  11. extern "C" {
  12. #include <ucontext.h>
  13. }
  14. #include <boost/context/detail/config.hpp>
  15. #include <algorithm>
  16. #include <cstddef>
  17. #include <cstdint>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <functional>
  21. #include <memory>
  22. #include <ostream>
  23. #include <system_error>
  24. #include <tuple>
  25. #include <utility>
  26. #include <boost/assert.hpp>
  27. #include <boost/config.hpp>
  28. #include <boost/context/detail/disable_overload.hpp>
  29. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  30. #include <boost/context/detail/exchange.hpp>
  31. #endif
  32. #include <boost/context/detail/externc.hpp>
  33. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  34. #include <boost/context/detail/invoke.hpp>
  35. #endif
  36. #include <boost/context/fixedsize_stack.hpp>
  37. #include <boost/context/flags.hpp>
  38. #include <boost/context/preallocated.hpp>
  39. #if defined(BOOST_USE_SEGMENTED_STACKS)
  40. #include <boost/context/segmented_stack.hpp>
  41. #endif
  42. #include <boost/context/stack_context.hpp>
  43. #ifdef BOOST_HAS_ABI_HEADERS
  44. # include BOOST_ABI_PREFIX
  45. #endif
  46. namespace boost {
  47. namespace context {
  48. namespace detail {
  49. // tampoline function
  50. // entered if the execution context
  51. // is resumed for the first time
  52. template< typename Record >
  53. static void entry_func( void * data) noexcept {
  54. Record * record = static_cast< Record * >( data);
  55. BOOST_ASSERT( nullptr != record);
  56. // start execution of toplevel context-function
  57. record->run();
  58. }
  59. struct BOOST_CONTEXT_DECL activation_record {
  60. ucontext_t uctx{};
  61. stack_context sctx{};
  62. bool main_ctx{ true };
  63. activation_record * from{ nullptr };
  64. std::function< activation_record*(activation_record*&) > ontop{};
  65. bool terminated{ false };
  66. bool force_unwind{ false };
  67. #if defined(BOOST_USE_ASAN)
  68. void * fake_stack{ nullptr };
  69. void * stack_bottom{ nullptr };
  70. std::size_t stack_size{ 0 };
  71. #endif
  72. static activation_record *& current() noexcept;
  73. // used for toplevel-context
  74. // (e.g. main context, thread-entry context)
  75. activation_record() {
  76. if ( BOOST_UNLIKELY( 0 != ::getcontext( & uctx) ) ) {
  77. throw std::system_error(
  78. std::error_code( errno, std::system_category() ),
  79. "getcontext() failed");
  80. }
  81. }
  82. activation_record( stack_context sctx_) noexcept :
  83. sctx( sctx_ ),
  84. main_ctx( false ) {
  85. }
  86. virtual ~activation_record() {
  87. }
  88. activation_record( activation_record const&) = delete;
  89. activation_record & operator=( activation_record const&) = delete;
  90. bool is_main_context() const noexcept {
  91. return main_ctx;
  92. }
  93. activation_record * resume() {
  94. from = current();
  95. // store `this` in static, thread local pointer
  96. // `this` will become the active (running) context
  97. current() = this;
  98. #if defined(BOOST_USE_SEGMENTED_STACKS)
  99. // adjust segmented stack properties
  100. __splitstack_getcontext( from->sctx.segments_ctx);
  101. __splitstack_setcontext( sctx.segments_ctx);
  102. #endif
  103. #if defined(BOOST_USE_ASAN)
  104. if ( terminated) {
  105. __sanitizer_start_switch_fiber( nullptr, stack_bottom, stack_size);
  106. } else {
  107. __sanitizer_start_switch_fiber( & from->fake_stack, stack_bottom, stack_size);
  108. }
  109. #endif
  110. // context switch from parent context to `this`-context
  111. ::swapcontext( & from->uctx, & uctx);
  112. #if defined(BOOST_USE_ASAN)
  113. __sanitizer_finish_switch_fiber( current()->fake_stack,
  114. (const void **) & current()->from->stack_bottom,
  115. & current()->from->stack_size);
  116. #endif
  117. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  118. return exchange( current()->from, nullptr);
  119. #else
  120. return std::exchange( current()->from, nullptr);
  121. #endif
  122. }
  123. template< typename Ctx, typename Fn >
  124. activation_record * resume_with( Fn && fn) {
  125. from = current();
  126. // store `this` in static, thread local pointer
  127. // `this` will become the active (running) context
  128. // returned by continuation::current()
  129. current() = this;
  130. #if defined(BOOST_NO_CXX14_GENERIC_LAMBDAS)
  131. current()->ontop = std::bind(
  132. [](typename std::decay< Fn >::type & fn, activation_record *& ptr){
  133. Ctx c{ ptr };
  134. c = fn( std::move( c) );
  135. if ( ! c) {
  136. ptr = nullptr;
  137. }
  138. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  139. return exchange( c.ptr_, nullptr);
  140. #else
  141. return std::exchange( c.ptr_, nullptr);
  142. #endif
  143. },
  144. std::forward< Fn >( fn),
  145. std::placeholders::_1);
  146. #else
  147. current()->ontop = [fn=std::forward<Fn>(fn)](activation_record *& ptr){
  148. Ctx c{ ptr };
  149. c = fn( std::move( c) );
  150. if ( ! c) {
  151. ptr = nullptr;
  152. }
  153. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  154. return exchange( c.ptr_, nullptr);
  155. #else
  156. return std::exchange( c.ptr_, nullptr);
  157. #endif
  158. };
  159. #endif
  160. #if defined(BOOST_USE_SEGMENTED_STACKS)
  161. // adjust segmented stack properties
  162. __splitstack_getcontext( from->sctx.segments_ctx);
  163. __splitstack_setcontext( sctx.segments_ctx);
  164. #endif
  165. #if defined(BOOST_USE_ASAN)
  166. __sanitizer_start_switch_fiber( & from->fake_stack, stack_bottom, stack_size);
  167. #endif
  168. // context switch from parent context to `this`-context
  169. ::swapcontext( & from->uctx, & uctx);
  170. #if defined(BOOST_USE_ASAN)
  171. __sanitizer_finish_switch_fiber( current()->fake_stack,
  172. (const void **) & current()->from->stack_bottom,
  173. & current()->from->stack_size);
  174. #endif
  175. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  176. return exchange( current()->from, nullptr);
  177. #else
  178. return std::exchange( current()->from, nullptr);
  179. #endif
  180. }
  181. virtual void deallocate() noexcept {
  182. }
  183. };
  184. struct BOOST_CONTEXT_DECL activation_record_initializer {
  185. activation_record_initializer() noexcept;
  186. ~activation_record_initializer();
  187. };
  188. struct forced_unwind {
  189. activation_record * from{ nullptr };
  190. #ifndef BOOST_ASSERT_IS_VOID
  191. bool caught{ false };
  192. #endif
  193. forced_unwind( activation_record * from_) noexcept :
  194. from{ from_ } {
  195. }
  196. #ifndef BOOST_ASSERT_IS_VOID
  197. ~forced_unwind() {
  198. BOOST_ASSERT( caught);
  199. }
  200. #endif
  201. };
  202. template< typename Ctx, typename StackAlloc, typename Fn >
  203. class capture_record : public activation_record {
  204. private:
  205. typename std::decay< StackAlloc >::type salloc_;
  206. typename std::decay< Fn >::type fn_;
  207. static void destroy( capture_record * p) noexcept {
  208. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  209. stack_context sctx = p->sctx;
  210. // deallocate activation record
  211. p->~capture_record();
  212. // destroy stack with stack allocator
  213. salloc.deallocate( sctx);
  214. }
  215. public:
  216. capture_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept :
  217. activation_record{ sctx },
  218. salloc_{ std::forward< StackAlloc >( salloc) },
  219. fn_( std::forward< Fn >( fn) ) {
  220. }
  221. void deallocate() noexcept override final {
  222. BOOST_ASSERT( main_ctx || ( ! main_ctx && terminated) );
  223. destroy( this);
  224. }
  225. void run() {
  226. #if defined(BOOST_USE_ASAN)
  227. __sanitizer_finish_switch_fiber( fake_stack,
  228. (const void **) & from->stack_bottom,
  229. & from->stack_size);
  230. #endif
  231. Ctx c{ from };
  232. try {
  233. // invoke context-function
  234. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  235. c = boost::context::detail::invoke( fn_, std::move( c) );
  236. #else
  237. c = std::invoke( fn_, std::move( c) );
  238. #endif
  239. } catch ( forced_unwind const& ex) {
  240. c = Ctx{ ex.from };
  241. #ifndef BOOST_ASSERT_IS_VOID
  242. const_cast< forced_unwind & >( ex).caught = true;
  243. #endif
  244. }
  245. // this context has finished its task
  246. from = nullptr;
  247. ontop = nullptr;
  248. terminated = true;
  249. force_unwind = false;
  250. c.resume();
  251. BOOST_ASSERT_MSG( false, "continuation already terminated");
  252. }
  253. };
  254. template< typename Ctx, typename StackAlloc, typename Fn >
  255. static activation_record * create_context1( StackAlloc && salloc, Fn && fn) {
  256. typedef capture_record< Ctx, StackAlloc, Fn > capture_t;
  257. auto sctx = salloc.allocate();
  258. // reserve space for control structure
  259. void * storage = reinterpret_cast< void * >(
  260. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  261. & ~ static_cast< uintptr_t >( 0xff) );
  262. // placment new for control structure on context stack
  263. capture_t * record = new ( storage) capture_t{
  264. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  265. // stack bottom
  266. void * stack_bottom = reinterpret_cast< void * >(
  267. reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) );
  268. // create user-context
  269. if ( BOOST_UNLIKELY( 0 != ::getcontext( & record->uctx) ) ) {
  270. record->~capture_t();
  271. salloc.deallocate( sctx);
  272. throw std::system_error(
  273. std::error_code( errno, std::system_category() ),
  274. "getcontext() failed");
  275. }
  276. record->uctx.uc_stack.ss_sp = stack_bottom;
  277. // 64byte gap between control structure and stack top
  278. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  279. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  280. record->uctx.uc_link = nullptr;
  281. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  282. #if defined(BOOST_USE_ASAN)
  283. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  284. record->stack_size = record->uctx.uc_stack.ss_size;
  285. #endif
  286. return record;
  287. }
  288. template< typename Ctx, typename StackAlloc, typename Fn >
  289. static activation_record * create_context2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  290. typedef capture_record< Ctx, StackAlloc, Fn > capture_t;
  291. // reserve space for control structure
  292. void * storage = reinterpret_cast< void * >(
  293. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  294. & ~ static_cast< uintptr_t >( 0xff) );
  295. // placment new for control structure on context stack
  296. capture_t * record = new ( storage) capture_t{
  297. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  298. // stack bottom
  299. void * stack_bottom = reinterpret_cast< void * >(
  300. reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) );
  301. // create user-context
  302. if ( BOOST_UNLIKELY( 0 != ::getcontext( & record->uctx) ) ) {
  303. record->~capture_t();
  304. salloc.deallocate( palloc.sctx);
  305. throw std::system_error(
  306. std::error_code( errno, std::system_category() ),
  307. "getcontext() failed");
  308. }
  309. record->uctx.uc_stack.ss_sp = stack_bottom;
  310. // 64byte gap between control structure and stack top
  311. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  312. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  313. record->uctx.uc_link = nullptr;
  314. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  315. #if defined(BOOST_USE_ASAN)
  316. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  317. record->stack_size = record->uctx.uc_stack.ss_size;
  318. #endif
  319. return record;
  320. }
  321. }
  322. class BOOST_CONTEXT_DECL continuation {
  323. private:
  324. friend struct detail::activation_record;
  325. template< typename Ctx, typename StackAlloc, typename Fn >
  326. friend class detail::capture_record;
  327. template< typename Ctx, typename StackAlloc, typename Fn >
  328. friend detail::activation_record * detail::create_context1( StackAlloc &&, Fn &&);
  329. template< typename Ctx, typename StackAlloc, typename Fn >
  330. friend detail::activation_record * detail::create_context2( preallocated, StackAlloc &&, Fn &&);
  331. template< typename StackAlloc, typename Fn >
  332. friend continuation
  333. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  334. template< typename StackAlloc, typename Fn >
  335. friend continuation
  336. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  337. detail::activation_record * ptr_{ nullptr };
  338. continuation( detail::activation_record * ptr) noexcept :
  339. ptr_{ ptr } {
  340. }
  341. public:
  342. continuation() = default;
  343. ~continuation() {
  344. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  345. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  346. ptr_->force_unwind = true;
  347. ptr_->resume();
  348. BOOST_ASSERT( ptr_->terminated);
  349. }
  350. ptr_->deallocate();
  351. }
  352. }
  353. continuation( continuation const&) = delete;
  354. continuation & operator=( continuation const&) = delete;
  355. continuation( continuation && other) noexcept {
  356. swap( other);
  357. }
  358. continuation & operator=( continuation && other) noexcept {
  359. if ( BOOST_LIKELY( this != & other) ) {
  360. continuation tmp = std::move( other);
  361. swap( tmp);
  362. }
  363. return * this;
  364. }
  365. continuation resume() & {
  366. return std::move( * this).resume();
  367. }
  368. continuation resume() && {
  369. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  370. detail::activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  371. #else
  372. detail::activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  373. #endif
  374. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  375. throw detail::forced_unwind{ ptr};
  376. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  377. ptr = detail::activation_record::current()->ontop( ptr);
  378. detail::activation_record::current()->ontop = nullptr;
  379. }
  380. return { ptr };
  381. }
  382. template< typename Fn >
  383. continuation resume_with( Fn && fn) & {
  384. return std::move( * this).resume_with( std::forward< Fn >( fn) );
  385. }
  386. template< typename Fn >
  387. continuation resume_with( Fn && fn) && {
  388. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  389. detail::activation_record * ptr =
  390. detail::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  391. #else
  392. detail::activation_record * ptr =
  393. std::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  394. #endif
  395. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  396. throw detail::forced_unwind{ ptr};
  397. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  398. ptr = detail::activation_record::current()->ontop( ptr);
  399. detail::activation_record::current()->ontop = nullptr;
  400. }
  401. return { ptr };
  402. }
  403. explicit operator bool() const noexcept {
  404. return nullptr != ptr_ && ! ptr_->terminated;
  405. }
  406. bool operator!() const noexcept {
  407. return nullptr == ptr_ || ptr_->terminated;
  408. }
  409. bool operator<( continuation const& other) const noexcept {
  410. return ptr_ < other.ptr_;
  411. }
  412. template< typename charT, class traitsT >
  413. friend std::basic_ostream< charT, traitsT > &
  414. operator<<( std::basic_ostream< charT, traitsT > & os, continuation const& other) {
  415. if ( nullptr != other.ptr_) {
  416. return os << other.ptr_;
  417. } else {
  418. return os << "{not-a-context}";
  419. }
  420. }
  421. void swap( continuation & other) noexcept {
  422. std::swap( ptr_, other.ptr_);
  423. }
  424. };
  425. template<
  426. typename Fn,
  427. typename = detail::disable_overload< continuation, Fn >
  428. >
  429. continuation
  430. callcc( Fn && fn) {
  431. return callcc(
  432. std::allocator_arg,
  433. #if defined(BOOST_USE_SEGMENTED_STACKS)
  434. segmented_stack(),
  435. #else
  436. fixedsize_stack(),
  437. #endif
  438. std::forward< Fn >( fn) );
  439. }
  440. template< typename StackAlloc, typename Fn >
  441. continuation
  442. callcc( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) {
  443. return continuation{
  444. detail::create_context1< continuation >(
  445. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  446. }
  447. template< typename StackAlloc, typename Fn >
  448. continuation
  449. callcc( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) {
  450. return continuation{
  451. detail::create_context2< continuation >(
  452. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  453. }
  454. inline
  455. void swap( continuation & l, continuation & r) noexcept {
  456. l.swap( r);
  457. }
  458. }}
  459. #ifdef BOOST_HAS_ABI_HEADERS
  460. # include BOOST_ABI_SUFFIX
  461. #endif
  462. #endif // BOOST_CONTEXT_CONTINUATION_H