fiber_ucontext.hpp 19 KB

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