fiber_ucontext.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. 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 (*)() ) & fiber_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 fiber_activation_record * create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  288. typedef fiber_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 (*)() ) & fiber_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 fiber {
  319. private:
  320. friend struct detail::fiber_activation_record;
  321. template< typename Ctx, typename StackAlloc, typename Fn >
  322. friend class detail::fiber_capture_record;
  323. template< typename Ctx, typename StackAlloc, typename Fn >
  324. friend detail::fiber_activation_record * detail::create_fiber1( StackAlloc &&, Fn &&);
  325. template< typename Ctx, typename StackAlloc, typename Fn >
  326. friend detail::fiber_activation_record * detail::create_fiber2( preallocated, StackAlloc &&, Fn &&);
  327. template< typename StackAlloc, typename Fn >
  328. friend fiber
  329. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  330. template< typename StackAlloc, typename Fn >
  331. friend fiber
  332. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  333. detail::fiber_activation_record * ptr_{ nullptr };
  334. fiber( detail::fiber_activation_record * ptr) noexcept :
  335. ptr_{ ptr } {
  336. }
  337. public:
  338. fiber() = default;
  339. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  340. fiber( Fn && fn) :
  341. fiber{
  342. std::allocator_arg,
  343. #if defined(BOOST_USE_SEGMENTED_STACKS)
  344. segmented_stack(),
  345. #else
  346. fixedsize_stack(),
  347. #endif
  348. std::forward< Fn >( fn) } {
  349. }
  350. template< typename StackAlloc, typename Fn >
  351. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  352. ptr_{ detail::create_fiber1< fiber >(
  353. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  354. }
  355. template< typename StackAlloc, typename Fn >
  356. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  357. ptr_{ detail::create_fiber2< fiber >(
  358. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  359. }
  360. ~fiber() {
  361. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  362. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  363. ptr_->force_unwind = true;
  364. ptr_->resume();
  365. BOOST_ASSERT( ptr_->terminated);
  366. }
  367. ptr_->deallocate();
  368. }
  369. }
  370. fiber( fiber const&) = delete;
  371. fiber & operator=( fiber const&) = delete;
  372. fiber( fiber && other) noexcept {
  373. swap( other);
  374. }
  375. fiber & operator=( fiber && other) noexcept {
  376. if ( BOOST_LIKELY( this != & other) ) {
  377. fiber tmp = std::move( other);
  378. swap( tmp);
  379. }
  380. return * this;
  381. }
  382. fiber resume() && {
  383. BOOST_ASSERT( nullptr != ptr_);
  384. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  385. detail::fiber_activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  386. #else
  387. detail::fiber_activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  388. #endif
  389. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  390. throw detail::forced_unwind{ ptr};
  391. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  392. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  393. detail::fiber_activation_record::current()->ontop = nullptr;
  394. }
  395. return { ptr };
  396. }
  397. template< typename Fn >
  398. fiber resume_with( Fn && fn) && {
  399. BOOST_ASSERT( nullptr != ptr_);
  400. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  401. detail::fiber_activation_record * ptr =
  402. detail::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  403. #else
  404. detail::fiber_activation_record * ptr =
  405. std::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  406. #endif
  407. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  408. throw detail::forced_unwind{ ptr};
  409. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  410. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  411. detail::fiber_activation_record::current()->ontop = nullptr;
  412. }
  413. return { ptr };
  414. }
  415. explicit operator bool() const noexcept {
  416. return nullptr != ptr_ && ! ptr_->terminated;
  417. }
  418. bool operator!() const noexcept {
  419. return nullptr == ptr_ || ptr_->terminated;
  420. }
  421. bool operator<( fiber const& other) const noexcept {
  422. return ptr_ < other.ptr_;
  423. }
  424. template< typename charT, class traitsT >
  425. friend std::basic_ostream< charT, traitsT > &
  426. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  427. if ( nullptr != other.ptr_) {
  428. return os << other.ptr_;
  429. } else {
  430. return os << "{not-a-context}";
  431. }
  432. }
  433. void swap( fiber & other) noexcept {
  434. std::swap( ptr_, other.ptr_);
  435. }
  436. };
  437. inline
  438. void swap( fiber & l, fiber & r) noexcept {
  439. l.swap( r);
  440. }
  441. typedef fiber fiber_context;
  442. }}
  443. #ifdef BOOST_HAS_ABI_HEADERS
  444. # include BOOST_ABI_SUFFIX
  445. #endif
  446. #endif // BOOST_CONTEXT_FIBER_H