fiber_ucontext.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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_FIBER_H
  6. #define BOOST_CONTEXT_FIBER_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 fiber_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 fiber_activation_record {
  60. ucontext_t uctx{};
  61. stack_context sctx{};
  62. bool main_ctx{ true };
  63. fiber_activation_record * from{ nullptr };
  64. std::function< fiber_activation_record*(fiber_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 fiber_activation_record *& current() noexcept;
  73. // used for toplevel-context
  74. // (e.g. main context, thread-entry context)
  75. fiber_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. fiber_activation_record( stack_context sctx_) noexcept :
  83. sctx( sctx_ ),
  84. main_ctx( false ) {
  85. }
  86. virtual ~fiber_activation_record() {
  87. }
  88. fiber_activation_record( fiber_activation_record const&) = delete;
  89. fiber_activation_record & operator=( fiber_activation_record const&) = delete;
  90. bool is_main_context() const noexcept {
  91. return main_ctx;
  92. }
  93. fiber_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. fiber_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 fiber::current()
  129. current() = this;
  130. #if defined(BOOST_NO_CXX14_GENERIC_LAMBDAS)
  131. current()->ontop = std::bind(
  132. [](typename std::decay< Fn >::type & fn, fiber_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)](fiber_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 fiber_activation_record_initializer {
  185. fiber_activation_record_initializer() noexcept;
  186. ~fiber_activation_record_initializer();
  187. };
  188. struct forced_unwind {
  189. fiber_activation_record * from{ nullptr };
  190. #ifndef BOOST_ASSERT_IS_VOID
  191. bool caught{ false };
  192. #endif
  193. forced_unwind( fiber_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 fiber_capture_record : public fiber_activation_record {
  204. private:
  205. typename std::decay< StackAlloc >::type salloc_;
  206. typename std::decay< Fn >::type fn_;
  207. static void destroy( fiber_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->~fiber_capture_record();
  212. // destroy stack with stack allocator
  213. salloc.deallocate( sctx);
  214. }
  215. public:
  216. fiber_capture_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept :
  217. fiber_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. std::move( c).resume();
  251. BOOST_ASSERT_MSG( false, "fiber already terminated");
  252. }
  253. };
  254. template< typename Ctx, typename StackAlloc, typename Fn >
  255. static fiber_activation_record * create_fiber1( StackAlloc && salloc, Fn && fn) {
  256. typedef fiber_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 (*)() ) & fiber_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 fiber_activation_record * create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  290. typedef fiber_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 (*)() ) & fiber_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 fiber {
  323. private:
  324. friend struct detail::fiber_activation_record;
  325. template< typename Ctx, typename StackAlloc, typename Fn >
  326. friend class detail::fiber_capture_record;
  327. template< typename Ctx, typename StackAlloc, typename Fn >
  328. friend detail::fiber_activation_record * detail::create_fiber1( StackAlloc &&, Fn &&);
  329. template< typename Ctx, typename StackAlloc, typename Fn >
  330. friend detail::fiber_activation_record * detail::create_fiber2( preallocated, StackAlloc &&, Fn &&);
  331. template< typename StackAlloc, typename Fn >
  332. friend fiber
  333. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  334. template< typename StackAlloc, typename Fn >
  335. friend fiber
  336. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  337. detail::fiber_activation_record * ptr_{ nullptr };
  338. fiber( detail::fiber_activation_record * ptr) noexcept :
  339. ptr_{ ptr } {
  340. }
  341. public:
  342. fiber() = default;
  343. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  344. fiber( Fn && fn) :
  345. fiber{
  346. std::allocator_arg,
  347. #if defined(BOOST_USE_SEGMENTED_STACKS)
  348. segmented_stack(),
  349. #else
  350. fixedsize_stack(),
  351. #endif
  352. std::forward< Fn >( fn) } {
  353. }
  354. template< typename StackAlloc, typename Fn >
  355. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  356. ptr_{ detail::create_fiber1< fiber >(
  357. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  358. }
  359. template< typename StackAlloc, typename Fn >
  360. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  361. ptr_{ detail::create_fiber2< fiber >(
  362. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  363. }
  364. ~fiber() {
  365. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  366. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  367. ptr_->force_unwind = true;
  368. ptr_->resume();
  369. BOOST_ASSERT( ptr_->terminated);
  370. }
  371. ptr_->deallocate();
  372. }
  373. }
  374. fiber( fiber const&) = delete;
  375. fiber & operator=( fiber const&) = delete;
  376. fiber( fiber && other) noexcept {
  377. swap( other);
  378. }
  379. fiber & operator=( fiber && other) noexcept {
  380. if ( BOOST_LIKELY( this != & other) ) {
  381. fiber tmp = std::move( other);
  382. swap( tmp);
  383. }
  384. return * this;
  385. }
  386. fiber resume() && {
  387. BOOST_ASSERT( nullptr != ptr_);
  388. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  389. detail::fiber_activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  390. #else
  391. detail::fiber_activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  392. #endif
  393. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  394. throw detail::forced_unwind{ ptr};
  395. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  396. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  397. detail::fiber_activation_record::current()->ontop = nullptr;
  398. }
  399. return { ptr };
  400. }
  401. template< typename Fn >
  402. fiber resume_with( Fn && fn) && {
  403. BOOST_ASSERT( nullptr != ptr_);
  404. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  405. detail::fiber_activation_record * ptr =
  406. detail::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  407. #else
  408. detail::fiber_activation_record * ptr =
  409. std::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  410. #endif
  411. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  412. throw detail::forced_unwind{ ptr};
  413. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  414. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  415. detail::fiber_activation_record::current()->ontop = nullptr;
  416. }
  417. return { ptr };
  418. }
  419. explicit operator bool() const noexcept {
  420. return nullptr != ptr_ && ! ptr_->terminated;
  421. }
  422. bool operator!() const noexcept {
  423. return nullptr == ptr_ || ptr_->terminated;
  424. }
  425. bool operator<( fiber const& other) const noexcept {
  426. return ptr_ < other.ptr_;
  427. }
  428. template< typename charT, class traitsT >
  429. friend std::basic_ostream< charT, traitsT > &
  430. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  431. if ( nullptr != other.ptr_) {
  432. return os << other.ptr_;
  433. } else {
  434. return os << "{not-a-context}";
  435. }
  436. }
  437. void swap( fiber & other) noexcept {
  438. std::swap( ptr_, other.ptr_);
  439. }
  440. };
  441. inline
  442. void swap( fiber & l, fiber & r) noexcept {
  443. l.swap( r);
  444. }
  445. typedef fiber fiber_context;
  446. }}
  447. #ifdef BOOST_HAS_ABI_HEADERS
  448. # include BOOST_ABI_SUFFIX
  449. #endif
  450. #endif // BOOST_CONTEXT_FIBER_H