continuation_ucontext.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. forced_unwind( activation_record * from_) noexcept :
  191. from{ from_ } {
  192. }
  193. };
  194. template< typename Ctx, typename StackAlloc, typename Fn >
  195. class capture_record : public activation_record {
  196. private:
  197. typename std::decay< StackAlloc >::type salloc_;
  198. typename std::decay< Fn >::type fn_;
  199. static void destroy( capture_record * p) noexcept {
  200. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  201. stack_context sctx = p->sctx;
  202. // deallocate activation record
  203. p->~capture_record();
  204. // destroy stack with stack allocator
  205. salloc.deallocate( sctx);
  206. }
  207. public:
  208. capture_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept :
  209. activation_record{ sctx },
  210. salloc_{ std::forward< StackAlloc >( salloc) },
  211. fn_( std::forward< Fn >( fn) ) {
  212. }
  213. void deallocate() noexcept override final {
  214. BOOST_ASSERT( main_ctx || ( ! main_ctx && terminated) );
  215. destroy( this);
  216. }
  217. void run() {
  218. #if defined(BOOST_USE_ASAN)
  219. __sanitizer_finish_switch_fiber( fake_stack,
  220. (const void **) & from->stack_bottom,
  221. & from->stack_size);
  222. #endif
  223. Ctx c{ from };
  224. try {
  225. // invoke context-function
  226. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  227. c = boost::context::detail::invoke( fn_, std::move( c) );
  228. #else
  229. c = std::invoke( fn_, std::move( c) );
  230. #endif
  231. } catch ( forced_unwind const& ex) {
  232. c = Ctx{ ex.from };
  233. }
  234. // this context has finished its task
  235. from = nullptr;
  236. ontop = nullptr;
  237. terminated = true;
  238. force_unwind = false;
  239. c.resume();
  240. BOOST_ASSERT_MSG( false, "continuation already terminated");
  241. }
  242. };
  243. template< typename Ctx, typename StackAlloc, typename Fn >
  244. static activation_record * create_context1( StackAlloc && salloc, Fn && fn) {
  245. typedef capture_record< Ctx, StackAlloc, Fn > capture_t;
  246. auto sctx = salloc.allocate();
  247. // reserve space for control structure
  248. void * storage = reinterpret_cast< void * >(
  249. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  250. & ~ static_cast< uintptr_t >( 0xff) );
  251. // placment new for control structure on context stack
  252. capture_t * record = new ( storage) capture_t{
  253. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  254. // stack bottom
  255. void * stack_bottom = reinterpret_cast< void * >(
  256. reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) );
  257. // create user-context
  258. if ( BOOST_UNLIKELY( 0 != ::getcontext( & record->uctx) ) ) {
  259. record->~capture_t();
  260. salloc.deallocate( sctx);
  261. throw std::system_error(
  262. std::error_code( errno, std::system_category() ),
  263. "getcontext() failed");
  264. }
  265. record->uctx.uc_stack.ss_sp = stack_bottom;
  266. // 64byte gap between control structure and stack top
  267. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  268. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  269. record->uctx.uc_link = nullptr;
  270. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  271. #if defined(BOOST_USE_ASAN)
  272. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  273. record->stack_size = record->uctx.uc_stack.ss_size;
  274. #endif
  275. return record;
  276. }
  277. template< typename Ctx, typename StackAlloc, typename Fn >
  278. static activation_record * create_context2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  279. typedef capture_record< Ctx, StackAlloc, Fn > capture_t;
  280. // reserve space for control structure
  281. void * storage = reinterpret_cast< void * >(
  282. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  283. & ~ static_cast< uintptr_t >( 0xff) );
  284. // placment new for control structure on context stack
  285. capture_t * record = new ( storage) capture_t{
  286. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  287. // stack bottom
  288. void * stack_bottom = reinterpret_cast< void * >(
  289. reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) );
  290. // create user-context
  291. if ( BOOST_UNLIKELY( 0 != ::getcontext( & record->uctx) ) ) {
  292. record->~capture_t();
  293. salloc.deallocate( palloc.sctx);
  294. throw std::system_error(
  295. std::error_code( errno, std::system_category() ),
  296. "getcontext() failed");
  297. }
  298. record->uctx.uc_stack.ss_sp = stack_bottom;
  299. // 64byte gap between control structure and stack top
  300. record->uctx.uc_stack.ss_size = reinterpret_cast< uintptr_t >( storage) -
  301. reinterpret_cast< uintptr_t >( stack_bottom) - static_cast< uintptr_t >( 64);
  302. record->uctx.uc_link = nullptr;
  303. ::makecontext( & record->uctx, ( void (*)() ) & entry_func< capture_t >, 1, record);
  304. #if defined(BOOST_USE_ASAN)
  305. record->stack_bottom = record->uctx.uc_stack.ss_sp;
  306. record->stack_size = record->uctx.uc_stack.ss_size;
  307. #endif
  308. return record;
  309. }
  310. }
  311. class BOOST_CONTEXT_DECL continuation {
  312. private:
  313. friend struct detail::activation_record;
  314. template< typename Ctx, typename StackAlloc, typename Fn >
  315. friend class detail::capture_record;
  316. template< typename Ctx, typename StackAlloc, typename Fn >
  317. friend detail::activation_record * detail::create_context1( StackAlloc &&, Fn &&);
  318. template< typename Ctx, typename StackAlloc, typename Fn >
  319. friend detail::activation_record * detail::create_context2( preallocated, StackAlloc &&, Fn &&);
  320. template< typename StackAlloc, typename Fn >
  321. friend continuation
  322. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  323. template< typename StackAlloc, typename Fn >
  324. friend continuation
  325. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  326. detail::activation_record * ptr_{ nullptr };
  327. continuation( detail::activation_record * ptr) noexcept :
  328. ptr_{ ptr } {
  329. }
  330. public:
  331. continuation() = default;
  332. ~continuation() {
  333. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  334. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  335. ptr_->force_unwind = true;
  336. ptr_->resume();
  337. BOOST_ASSERT( ptr_->terminated);
  338. }
  339. ptr_->deallocate();
  340. }
  341. }
  342. continuation( continuation const&) = delete;
  343. continuation & operator=( continuation const&) = delete;
  344. continuation( continuation && other) noexcept {
  345. swap( other);
  346. }
  347. continuation & operator=( continuation && other) noexcept {
  348. if ( BOOST_LIKELY( this != & other) ) {
  349. continuation tmp = std::move( other);
  350. swap( tmp);
  351. }
  352. return * this;
  353. }
  354. continuation resume() & {
  355. return std::move( * this).resume();
  356. }
  357. continuation resume() && {
  358. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  359. detail::activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  360. #else
  361. detail::activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  362. #endif
  363. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  364. throw detail::forced_unwind{ ptr};
  365. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  366. ptr = detail::activation_record::current()->ontop( ptr);
  367. detail::activation_record::current()->ontop = nullptr;
  368. }
  369. return { ptr };
  370. }
  371. template< typename Fn >
  372. continuation resume_with( Fn && fn) & {
  373. return std::move( * this).resume_with( std::forward< Fn >( fn) );
  374. }
  375. template< typename Fn >
  376. continuation resume_with( Fn && fn) && {
  377. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  378. detail::activation_record * ptr =
  379. detail::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  380. #else
  381. detail::activation_record * ptr =
  382. std::exchange( ptr_, nullptr)->resume_with< continuation >( std::forward< Fn >( fn) );
  383. #endif
  384. if ( BOOST_UNLIKELY( detail::activation_record::current()->force_unwind) ) {
  385. throw detail::forced_unwind{ ptr};
  386. } else if ( BOOST_UNLIKELY( nullptr != detail::activation_record::current()->ontop) ) {
  387. ptr = detail::activation_record::current()->ontop( ptr);
  388. detail::activation_record::current()->ontop = nullptr;
  389. }
  390. return { ptr };
  391. }
  392. explicit operator bool() const noexcept {
  393. return nullptr != ptr_ && ! ptr_->terminated;
  394. }
  395. bool operator!() const noexcept {
  396. return nullptr == ptr_ || ptr_->terminated;
  397. }
  398. bool operator<( continuation const& other) const noexcept {
  399. return ptr_ < other.ptr_;
  400. }
  401. #if !defined(BOOST_EMBTC)
  402. template< typename charT, class traitsT >
  403. friend std::basic_ostream< charT, traitsT > &
  404. operator<<( std::basic_ostream< charT, traitsT > & os, continuation const& other) {
  405. if ( nullptr != other.ptr_) {
  406. return os << other.ptr_;
  407. } else {
  408. return os << "{not-a-context}";
  409. }
  410. }
  411. #else
  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. #endif
  416. void swap( continuation & other) noexcept {
  417. std::swap( ptr_, other.ptr_);
  418. }
  419. };
  420. #if defined(BOOST_EMBTC)
  421. template< typename charT, class traitsT >
  422. inline std::basic_ostream< charT, traitsT > &
  423. operator<<( std::basic_ostream< charT, traitsT > & os, continuation const& other) {
  424. if ( nullptr != other.ptr_) {
  425. return os << other.ptr_;
  426. } else {
  427. return os << "{not-a-context}";
  428. }
  429. }
  430. #endif
  431. template<
  432. typename Fn,
  433. typename = detail::disable_overload< continuation, Fn >
  434. >
  435. continuation
  436. callcc( Fn && fn) {
  437. return callcc(
  438. std::allocator_arg,
  439. #if defined(BOOST_USE_SEGMENTED_STACKS)
  440. segmented_stack(),
  441. #else
  442. fixedsize_stack(),
  443. #endif
  444. std::forward< Fn >( fn) );
  445. }
  446. template< typename StackAlloc, typename Fn >
  447. continuation
  448. callcc( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) {
  449. return continuation{
  450. detail::create_context1< continuation >(
  451. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  452. }
  453. template< typename StackAlloc, typename Fn >
  454. continuation
  455. callcc( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) {
  456. return continuation{
  457. detail::create_context2< continuation >(
  458. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) }.resume();
  459. }
  460. inline
  461. void swap( continuation & l, continuation & r) noexcept {
  462. l.swap( r);
  463. }
  464. }}
  465. #ifdef BOOST_HAS_ABI_HEADERS
  466. # include BOOST_ABI_SUFFIX
  467. #endif
  468. #endif // BOOST_CONTEXT_CONTINUATION_H