context.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. }
  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. }
  111. TContMachineContext::TSan::TSan() noexcept
  112. : TL(nullptr)
  113. {
  114. }
  115. TContMachineContext::TSan::TSan(const TContClosure& c) noexcept
  116. : NSan::TFiberContext(c.Stack.data(), c.Stack.size(), c.ContName)
  117. , TL(c.TrampoLine)
  118. {
  119. }
  120. void TContMachineContext::TSan::DoRunNaked() {
  121. AfterSwitch();
  122. TL->DoRunNaked();
  123. BeforeFinish();
  124. }
  125. TContMachineContext::TContMachineContext(const TContClosure& c)
  126. #if defined(_asan_enabled_) || defined(_tsan_enabled_)
  127. : San_(c)
  128. #endif
  129. {
  130. TStackType stack(c.Stack);
  131. /*
  132. * arg, and align data
  133. */
  134. #if defined(_asan_enabled_)
  135. auto trampoline = &San_;
  136. #else
  137. auto trampoline = c.TrampoLine;
  138. #endif
  139. #if defined(_x86_64_)
  140. stack.ReAlign();
  141. // push twice to preserve alignment by 16
  142. stack.Push(trampoline); // second stack argument
  143. stack.Push(trampoline); // first stack argument
  144. stack.Push(nullptr); // fake return address
  145. #else
  146. stack.Push(trampoline);
  147. stack.Push(trampoline);
  148. stack.ReAlign();
  149. /*
  150. * fake return address
  151. */
  152. for (size_t i = 0; i < EXTRA_PUSH_ARGS; ++i) {
  153. stack.Push(nullptr);
  154. }
  155. #endif
  156. __mysetjmp(Buf_);
  157. JmpBufProgrReg(Buf_) = reinterpret_cast<void*>(ContextTrampoLine);
  158. JmpBufStackReg(Buf_) = stack.StackPtr();
  159. JmpBufFrameReg(Buf_) = nullptr;
  160. }
  161. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  162. if (Y_LIKELY(__mysetjmp(Buf_) == 0)) {
  163. #if defined(_asan_enabled_) || defined(_tsan_enabled_)
  164. next->San_.BeforeSwitch(&San_);
  165. #endif
  166. __mylongjmp(next->Buf_, 1);
  167. } else {
  168. #if defined(_asan_enabled_)
  169. San_.AfterSwitch();
  170. #endif
  171. }
  172. }
  173. #elif defined(_win_) && defined(_32_)
  174. void __stdcall ContextTrampoLine(void* arg) {
  175. Run(arg);
  176. }
  177. #else
  178. void ContextTrampoLine(void* arg) {
  179. Run(arg);
  180. }
  181. #endif
  182. #if defined(USE_FIBER_CONT)
  183. TContMachineContext::TContMachineContext()
  184. : Fiber_(ConvertThreadToFiber(this))
  185. , MainFiber_(true)
  186. {
  187. Y_ENSURE(Fiber_, TStringBuf("fiber error"));
  188. }
  189. TContMachineContext::TContMachineContext(const TContClosure& c)
  190. : Fiber_(CreateFiber(c.Stack.size(), (LPFIBER_START_ROUTINE)ContextTrampoLine, (LPVOID)c.TrampoLine))
  191. , MainFiber_(false)
  192. {
  193. Y_ENSURE(Fiber_, TStringBuf("fiber error"));
  194. }
  195. TContMachineContext::~TContMachineContext() {
  196. if (MainFiber_) {
  197. ConvertFiberToThread();
  198. } else {
  199. DeleteFiber(Fiber_);
  200. }
  201. }
  202. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  203. SwitchToFiber(next->Fiber_);
  204. }
  205. #endif
  206. #if defined(USE_GENERIC_CONT)
  207. #include <pthread.h>
  208. struct TContMachineContext::TImpl {
  209. inline TImpl()
  210. : TL(nullptr)
  211. , Finish(false)
  212. {
  213. }
  214. inline TImpl(const TContClosure& c)
  215. : TL(c.TrampoLine)
  216. , Finish(false)
  217. {
  218. Thread.Reset(new TThread(TThread::TParams(Run, this).SetStackSize(c.Stack.size()).SetStackPointer((void*)c.Stack.data())));
  219. Thread->Start();
  220. }
  221. inline ~TImpl() {
  222. if (Thread) {
  223. Finish = true;
  224. Signal();
  225. Thread->Join();
  226. }
  227. }
  228. inline void SwitchTo(TImpl* next) noexcept {
  229. next->Signal();
  230. Wait();
  231. }
  232. static void* Run(void* self) {
  233. ((TImpl*)self)->DoRun();
  234. return nullptr;
  235. }
  236. inline void DoRun() {
  237. Wait();
  238. TL->DoRun();
  239. }
  240. inline void Signal() noexcept {
  241. Event.Signal();
  242. }
  243. inline void Wait() noexcept {
  244. Event.Wait();
  245. if (Finish) {
  246. // TODO - need proper TThread::Exit(), have some troubles in win32 now
  247. pthread_exit(0);
  248. }
  249. }
  250. TAutoEvent Event;
  251. THolder<TThread> Thread;
  252. ITrampoLine* TL;
  253. bool Finish;
  254. };
  255. TContMachineContext::TContMachineContext()
  256. : Impl_(new TImpl())
  257. {
  258. }
  259. TContMachineContext::TContMachineContext(const TContClosure& c)
  260. : Impl_(new TImpl(c))
  261. {
  262. }
  263. TContMachineContext::~TContMachineContext() {
  264. }
  265. void TContMachineContext::SwitchTo(TContMachineContext* next) noexcept {
  266. Impl_->SwitchTo(next->Impl_.Get());
  267. }
  268. #endif
  269. void TExceptionSafeContext::SwitchTo(TExceptionSafeContext* to) noexcept {
  270. #if defined(_unix_)
  271. static_assert(sizeof(__cxxabiv1::__cxa_eh_globals) == sizeof(Buf_), "size mismatch of __cxa_eh_globals structure");
  272. auto* eh = __cxxabiv1::__cxa_get_globals();
  273. ::memcpy(Buf_, eh, sizeof(Buf_));
  274. ::memcpy(eh, to->Buf_, sizeof(Buf_));
  275. #endif
  276. TContMachineContext::SwitchTo(to);
  277. }