fiber_winfib.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. detail::fiber_activation_record * ptr_{ nullptr };
  255. fiber( detail::fiber_activation_record * ptr) noexcept :
  256. ptr_{ ptr } {
  257. }
  258. public:
  259. fiber() = default;
  260. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  261. fiber( Fn && fn) :
  262. fiber{ std::allocator_arg,
  263. fixedsize_stack(),
  264. std::forward< Fn >( fn) } {
  265. }
  266. template< typename StackAlloc, typename Fn >
  267. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  268. ptr_{ detail::create_fiber1< fiber >(
  269. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {;
  270. }
  271. template< typename StackAlloc, typename Fn >
  272. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  273. ptr_{ detail::create_fiber2< fiber >(
  274. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  275. }
  276. ~fiber() {
  277. if ( BOOST_UNLIKELY( nullptr != ptr_) && ! ptr_->main_ctx) {
  278. if ( BOOST_LIKELY( ! ptr_->terminated) ) {
  279. ptr_->force_unwind = true;
  280. ptr_->resume();
  281. BOOST_ASSERT( ptr_->terminated);
  282. }
  283. ptr_->deallocate();
  284. }
  285. }
  286. fiber( fiber const&) = delete;
  287. fiber & operator=( fiber const&) = delete;
  288. fiber( fiber && other) noexcept {
  289. swap( other);
  290. }
  291. fiber & operator=( fiber && other) noexcept {
  292. if ( BOOST_LIKELY( this != & other) ) {
  293. fiber tmp = std::move( other);
  294. swap( tmp);
  295. }
  296. return * this;
  297. }
  298. fiber resume() && {
  299. BOOST_ASSERT( nullptr != ptr_);
  300. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  301. detail::fiber_activation_record * ptr = detail::exchange( ptr_, nullptr)->resume();
  302. #else
  303. detail::fiber_activation_record * ptr = std::exchange( ptr_, nullptr)->resume();
  304. #endif
  305. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  306. throw detail::forced_unwind{ ptr};
  307. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  308. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  309. detail::fiber_activation_record::current()->ontop = nullptr;
  310. }
  311. return { ptr };
  312. }
  313. template< typename Fn >
  314. fiber resume_with( Fn && fn) && {
  315. BOOST_ASSERT( nullptr != ptr_);
  316. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  317. detail::fiber_activation_record * ptr =
  318. detail::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  319. #else
  320. detail::fiber_activation_record * ptr =
  321. std::exchange( ptr_, nullptr)->resume_with< fiber >( std::forward< Fn >( fn) );
  322. #endif
  323. if ( BOOST_UNLIKELY( detail::fiber_activation_record::current()->force_unwind) ) {
  324. throw detail::forced_unwind{ ptr};
  325. } else if ( BOOST_UNLIKELY( nullptr != detail::fiber_activation_record::current()->ontop) ) {
  326. ptr = detail::fiber_activation_record::current()->ontop( ptr);
  327. detail::fiber_activation_record::current()->ontop = nullptr;
  328. }
  329. return { ptr };
  330. }
  331. explicit operator bool() const noexcept {
  332. return nullptr != ptr_ && ! ptr_->terminated;
  333. }
  334. bool operator!() const noexcept {
  335. return nullptr == ptr_ || ptr_->terminated;
  336. }
  337. bool operator<( fiber const& other) const noexcept {
  338. return ptr_ < other.ptr_;
  339. }
  340. #if !defined(BOOST_EMBTC)
  341. template< typename charT, class traitsT >
  342. friend std::basic_ostream< charT, traitsT > &
  343. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  344. if ( nullptr != other.ptr_) {
  345. return os << other.ptr_;
  346. } else {
  347. return os << "{not-a-context}";
  348. }
  349. }
  350. #else
  351. template< typename charT, class traitsT >
  352. friend std::basic_ostream< charT, traitsT > &
  353. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other);
  354. #endif
  355. void swap( fiber & other) noexcept {
  356. std::swap( ptr_, other.ptr_);
  357. }
  358. };
  359. #if defined(BOOST_EMBTC)
  360. template< typename charT, class traitsT >
  361. inline std::basic_ostream< charT, traitsT > &
  362. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  363. if ( nullptr != other.ptr_) {
  364. return os << other.ptr_;
  365. } else {
  366. return os << "{not-a-context}";
  367. }
  368. }
  369. #endif
  370. inline
  371. void swap( fiber & l, fiber & r) noexcept {
  372. l.swap( r);
  373. }
  374. typedef fiber fiber_context;
  375. }}
  376. #if defined(BOOST_MSVC)
  377. # pragma warning(pop)
  378. #endif
  379. #ifdef BOOST_HAS_ABI_HEADERS
  380. # include BOOST_ABI_SUFFIX
  381. #endif
  382. #endif // BOOST_CONTEXT_FIBER_H