fiber_winfib.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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 <windows.h>
  8. #include <boost/context/detail/config.hpp>
  9. #include <algorithm>
  10. #include <cstddef>
  11. #include <cstdint>
  12. #include <cstdlib>
  13. #include <cstring>
  14. #include <functional>
  15. #include <memory>
  16. #include <ostream>
  17. #include <system_error>
  18. #include <tuple>
  19. #include <utility>
  20. #include <boost/assert.hpp>
  21. #include <boost/config.hpp>
  22. #include <boost/context/detail/disable_overload.hpp>
  23. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  24. #include <boost/context/detail/exchange.hpp>
  25. #endif
  26. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  27. #include <boost/context/detail/invoke.hpp>
  28. #endif
  29. #include <boost/context/fixedsize_stack.hpp>
  30. #include <boost/context/flags.hpp>
  31. #include <boost/context/preallocated.hpp>
  32. #include <boost/context/stack_context.hpp>
  33. #ifdef BOOST_HAS_ABI_HEADERS
  34. # include BOOST_ABI_PREFIX
  35. #endif
  36. #if defined(BOOST_MSVC)
  37. # pragma warning(push)
  38. # pragma warning(disable: 4702)
  39. #endif
  40. namespace boost {
  41. namespace context {
  42. namespace detail {
  43. // tampoline function
  44. // entered if the execution context
  45. // is resumed for the first time
  46. template< typename Record >
  47. static VOID WINAPI fiber_entry_func( LPVOID data) noexcept {
  48. Record * record = static_cast< Record * >( data);
  49. BOOST_ASSERT( nullptr != record);
  50. // start execution of toplevel context-function
  51. record->run();
  52. }
  53. struct BOOST_CONTEXT_DECL fiber_activation_record {
  54. LPVOID fiber{ nullptr };
  55. stack_context sctx{};
  56. bool main_ctx{ true };
  57. fiber_activation_record * from{ nullptr };
  58. std::function< fiber_activation_record*(fiber_activation_record*&) > ontop{};
  59. bool terminated{ false };
  60. bool force_unwind{ false };
  61. static fiber_activation_record *& current() noexcept;
  62. // used for toplevel-context
  63. // (e.g. main context, thread-entry context)
  64. fiber_activation_record() noexcept {
  65. #if ( _WIN32_WINNT > 0x0600)
  66. if ( ::IsThreadAFiber() ) {
  67. fiber = ::GetCurrentFiber();
  68. } else {
  69. fiber = ::ConvertThreadToFiber( nullptr);
  70. }
  71. #else
  72. fiber = ::ConvertThreadToFiber( nullptr);
  73. if ( BOOST_UNLIKELY( nullptr == fiber) ) {
  74. BOOST_ASSERT( ERROR_ALREADY_FIBER == ::GetLastError());
  75. fiber = ::GetCurrentFiber();
  76. BOOST_ASSERT( nullptr != fiber);
  77. BOOST_ASSERT( reinterpret_cast< LPVOID >( 0x1E00) != fiber);
  78. }
  79. #endif
  80. }
  81. fiber_activation_record( stack_context sctx_) noexcept :
  82. sctx{ sctx_ },
  83. main_ctx{ false } {
  84. }
  85. virtual ~fiber_activation_record() {
  86. if ( BOOST_UNLIKELY( main_ctx) ) {
  87. ::ConvertFiberToThread();
  88. } else {
  89. ::DeleteFiber( fiber);
  90. }
  91. }
  92. fiber_activation_record( fiber_activation_record const&) = delete;
  93. fiber_activation_record & operator=( fiber_activation_record const&) = delete;
  94. bool is_main_context() const noexcept {
  95. return main_ctx;
  96. }
  97. fiber_activation_record * resume() {
  98. from = current();
  99. // store `this` in static, thread local pointer
  100. // `this` will become the active (running) context
  101. current() = this;
  102. // context switch from parent context to `this`-context
  103. // context switch
  104. ::SwitchToFiber( fiber);
  105. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  106. return detail::exchange( current()->from, nullptr);
  107. #else
  108. return std::exchange( current()->from, nullptr);
  109. #endif
  110. }
  111. template< typename Ctx, typename Fn >
  112. fiber_activation_record * resume_with( Fn && fn) {
  113. from = current();
  114. // store `this` in static, thread local pointer
  115. // `this` will become the active (running) context
  116. // returned by fiber::current()
  117. current() = this;
  118. #if defined(BOOST_NO_CXX14_GENERIC_LAMBDAS)
  119. current()->ontop = std::bind(
  120. [](typename std::decay< Fn >::type & fn, fiber_activation_record *& ptr){
  121. Ctx c{ ptr };
  122. c = fn( std::move( c) );
  123. if ( ! c) {
  124. ptr = nullptr;
  125. }
  126. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  127. return exchange( c.ptr_, nullptr);
  128. #else
  129. return std::exchange( c.ptr_, nullptr);
  130. #endif
  131. },
  132. std::forward< Fn >( fn),
  133. std::placeholders::_1);
  134. #else
  135. current()->ontop = [fn=std::forward<Fn>(fn)](fiber_activation_record *& ptr){
  136. Ctx c{ ptr };
  137. c = fn( std::move( c) );
  138. if ( ! c) {
  139. ptr = nullptr;
  140. }
  141. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  142. return exchange( c.ptr_, nullptr);
  143. #else
  144. return std::exchange( c.ptr_, nullptr);
  145. #endif
  146. };
  147. #endif
  148. // context switch
  149. ::SwitchToFiber( fiber);
  150. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  151. return detail::exchange( current()->from, nullptr);
  152. #else
  153. return std::exchange( current()->from, nullptr);
  154. #endif
  155. }
  156. virtual void deallocate() noexcept {
  157. }
  158. };
  159. struct BOOST_CONTEXT_DECL fiber_activation_record_initializer {
  160. fiber_activation_record_initializer() noexcept;
  161. ~fiber_activation_record_initializer();
  162. };
  163. struct forced_unwind {
  164. fiber_activation_record * from{ nullptr };
  165. #ifndef BOOST_ASSERT_IS_VOID
  166. bool caught{ false };
  167. #endif
  168. explicit forced_unwind( fiber_activation_record * from_) :
  169. from{ from_ } {
  170. }
  171. #ifndef BOOST_ASSERT_IS_VOID
  172. ~forced_unwind() {
  173. BOOST_ASSERT( caught);
  174. }
  175. #endif
  176. };
  177. template< typename Ctx, typename StackAlloc, typename Fn >
  178. class fiber_capture_record : public fiber_activation_record {
  179. private:
  180. typename std::decay< StackAlloc >::type salloc_;
  181. typename std::decay< Fn >::type fn_;
  182. static void destroy( fiber_capture_record * p) noexcept {
  183. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  184. stack_context sctx = p->sctx;
  185. // deallocate activation record
  186. p->~fiber_capture_record();
  187. // destroy stack with stack allocator
  188. salloc.deallocate( sctx);
  189. }
  190. public:
  191. fiber_capture_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept :
  192. fiber_activation_record( sctx),
  193. salloc_( std::forward< StackAlloc >( salloc)),
  194. fn_( std::forward< Fn >( fn) ) {
  195. }
  196. void deallocate() noexcept override final {
  197. BOOST_ASSERT( main_ctx || ( ! main_ctx && terminated) );
  198. destroy( this);
  199. }
  200. void run() {
  201. Ctx c{ from };
  202. try {
  203. // invoke context-function
  204. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  205. c = boost::context::detail::invoke( fn_, std::move( c) );
  206. #else
  207. c = std::invoke( fn_, std::move( c) );
  208. #endif
  209. } catch ( forced_unwind const& ex) {
  210. c = Ctx{ ex.from };
  211. #ifndef BOOST_ASSERT_IS_VOID
  212. const_cast< forced_unwind & >( ex).caught = true;
  213. #endif
  214. }
  215. // this context has finished its task
  216. from = nullptr;
  217. ontop = nullptr;
  218. terminated = true;
  219. force_unwind = false;
  220. std::move( c).resume();
  221. BOOST_ASSERT_MSG( false, "fiber already terminated");
  222. }
  223. };
  224. template< typename Ctx, typename StackAlloc, typename Fn >
  225. static fiber_activation_record * create_fiber1( StackAlloc && salloc, Fn && fn) {
  226. typedef fiber_capture_record< Ctx, StackAlloc, Fn > capture_t;
  227. auto sctx = salloc.allocate();
  228. BOOST_ASSERT( ( sizeof( capture_t) ) < sctx.size);
  229. // reserve space for control structure
  230. void * storage = reinterpret_cast< void * >(
  231. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  232. & ~ static_cast< uintptr_t >( 0xff) );
  233. // placment new for control structure on context stack
  234. capture_t * record = new ( storage) capture_t{
  235. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  236. // create user-context
  237. record->fiber = ::CreateFiber( sctx.size, & detail::fiber_entry_func< capture_t >, record);
  238. return record;
  239. }
  240. template< typename Ctx, typename StackAlloc, typename Fn >
  241. static fiber_activation_record * create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  242. typedef fiber_capture_record< Ctx, StackAlloc, Fn > capture_t;
  243. BOOST_ASSERT( ( sizeof( capture_t) ) < palloc.size);
  244. // reserve space for control structure
  245. void * storage = reinterpret_cast< void * >(
  246. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  247. & ~ static_cast< uintptr_t >( 0xff) );
  248. // placment new for control structure on context stack
  249. capture_t * record = new ( storage) capture_t{
  250. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  251. // create user-context
  252. record->fiber = ::CreateFiber( palloc.sctx.size, & detail::fiber_entry_func< capture_t >, record);
  253. return record;
  254. }
  255. }
  256. class BOOST_CONTEXT_DECL fiber {
  257. private:
  258. friend struct detail::fiber_activation_record;
  259. template< typename Ctx, typename StackAlloc, typename Fn >
  260. friend class detail::fiber_capture_record;
  261. template< typename Ctx, typename StackAlloc, typename Fn >
  262. friend detail::fiber_activation_record * detail::create_fiber1( StackAlloc &&, Fn &&);
  263. template< typename Ctx, typename StackAlloc, typename Fn >
  264. friend detail::fiber_activation_record * detail::create_fiber2( preallocated, StackAlloc &&, Fn &&);
  265. template< typename StackAlloc, typename Fn >
  266. friend fiber
  267. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  268. template< typename StackAlloc, typename Fn >
  269. friend fiber
  270. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  271. detail::fiber_activation_record * ptr_{ nullptr };
  272. fiber( detail::fiber_activation_record * ptr) noexcept :
  273. ptr_{ ptr } {
  274. }
  275. public:
  276. fiber() = default;
  277. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  278. fiber( Fn && fn) :
  279. fiber{ std::allocator_arg,
  280. fixedsize_stack(),
  281. std::forward< Fn >( fn) } {
  282. }
  283. template< typename StackAlloc, typename Fn >
  284. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  285. ptr_{ detail::create_fiber1< fiber >(
  286. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {;
  287. }
  288. template< typename StackAlloc, typename Fn >
  289. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  290. ptr_{ detail::create_fiber2< fiber >(
  291. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  292. }
  293. ~fiber() {
  294. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  295. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  296. ptr_->force_unwind = true;
  297. ptr_->resume();
  298. BOOST_ASSERT( ptr_->terminated);
  299. }
  300. ptr_->deallocate();
  301. }
  302. }
  303. fiber( fiber const&) = delete;
  304. fiber & operator=( fiber const&) = delete;
  305. fiber( fiber && other) noexcept {
  306. swap( other);
  307. }
  308. fiber & operator=( fiber && other) noexcept {
  309. if ( BOOST_LIKELY( this != & other) ) {
  310. fiber tmp = std::move( other);
  311. swap( tmp);
  312. }
  313. return * this;
  314. }
  315. fiber resume() && {
  316. BOOST_ASSERT( nullptr != ptr_);
  317. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  318. detail::fiber_activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  319. #else
  320. detail::fiber_activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  321. #endif
  322. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  323. throw detail::forced_unwind{ ptr};
  324. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  325. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  326. detail::fiber_activation_record::current()->ontop = nullptr;
  327. }
  328. return { ptr };
  329. }
  330. template< typename Fn >
  331. fiber resume_with( Fn && fn) && {
  332. BOOST_ASSERT( nullptr != ptr_);
  333. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  334. detail::fiber_activation_record * ptr =
  335. detail::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  336. #else
  337. detail::fiber_activation_record * ptr =
  338. std::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  339. #endif
  340. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  341. throw detail::forced_unwind{ ptr};
  342. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  343. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  344. detail::fiber_activation_record::current()->ontop = nullptr;
  345. }
  346. return { ptr };
  347. }
  348. explicit operator bool() const noexcept {
  349. return nullptr != ptr_ && ! ptr_->terminated;
  350. }
  351. bool operator!() const noexcept {
  352. return nullptr == ptr_ || ptr_->terminated;
  353. }
  354. bool operator<( fiber const& other) const noexcept {
  355. return ptr_ < other.ptr_;
  356. }
  357. #if !defined(BOOST_EMBTC)
  358. template< typename charT, class traitsT >
  359. friend std::basic_ostream< charT, traitsT > &
  360. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  361. if ( nullptr != other.ptr_) {
  362. return os << other.ptr_;
  363. } else {
  364. return os << "{not-a-context}";
  365. }
  366. }
  367. #else
  368. template< typename charT, class traitsT >
  369. friend std::basic_ostream< charT, traitsT > &
  370. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other);
  371. #endif
  372. void swap( fiber & other) noexcept {
  373. std::swap( ptr_, other.ptr_);
  374. }
  375. };
  376. #if defined(BOOST_EMBTC)
  377. template< typename charT, class traitsT >
  378. inline std::basic_ostream< charT, traitsT > &
  379. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  380. if ( nullptr != other.ptr_) {
  381. return os << other.ptr_;
  382. } else {
  383. return os << "{not-a-context}";
  384. }
  385. }
  386. #endif
  387. inline
  388. void swap( fiber & l, fiber & r) noexcept {
  389. l.swap( r);
  390. }
  391. typedef fiber fiber_context;
  392. }}
  393. #if defined(BOOST_MSVC)
  394. # pragma warning(pop)
  395. #endif
  396. #ifdef BOOST_HAS_ABI_HEADERS
  397. # include BOOST_ABI_SUFFIX
  398. #endif
  399. #endif // BOOST_CONTEXT_FIBER_H