fiber_fcontext.hpp 14 KB

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