continuation_ucontext.hpp 18 KB

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