fiber_winfib.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. explicit forced_unwind( fiber_activation_record * from_) :
  166. from{ from_ } {
  167. }
  168. };
  169. template< typename Ctx, typename StackAlloc, typename Fn >
  170. class fiber_capture_record : public fiber_activation_record {
  171. private:
  172. typename std::decay< StackAlloc >::type salloc_;
  173. typename std::decay< Fn >::type fn_;
  174. static void destroy( fiber_capture_record * p) noexcept {
  175. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  176. stack_context sctx = p->sctx;
  177. // deallocate activation record
  178. p->~fiber_capture_record();
  179. // destroy stack with stack allocator
  180. salloc.deallocate( sctx);
  181. }
  182. public:
  183. fiber_capture_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept :
  184. fiber_activation_record( sctx),
  185. salloc_( std::forward< StackAlloc >( salloc)),
  186. fn_( std::forward< Fn >( fn) ) {
  187. }
  188. void deallocate() noexcept override final {
  189. BOOST_ASSERT( main_ctx || ( ! main_ctx && terminated) );
  190. destroy( this);
  191. }
  192. void run() {
  193. Ctx c{ from };
  194. try {
  195. // invoke context-function
  196. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  197. c = boost::context::detail::invoke( fn_, std::move( c) );
  198. #else
  199. c = std::invoke( fn_, std::move( c) );
  200. #endif
  201. } catch ( forced_unwind const& ex) {
  202. c = Ctx{ ex.from };
  203. }
  204. // this context has finished its task
  205. from = nullptr;
  206. ontop = nullptr;
  207. terminated = true;
  208. force_unwind = false;
  209. std::move( c).resume();
  210. BOOST_ASSERT_MSG( false, "fiber already terminated");
  211. }
  212. };
  213. template< typename Ctx, typename StackAlloc, typename Fn >
  214. static fiber_activation_record * create_fiber1( StackAlloc && salloc, Fn && fn) {
  215. typedef fiber_capture_record< Ctx, StackAlloc, Fn > capture_t;
  216. auto sctx = salloc.allocate();
  217. BOOST_ASSERT( ( sizeof( capture_t) ) < sctx.size);
  218. // reserve space for control structure
  219. void * storage = reinterpret_cast< void * >(
  220. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  221. & ~ static_cast< uintptr_t >( 0xff) );
  222. // placment new for control structure on context stack
  223. capture_t * record = new ( storage) capture_t{
  224. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  225. // create user-context
  226. record->fiber = ::CreateFiber( sctx.size, & detail::fiber_entry_func< capture_t >, record);
  227. return record;
  228. }
  229. template< typename Ctx, typename StackAlloc, typename Fn >
  230. static fiber_activation_record * create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  231. typedef fiber_capture_record< Ctx, StackAlloc, Fn > capture_t;
  232. BOOST_ASSERT( ( sizeof( capture_t) ) < palloc.size);
  233. // reserve space for control structure
  234. void * storage = reinterpret_cast< void * >(
  235. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( capture_t) ) )
  236. & ~ static_cast< uintptr_t >( 0xff) );
  237. // placment new for control structure on context stack
  238. capture_t * record = new ( storage) capture_t{
  239. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  240. // create user-context
  241. record->fiber = ::CreateFiber( palloc.sctx.size, & detail::fiber_entry_func< capture_t >, record);
  242. return record;
  243. }
  244. }
  245. class BOOST_CONTEXT_DECL fiber {
  246. private:
  247. friend struct detail::fiber_activation_record;
  248. template< typename Ctx, typename StackAlloc, typename Fn >
  249. friend class detail::fiber_capture_record;
  250. template< typename Ctx, typename StackAlloc, typename Fn >
  251. friend detail::fiber_activation_record * detail::create_fiber1( StackAlloc &&, Fn &&);
  252. template< typename Ctx, typename StackAlloc, typename Fn >
  253. friend detail::fiber_activation_record * detail::create_fiber2( preallocated, StackAlloc &&, Fn &&);
  254. template< typename StackAlloc, typename Fn >
  255. friend fiber
  256. callcc( std::allocator_arg_t, StackAlloc &&, Fn &&);
  257. template< typename StackAlloc, typename Fn >
  258. friend fiber
  259. callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&);
  260. detail::fiber_activation_record * ptr_{ nullptr };
  261. fiber( detail::fiber_activation_record * ptr) noexcept :
  262. ptr_{ ptr } {
  263. }
  264. public:
  265. fiber() = default;
  266. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  267. fiber( Fn && fn) :
  268. fiber{ std::allocator_arg,
  269. fixedsize_stack(),
  270. std::forward< Fn >( fn) } {
  271. }
  272. template< typename StackAlloc, typename Fn >
  273. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  274. ptr_{ detail::create_fiber1< fiber >(
  275. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {;
  276. }
  277. template< typename StackAlloc, typename Fn >
  278. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  279. ptr_{ detail::create_fiber2< fiber >(
  280. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  281. }
  282. ~fiber() {
  283. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  284. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  285. ptr_->force_unwind = true;
  286. ptr_->resume();
  287. BOOST_ASSERT( ptr_->terminated);
  288. }
  289. ptr_->deallocate();
  290. }
  291. }
  292. fiber( fiber const&) = delete;
  293. fiber & operator=( fiber const&) = delete;
  294. fiber( fiber && other) noexcept {
  295. swap( other);
  296. }
  297. fiber & operator=( fiber && other) noexcept {
  298. if ( BOOST_LIKELY( this != & other) ) {
  299. fiber tmp = std::move( other);
  300. swap( tmp);
  301. }
  302. return * this;
  303. }
  304. fiber resume() && {
  305. BOOST_ASSERT( nullptr != ptr_);
  306. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  307. detail::fiber_activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  308. #else
  309. detail::fiber_activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  310. #endif
  311. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  312. throw detail::forced_unwind{ ptr};
  313. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  314. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  315. detail::fiber_activation_record::current()->ontop = nullptr;
  316. }
  317. return { ptr };
  318. }
  319. template< typename Fn >
  320. fiber resume_with( Fn && fn) && {
  321. BOOST_ASSERT( nullptr != ptr_);
  322. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  323. detail::fiber_activation_record * ptr =
  324. detail::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  325. #else
  326. detail::fiber_activation_record * ptr =
  327. std::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  328. #endif
  329. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  330. throw detail::forced_unwind{ ptr};
  331. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  332. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  333. detail::fiber_activation_record::current()->ontop = nullptr;
  334. }
  335. return { ptr };
  336. }
  337. explicit operator bool() const noexcept {
  338. return nullptr != ptr_ && ! ptr_->terminated;
  339. }
  340. bool operator!() const noexcept {
  341. return nullptr == ptr_ || ptr_->terminated;
  342. }
  343. bool operator<( fiber const& other) const noexcept {
  344. return ptr_ < other.ptr_;
  345. }
  346. #if !defined(BOOST_EMBTC)
  347. template< typename charT, class traitsT >
  348. friend std::basic_ostream< charT, traitsT > &
  349. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  350. if ( nullptr != other.ptr_) {
  351. return os << other.ptr_;
  352. } else {
  353. return os << "{not-a-context}";
  354. }
  355. }
  356. #else
  357. template< typename charT, class traitsT >
  358. friend std::basic_ostream< charT, traitsT > &
  359. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other);
  360. #endif
  361. void swap( fiber & other) noexcept {
  362. std::swap( ptr_, other.ptr_);
  363. }
  364. };
  365. #if defined(BOOST_EMBTC)
  366. template< typename charT, class traitsT >
  367. inline std::basic_ostream< charT, traitsT > &
  368. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  369. if ( nullptr != other.ptr_) {
  370. return os << other.ptr_;
  371. } else {
  372. return os << "{not-a-context}";
  373. }
  374. }
  375. #endif
  376. inline
  377. void swap( fiber & l, fiber & r) noexcept {
  378. l.swap( r);
  379. }
  380. typedef fiber fiber_context;
  381. }}
  382. #if defined(BOOST_MSVC)
  383. # pragma warning(pop)
  384. #endif
  385. #ifdef BOOST_HAS_ABI_HEADERS
  386. # include BOOST_ABI_SUFFIX
  387. #endif
  388. #endif // BOOST_CONTEXT_FIBER_H