fiber_fcontext.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/context/detail/config.hpp>
  8. #include <algorithm>
  9. #include <cstddef>
  10. #include <cstdint>
  11. #include <cstdlib>
  12. #include <exception>
  13. #include <functional>
  14. #include <memory>
  15. #include <ostream>
  16. #include <tuple>
  17. #include <utility>
  18. #include <boost/assert.hpp>
  19. #include <boost/config.hpp>
  20. #include <boost/intrusive_ptr.hpp>
  21. #include <boost/core/ignore_unused.hpp>
  22. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  23. #include <boost/context/detail/exchange.hpp>
  24. #endif
  25. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  26. #include <boost/context/detail/invoke.hpp>
  27. #endif
  28. #include <boost/context/detail/disable_overload.hpp>
  29. #include <boost/context/detail/exception.hpp>
  30. #include <boost/context/detail/fcontext.hpp>
  31. #include <boost/context/detail/tuple.hpp>
  32. #include <boost/context/fixedsize_stack.hpp>
  33. #include <boost/context/flags.hpp>
  34. #include <boost/context/preallocated.hpp>
  35. #include <boost/context/segmented_stack.hpp>
  36. #include <boost/context/stack_context.hpp>
  37. #ifdef BOOST_HAS_ABI_HEADERS
  38. # include BOOST_ABI_PREFIX
  39. #endif
  40. #if defined(__CET__) && defined(__unix__)
  41. # include <cet.h>
  42. # include <sys/mman.h>
  43. # include <unistd.h>
  44. # define SHSTK_ENABLED (__CET__ & 0x2)
  45. # define BOOST_CONTEXT_SHADOW_STACK (SHSTK_ENABLED && SHADOW_STACK_SYSCALL)
  46. # if !defined(__NR_map_shadow_stack)
  47. # define __NR_map_shadow_stack 453
  48. # endif
  49. #ifndef SHADOW_STACK_SET_TOKEN
  50. # define SHADOW_STACK_SET_TOKEN 0x1
  51. #endif
  52. #endif
  53. #if defined(BOOST_MSVC)
  54. # pragma warning(push)
  55. # pragma warning(disable: 4702)
  56. #endif
  57. #if ! (defined(__GLIBCPP__) || defined(__GLIBCXX__))
  58. namespace boost {
  59. namespace context {
  60. namespace detail {
  61. // manage_exception_state is a dummy struct unless we have specific support
  62. struct manage_exception_state {};
  63. } // namespace detail
  64. } // namespace context
  65. } // namespace boost
  66. #else // libstdc++
  67. #include <cxxabi.h>
  68. namespace __cxxabiv1 {
  69. struct __cxa_eh_globals {
  70. void * caughtExceptions;
  71. unsigned int uncaughtExceptions;
  72. };
  73. class manage_exception_state {
  74. public:
  75. manage_exception_state() {
  76. exception_state_ = *__cxa_get_globals();
  77. }
  78. ~manage_exception_state() {
  79. *__cxa_get_globals() = exception_state_;
  80. }
  81. private:
  82. __cxa_eh_globals exception_state_;
  83. };
  84. } // namespace __cxxabiv1
  85. namespace boost {
  86. namespace context {
  87. namespace detail {
  88. using __cxxabiv1::manage_exception_state;
  89. } // namespace detail
  90. } // namespace context
  91. } // namespace boost
  92. #endif // __GLIBCPP__ or __GLIBCXX__
  93. namespace boost {
  94. namespace context {
  95. namespace detail {
  96. inline
  97. transfer_t fiber_unwind( transfer_t t) {
  98. throw forced_unwind( t.fctx);
  99. return { nullptr, nullptr };
  100. }
  101. template< typename Rec >
  102. transfer_t fiber_exit( transfer_t t) noexcept {
  103. Rec * rec = static_cast< Rec * >( t.data);
  104. #if BOOST_CONTEXT_SHADOW_STACK
  105. // destroy shadow stack
  106. std::size_t ss_size = *((unsigned long*)(reinterpret_cast< uintptr_t >( rec)- 16));
  107. long unsigned int ss_base = *((unsigned long*)(reinterpret_cast< uintptr_t >( rec)- 8));
  108. munmap((void *)ss_base, ss_size);
  109. #endif
  110. // destroy context stack
  111. rec->deallocate();
  112. return { nullptr, nullptr };
  113. }
  114. template< typename Rec >
  115. void fiber_entry( transfer_t t) noexcept {
  116. // transfer control structure to the context-stack
  117. Rec * rec = static_cast< Rec * >( t.data);
  118. BOOST_ASSERT( nullptr != t.fctx);
  119. BOOST_ASSERT( nullptr != rec);
  120. try {
  121. // jump back to `create_context()`
  122. t = jump_fcontext( t.fctx, nullptr);
  123. // start executing
  124. t.fctx = rec->run( t.fctx);
  125. } catch ( forced_unwind const& ex) {
  126. t = { ex.fctx, nullptr };
  127. }
  128. BOOST_ASSERT( nullptr != t.fctx);
  129. // destroy context-stack of `this`context on next context
  130. ontop_fcontext( t.fctx, rec, fiber_exit< Rec >);
  131. BOOST_ASSERT_MSG( false, "context already terminated");
  132. }
  133. template< typename Ctx, typename Fn >
  134. transfer_t fiber_ontop( transfer_t t) {
  135. BOOST_ASSERT( nullptr != t.data);
  136. auto p = *static_cast< Fn * >( t.data);
  137. t.data = nullptr;
  138. // execute function, pass fiber via reference
  139. Ctx c = p( Ctx{ t.fctx } );
  140. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  141. return { exchange( c.fctx_, nullptr), nullptr };
  142. #else
  143. return { std::exchange( c.fctx_, nullptr), nullptr };
  144. #endif
  145. }
  146. template< typename Ctx, typename StackAlloc, typename Fn >
  147. class fiber_record {
  148. private:
  149. stack_context sctx_;
  150. typename std::decay< StackAlloc >::type salloc_;
  151. typename std::decay< Fn >::type fn_;
  152. static void destroy( fiber_record * p) noexcept {
  153. typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_);
  154. stack_context sctx = p->sctx_;
  155. // deallocate fiber_record
  156. p->~fiber_record();
  157. // destroy stack with stack allocator
  158. salloc.deallocate( sctx);
  159. }
  160. public:
  161. fiber_record( stack_context sctx, StackAlloc && salloc,
  162. Fn && fn) noexcept :
  163. sctx_( sctx),
  164. salloc_( std::forward< StackAlloc >( salloc)),
  165. fn_( std::forward< Fn >( fn) ) {
  166. }
  167. fiber_record( fiber_record const&) = delete;
  168. fiber_record & operator=( fiber_record const&) = delete;
  169. void deallocate() noexcept {
  170. destroy( this);
  171. }
  172. fcontext_t run( fcontext_t fctx) {
  173. // invoke context-function
  174. #if defined(BOOST_NO_CXX17_STD_INVOKE)
  175. Ctx c = boost::context::detail::invoke( fn_, Ctx{ fctx } );
  176. #else
  177. Ctx c = std::invoke( fn_, Ctx{ fctx } );
  178. #endif
  179. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  180. return exchange( c.fctx_, nullptr);
  181. #else
  182. return std::exchange( c.fctx_, nullptr);
  183. #endif
  184. }
  185. };
  186. template< typename Record, typename StackAlloc, typename Fn >
  187. fcontext_t create_fiber1( StackAlloc && salloc, Fn && fn) {
  188. auto sctx = salloc.allocate();
  189. // reserve space for control structure
  190. void * storage = reinterpret_cast< void * >(
  191. ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( Record) ) )
  192. & ~static_cast< uintptr_t >( 0xff) );
  193. // placement new for control structure on context stack
  194. Record * record = new ( storage) Record{
  195. sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  196. // 64byte gab between control structure and stack top
  197. // should be 16byte aligned
  198. void * stack_top = reinterpret_cast< void * >(
  199. reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) );
  200. void * stack_bottom = reinterpret_cast< void * >(
  201. reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) );
  202. // create fast-context
  203. const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom);
  204. #if BOOST_CONTEXT_SHADOW_STACK
  205. std::size_t ss_size = size >> 5;
  206. // align shadow stack to 8 bytes.
  207. ss_size = (ss_size + 7) & ~7;
  208. // Todo: shadow stack occupies at least 4KB
  209. ss_size = (ss_size > 4096) ? size : 4096;
  210. // create shadow stack
  211. void *ss_base = (void *)syscall(__NR_map_shadow_stack, 0, ss_size, SHADOW_STACK_SET_TOKEN);
  212. BOOST_ASSERT(ss_base != -1);
  213. unsigned long ss_sp = (unsigned long)ss_base + ss_size;
  214. /* pass the shadow stack pointer to make_fcontext
  215. i.e., link the new shadow stack with the new fcontext
  216. TODO should be a better way? */
  217. *((unsigned long*)(reinterpret_cast< uintptr_t >( stack_top)- 8)) = ss_sp;
  218. /* Todo: place shadow stack info in 64byte gap */
  219. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 8)) = (unsigned long) ss_base;
  220. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 16)) = ss_size;
  221. #endif
  222. const fcontext_t fctx = make_fcontext( stack_top, size, & fiber_entry< Record >);
  223. BOOST_ASSERT( nullptr != fctx);
  224. // transfer control structure to context-stack
  225. return jump_fcontext( fctx, record).fctx;
  226. }
  227. template< typename Record, typename StackAlloc, typename Fn >
  228. fcontext_t create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) {
  229. // reserve space for control structure
  230. void * storage = reinterpret_cast< void * >(
  231. ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( Record) ) )
  232. & ~ static_cast< uintptr_t >( 0xff) );
  233. // placwment new for control structure on context-stack
  234. Record * record = new ( storage) Record{
  235. palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) };
  236. // 64byte gab between control structure and stack top
  237. void * stack_top = reinterpret_cast< void * >(
  238. reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) );
  239. void * stack_bottom = reinterpret_cast< void * >(
  240. reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) );
  241. // create fast-context
  242. const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom);
  243. #if BOOST_CONTEXT_SHADOW_STACK
  244. std::size_t ss_size = size >> 5;
  245. // align shadow stack to 8 bytes.
  246. ss_size = (ss_size + 7) & ~7;
  247. // Todo: shadow stack occupies at least 4KB
  248. ss_size = (ss_size > 4096) ? size : 4096;
  249. // create shadow stack
  250. void *ss_base = (void *)syscall(__NR_map_shadow_stack, 0, ss_size, SHADOW_STACK_SET_TOKEN);
  251. BOOST_ASSERT(ss_base != -1);
  252. unsigned long ss_sp = (unsigned long)ss_base + ss_size;
  253. /* pass the shadow stack pointer to make_fcontext
  254. i.e., link the new shadow stack with the new fcontext
  255. TODO should be a better way? */
  256. *((unsigned long*)(reinterpret_cast< uintptr_t >( stack_top)- 8)) = ss_sp;
  257. /* Todo: place shadow stack info in 64byte gap */
  258. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 8)) = (unsigned long) ss_base;
  259. *((unsigned long*)(reinterpret_cast< uintptr_t >( storage)- 16)) = ss_size;
  260. #endif
  261. const fcontext_t fctx = make_fcontext( stack_top, size, & fiber_entry< Record >);
  262. BOOST_ASSERT( nullptr != fctx);
  263. // transfer control structure to context-stack
  264. return jump_fcontext( fctx, record).fctx;
  265. }
  266. } // namespace detail
  267. class fiber {
  268. private:
  269. template< typename Ctx, typename StackAlloc, typename Fn >
  270. friend class detail::fiber_record;
  271. template< typename Ctx, typename Fn >
  272. friend detail::transfer_t
  273. detail::fiber_ontop( detail::transfer_t);
  274. detail::fcontext_t fctx_{ nullptr };
  275. fiber( detail::fcontext_t fctx) noexcept :
  276. fctx_{ fctx } {
  277. }
  278. public:
  279. fiber() noexcept = default;
  280. template< typename Fn, typename = detail::disable_overload< fiber, Fn > >
  281. fiber( Fn && fn) :
  282. fiber{ std::allocator_arg, fixedsize_stack(), std::forward< Fn >( fn) } {
  283. }
  284. template< typename StackAlloc, typename Fn >
  285. fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) :
  286. fctx_{ detail::create_fiber1< detail::fiber_record< fiber, StackAlloc, Fn > >(
  287. std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  288. }
  289. template< typename StackAlloc, typename Fn >
  290. fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) :
  291. fctx_{ detail::create_fiber2< detail::fiber_record< fiber, StackAlloc, Fn > >(
  292. palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } {
  293. }
  294. #if defined(BOOST_USE_SEGMENTED_STACKS)
  295. template< typename Fn >
  296. fiber( std::allocator_arg_t, segmented_stack, Fn &&);
  297. template< typename StackAlloc, typename Fn >
  298. fiber( std::allocator_arg_t, preallocated, segmented_stack, Fn &&);
  299. #endif
  300. ~fiber() {
  301. if ( BOOST_UNLIKELY( nullptr != fctx_) ) {
  302. detail::manage_exception_state exstate;
  303. boost::ignore_unused(exstate);
  304. detail::ontop_fcontext(
  305. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  306. detail::exchange( fctx_, nullptr),
  307. #else
  308. std::exchange( fctx_, nullptr),
  309. #endif
  310. nullptr,
  311. detail::fiber_unwind);
  312. }
  313. }
  314. fiber( fiber && other) noexcept {
  315. swap( other);
  316. }
  317. fiber & operator=( fiber && other) noexcept {
  318. if ( BOOST_LIKELY( this != & other) ) {
  319. fiber tmp = std::move( other);
  320. swap( tmp);
  321. }
  322. return * this;
  323. }
  324. fiber( fiber const& other) noexcept = delete;
  325. fiber & operator=( fiber const& other) noexcept = delete;
  326. fiber resume() && {
  327. BOOST_ASSERT( nullptr != fctx_);
  328. detail::manage_exception_state exstate;
  329. boost::ignore_unused(exstate);
  330. return { detail::jump_fcontext(
  331. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  332. detail::exchange( fctx_, nullptr),
  333. #else
  334. std::exchange( fctx_, nullptr),
  335. #endif
  336. nullptr).fctx };
  337. }
  338. template< typename Fn >
  339. fiber resume_with( Fn && fn) && {
  340. BOOST_ASSERT( nullptr != fctx_);
  341. detail::manage_exception_state exstate;
  342. boost::ignore_unused(exstate);
  343. auto p = std::forward< Fn >( fn);
  344. return { detail::ontop_fcontext(
  345. #if defined(BOOST_NO_CXX14_STD_EXCHANGE)
  346. detail::exchange( fctx_, nullptr),
  347. #else
  348. std::exchange( fctx_, nullptr),
  349. #endif
  350. & p,
  351. detail::fiber_ontop< fiber, decltype(p) >).fctx };
  352. }
  353. explicit operator bool() const noexcept {
  354. return nullptr != fctx_;
  355. }
  356. bool operator!() const noexcept {
  357. return nullptr == fctx_;
  358. }
  359. bool operator<( fiber const& other) const noexcept {
  360. return fctx_ < other.fctx_;
  361. }
  362. #if !defined(BOOST_EMBTC)
  363. template< typename charT, class traitsT >
  364. friend std::basic_ostream< charT, traitsT > &
  365. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  366. if ( nullptr != other.fctx_) {
  367. return os << other.fctx_;
  368. } else {
  369. return os << "{not-a-context}";
  370. }
  371. }
  372. #else
  373. template< typename charT, class traitsT >
  374. friend std::basic_ostream< charT, traitsT > &
  375. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other);
  376. #endif
  377. void swap( fiber & other) noexcept {
  378. std::swap( fctx_, other.fctx_);
  379. }
  380. };
  381. #if defined(BOOST_EMBTC)
  382. template< typename charT, class traitsT >
  383. inline std::basic_ostream< charT, traitsT > &
  384. operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) {
  385. if ( nullptr != other.fctx_) {
  386. return os << other.fctx_;
  387. } else {
  388. return os << "{not-a-context}";
  389. }
  390. }
  391. #endif
  392. inline
  393. void swap( fiber & l, fiber & r) noexcept {
  394. l.swap( r);
  395. }
  396. typedef fiber fiber_context;
  397. }}
  398. #if defined(BOOST_MSVC)
  399. # pragma warning(pop)
  400. #endif
  401. #ifdef BOOST_HAS_ABI_HEADERS
  402. # include BOOST_ABI_SUFFIX
  403. #endif
  404. #endif // BOOST_CONTEXT_FIBER_H