context.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #include "compiler.h"
  2. #include "defaults.h"
  3. #include "event.h"
  4. #include "thread.h"
  5. #include <cstdlib> //for abort()
  6. #if defined(_win_)
  7. #include "winint.h"
  8. #endif
  9. #if defined(_unix_)
  10. #include <cxxabi.h>
  11. #if !defined(Y_CXA_EH_GLOBALS_COMPLETE)
  12. namespace __cxxabiv1 {
  13. struct __cxa_eh_globals {
  14. void* caughtExceptions;
  15. unsigned int uncaughtExceptions;
  16. };
  17. extern "C" __cxa_eh_globals* __cxa_get_globals();
  18. } // namespace __cxxabiv1
  19. #endif
  20. #endif
  21. #include <util/stream/output.h>
  22. #include <util/generic/yexception.h>
  23. #define FROM_CONTEXT_IMPL
  24. #include "context.h"
  25. void ITrampoLine::DoRun() {
  26. }
  27. void ITrampoLine::DoRunNaked() {
  28. try {
  29. DoRun();
  30. } catch (...) {
  31. Cerr << "Uncaught exception in coroutine: " << CurrentExceptionMessage() << "\n";
  32. }
  33. abort();
  34. }
  35. static inline void Run(void* arg) {
  36. ((ITrampoLine*)arg)->DoRunNaked();
  37. }
  38. #if defined(USE_JUMP_CONT)
  39. extern "C" void __mylongjmp(__myjmp_buf env, int val) __attribute__((__noreturn__));
  40. extern "C" int __mysetjmp(__myjmp_buf env) __attribute__((__returns_twice__));
  41. namespace {
  42. class TStackType {
  43. public:
  44. inline TStackType(TArrayRef<char> range) noexcept
  45. #if defined(STACK_GROW_DOWN)
  46. : Data_(range.data() + range.size())
  47. #else
  48. : Data_(range.data() + STACK_ALIGN)
  49. #endif
  50. {
  51. ReAlign();
  52. }
  53. inline ~TStackType() = default;
  54. inline void ReAlign() noexcept {
  55. Data_ = AlignStackPtr(Data_);
  56. }
  57. template <class T>
  58. inline void Push(T t) noexcept {
  59. #if defined(STACK_GROW_DOWN)
  60. Data_ -= sizeof(T);
  61. *((T*)Data_) = t;
  62. #else
  63. *((T*)Data_) = t;
  64. Data_ += sizeof(T);
  65. #endif
  66. }
  67. inline char* StackPtr() noexcept {
  68. return Data_;
  69. }
  70. private:
  71. static inline char* AlignStackPtr(char* ptr) noexcept {
  72. #if defined(STACK_GROW_DOWN)
  73. return AlignDown(ptr, STACK_ALIGN);
  74. #else
  75. return AlignUp(ptr, STACK_ALIGN);
  76. #endif
  77. }
  78. private:
  79. char* Data_;
  80. };
  81. static inline void*& JmpBufReg(__myjmp_buf& buf, size_t n) noexcept {
  82. return (((void**)(void*)(buf))[n]);
  83. }
  84. static inline void*& JmpBufStackReg(__myjmp_buf& buf) noexcept {
  85. return JmpBufReg(buf, STACK_CNT);
  86. }
  87. static inline void*& JmpBufProgrReg(__myjmp_buf& buf) noexcept {
  88. return JmpBufReg(buf, PROGR_CNT);
  89. }
  90. static inline void*& JmpBufFrameReg(__myjmp_buf& buf) noexcept {
  91. return JmpBufReg(buf, FRAME_CNT);
  92. }
  93. #if defined(_x86_64_)
  94. // not sure if Y_NO_SANITIZE is needed
  95. Y_NO_SANITIZE("address")
  96. Y_NO_SANITIZE("memory") extern "C" void ContextTrampoLine(void*, void*, void*, void*, void*, void*, // register arguments, no defined value
  97. /* first argument passed through the stack */ void* t1,
  98. /* second argument passed through the stack */ void* t2) {
  99. Y_ASSERT(t1 == t2);
  100. Run(t1);
  101. }
  102. #else
  103. Y_NO_SANITIZE("address")
  104. Y_NO_SANITIZE("memory") static void ContextTrampoLine() {
  105. void** argPtr = (void**)((char*)AlignUp(&argPtr + EXTRA_PUSH_ARGS, STACK_ALIGN) + STACK_ALIGN);
  106. Y_ASSERT(*(argPtr - 1) == *(argPtr - 2));
  107. Run(*(argPtr - 1));
  108. }
  109. #endif
  110. } // namespace
  111. #if defined(USE_SANITIZER_CONTEXT)
  112. TContMachineContext::TSan::TSan() noexcept
  113. : TL(nullptr)
  114. {
  115. }
  116. TContMachineContext::TSan::TSan(const TContClosure& c) noexcept
  117. : NSan::TFiberContext(c.Stack.data(), c.Stack.size(), c.ContName)
  118. , TL(c.TrampoLine)
  119. {
  120. }
  121. void TContMachineContext::TSan::DoRunNaked() {
  122. AfterSwitch();
  123. TL->DoRunNaked();
  124. }
  125. #endif
  126. TContMachineContext::TContMachineContext(const TContClosure& c)
  127. #if defined(USE_SANITIZER_CONTEXT)
  128. : San_(c)
  129. #endif
  130. {
  131. TStackType stack(c.Stack);
  132. /*
  133. * arg, and align data
  134. */
  135. #if defined(USE_SANITIZER_CONTEXT)
  136. auto trampoline = &San_;
  137. #else
  138. auto trampoline = c.TrampoLine;
  139. #endif
  140. #if defined(_x86_64_)
  141. stack.ReAlign();
  142. // push twice to preserve alignment by 16
  143. stack.Push(trampoline); // second stack argument
  144. stack.Push(trampoline); // first stack argument
  145. stack.Push(nullptr); // fake return address
  146. #else
  147. stack.Push(trampoline);
  148. stack.Push(trampoline);
  149. stack.ReAlign();
  150. /*
  151. * fake return address
  152. */
  153. for (size_t i = 0; i < EXTRA_PUSH_ARGS; ++i) {
  154. stack.Push(nullptr);
  155. }
  156. #endif
  157. __mysetjmp(Buf_);
  158. JmpBufProgrReg(Buf_) = reinterpret_cast<void*>(ContextTrampoLine);
  159. JmpBufStackReg(Buf_) = stack.StackPtr();
  160. JmpBufFrameReg(Buf_) = nullptr;
  161. }
  162. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  163. if (Y_LIKELY(__mysetjmp(Buf_) == 0)) {
  164. #if defined(USE_SANITIZER_CONTEXT)
  165. next->San_.BeforeSwitch(&San_);
  166. #endif
  167. __mylongjmp(next->Buf_, 1);
  168. } else {
  169. #if defined(USE_SANITIZER_CONTEXT)
  170. San_.AfterSwitch();
  171. #endif
  172. }
  173. }
  174. #elif defined(_win_) && defined(_32_)
  175. void __stdcall ContextTrampoLine(void* arg) {
  176. Run(arg);
  177. }
  178. #else
  179. void ContextTrampoLine(void* arg) {
  180. Run(arg);
  181. }
  182. #endif
  183. #if defined(USE_FIBER_CONT)
  184. TContMachineContext::TContMachineContext()
  185. : Fiber_(ConvertThreadToFiber(this))
  186. , MainFiber_(true)
  187. {
  188. Y_ENSURE(Fiber_, TStringBuf("fiber error"));
  189. }
  190. TContMachineContext::TContMachineContext(const TContClosure& c)
  191. : Fiber_(CreateFiber(c.Stack.size(), (LPFIBER_START_ROUTINE)ContextTrampoLine, (LPVOID)c.TrampoLine))
  192. , MainFiber_(false)
  193. {
  194. Y_ENSURE(Fiber_, TStringBuf("fiber error"));
  195. }
  196. TContMachineContext::~TContMachineContext() {
  197. if (MainFiber_) {
  198. ConvertFiberToThread();
  199. } else {
  200. DeleteFiber(Fiber_);
  201. }
  202. }
  203. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  204. SwitchToFiber(next->Fiber_);
  205. }
  206. #endif
  207. #if defined(USE_GENERIC_CONT)
  208. #include <pthread.h>
  209. struct TContMachineContext::TImpl {
  210. inline TImpl()
  211. : TL(nullptr)
  212. , Finish(false)
  213. {
  214. }
  215. inline TImpl(const TContClosure& c)
  216. : TL(c.TrampoLine)
  217. , Finish(false)
  218. {
  219. Thread.Reset(new TThread(TThread::TParams(Run, this).SetStackSize(c.Stack.size()).SetStackPointer((void*)c.Stack.data())));
  220. Thread->Start();
  221. }
  222. inline ~TImpl() {
  223. if (Thread) {
  224. Finish = true;
  225. Signal();
  226. Thread->Join();
  227. }
  228. }
  229. inline void SwitchTo(TImpl* next) noexcept {
  230. next->Signal();
  231. Wait();
  232. }
  233. static void* Run(void* self) {
  234. ((TImpl*)self)->DoRun();
  235. return nullptr;
  236. }
  237. inline void DoRun() {
  238. Wait();
  239. TL->DoRun();
  240. }
  241. inline void Signal() noexcept {
  242. Event.Signal();
  243. }
  244. inline void Wait() noexcept {
  245. Event.Wait();
  246. if (Finish) {
  247. // TODO - need proper TThread::Exit(), have some troubles in win32 now
  248. pthread_exit(0);
  249. }
  250. }
  251. TAutoEvent Event;
  252. THolder<TThread> Thread;
  253. ITrampoLine* TL;
  254. bool Finish;
  255. };
  256. TContMachineContext::TContMachineContext()
  257. : Impl_(new TImpl())
  258. {
  259. }
  260. TContMachineContext::TContMachineContext(const TContClosure& c)
  261. : Impl_(new TImpl(c))
  262. {
  263. }
  264. TContMachineContext::~TContMachineContext() {
  265. }
  266. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  267. Impl_->SwitchTo(next->Impl_.Get());
  268. }
  269. #endif
  270. void TExceptionSafeContext::SwitchTo(TExceptionSafeContext* to) noexcept {
  271. #if defined(_unix_)
  272. static_assert(sizeof(__cxxabiv1::__cxa_eh_globals) == sizeof(Buf_), "size mismatch of __cxa_eh_globals structure");
  273. auto* eh = __cxxabiv1::__cxa_get_globals();
  274. ::memcpy(Buf_, eh, sizeof(Buf_));
  275. ::memcpy(eh, to->Buf_, sizeof(Buf_));
  276. #endif
  277. TContMachineContext::SwitchTo(to);
  278. }