continuation_ucontext.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. throw std::system_error(
  271. std::error_code( errno, std::system_category() ),
  272. "getcontext() failed");
  273. }
  274. record->uctx.uc_stack.ss_sp = stack_bottom;
  275. // 64byte gap between control structure and stack top
  276. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  277. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  278. record->uctx.uc_link = nullptr;
  279. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  280. #if defined(BOOST_USE_ASAN)
  281. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  282. record->stack_size = record->uctx.uc_stack.ss_size;
  283. #endif
  284. return record;
  285. }
  286. template< typename Ctx, typename StackAlloc, typename Fn >
  287. static activation_record * create_context2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  288. typedef capture_record< Ctx, StackAlloc, Fn > capture_t;
  289. // reserve space for control structure
  290. void * storage = reinterpret_cast< void * >(
  291. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  292. & ~ static_cast< uintptr_t >( 0xff) );
  293. // placment new for control structure on context stack
  294. capture_t * record = new ( storage) capture_t{
  295. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  296. // stack bottom
  297. void * stack_bottom = reinterpret_cast< void * >(
  298. reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) );
  299. // create user-context
  300. if ( BOOST_UNLIKELY( 0 != ::getcontext( & record->uctx) ) ) {
  301. throw std::system_error(
  302. std::error_code( errno, std::system_category() ),
  303. "getcontext() failed");
  304. }
  305. record->uctx.uc_stack.ss_sp = stack_bottom;
  306. // 64byte gap between control structure and stack top
  307. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  308. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  309. record->uctx.uc_link = nullptr;
  310. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  311. #if defined(BOOST_USE_ASAN)
  312. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  313. record->stack_size = record->uctx.uc_stack.ss_size;
  314. #endif
  315. return record;
  316. }
  317. }
  318. class BOOST_CONTEXT_DECL continuation {
  319. private:
  320. friend struct detail::activation_record;
  321. template< typename Ctx, typename StackAlloc, typename Fn >
  322. friend class detail::capture_record;
  323. template< typename Ctx, typename StackAlloc, typename Fn >
  324. friend detail::activation_record * detail::create_context1( StackAlloc &&, Fn &&);
  325. template< typename Ctx, typename StackAlloc, typename Fn >
  326. friend detail::activation_record * detail::create_context2( preallocated, StackAlloc &&, Fn &&);
  327. template< typename StackAlloc, typename Fn >
  328. friend continuation
  329. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  330. template< typename StackAlloc, typename Fn >
  331. friend continuation
  332. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  333. detail::activation_record * ptr_{ nullptr };
  334. continuation( detail::activation_record * ptr) noexcept :
  335. ptr_{ ptr } {
  336. }
  337. public:
  338. continuation() = default;
  339. ~continuation() {
  340. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  341. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  342. ptr_->force_unwind = true;
  343. ptr_->resume();
  344. BOOST_ASSERT( ptr_->terminated);
  345. }
  346. ptr_->deallocate();
  347. }
  348. }
  349. continuation( continuation const&) = delete;
  350. continuation & operator=( continuation const&) = delete;
  351. continuation( continuation && other) noexcept {
  352. swap( other);
  353. }
  354. continuation & operator=( continuation && other) noexcept {
  355. if ( BOOST_LIKELY( this != & other) ) {
  356. continuation tmp = std::move( other);
  357. swap( tmp);
  358. }
  359. return * this;
  360. }
  361. continuation resume() & {
  362. return std::move( * this).resume();
  363. }
  364. continuation resume() && {
  365. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  366. detail::activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  367. #else
  368. detail::activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  369. #endif
  370. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  371. throw detail::forced_unwind{ ptr};
  372. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  373. ptr = detail::activation_record::current()->ontop( ptr);
  374. detail::activation_record::current()->ontop = nullptr;
  375. }
  376. return { ptr };
  377. }
  378. template< typename Fn >
  379. continuation resume_with( Fn && fn) & {
  380. return std::move( * this).resume_with( std::forward< Fn >( fn) );
  381. }
  382. template< typename Fn >
  383. continuation resume_with( Fn && fn) && {
  384. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  385. detail::activation_record * ptr =
  386. detail::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  387. #else
  388. detail::activation_record * ptr =
  389. std::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  390. #endif
  391. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  392. throw detail::forced_unwind{ ptr};
  393. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  394. ptr = detail::activation_record::current()->ontop( ptr);
  395. detail::activation_record::current()->ontop = nullptr;
  396. }
  397. return { ptr };
  398. }
  399. explicit operator bool() const noexcept {
  400. return nullptr != ptr_ && ! ptr_->terminated;
  401. }
  402. bool operator!() const noexcept {
  403. return nullptr == ptr_ || ptr_->terminated;
  404. }
  405. bool operator<( continuation const& other) const noexcept {
  406. return ptr_ < other.ptr_;
  407. }
  408. template< typename charT, class traitsT >
  409. friend std::basic_ostream< charT, traitsT > &
  410. operator<<( std::basic_ostream< charT, traitsT > & os, continuation const& other) {
  411. if ( nullptr != other.ptr_) {
  412. return os << other.ptr_;
  413. } else {
  414. return os << "{not-a-context}";
  415. }
  416. }
  417. void swap( continuation & other) noexcept {
  418. std::swap( ptr_, other.ptr_);
  419. }
  420. };
  421. template<
  422. typename Fn,
  423. typename = detail::disable_overload< continuation, Fn >
  424. >
  425. continuation
  426. callcc( Fn && fn) {
  427. return callcc(
  428. std::allocator_arg,
  429. #if defined(BOOST_USE_SEGMENTED_STACKS)
  430. segmented_stack(),
  431. #else
  432. fixedsize_stack(),
  433. #endif
  434. std::forward< Fn >( fn) );
  435. }
  436. template< typename StackAlloc, typename Fn >
  437. continuation
  438. callcc( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) {
  439. return continuation{
  440. detail::create_context1< continuation >(
  441. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  442. }
  443. template< typename StackAlloc, typename Fn >
  444. continuation
  445. callcc( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) {
  446. return continuation{
  447. detail::create_context2< continuation >(
  448. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  449. }
  450. inline
  451. void swap( continuation & l, continuation & r) noexcept {
  452. l.swap( r);
  453. }
  454. }}
  455. #ifdef BOOST_HAS_ABI_HEADERS
  456. # include BOOST_ABI_SUFFIX
  457. #endif
  458. #endif // BOOST_CONTEXT_CONTINUATION_H