libcommunism
Userspace cooperative threading library
SetJmp.h
Go to the documentation of this file.
1 #ifndef ARCH_SETJMP_SETJMP_H
2 #define ARCH_SETJMP_SETJMP_H
3 
4 #include "CothreadPrivate.h"
5 #include "CothreadImpl.h"
6 
7 #include <array>
8 #include <cstddef>
9 #include <mutex>
10 
11 #include <csetjmp>
12 
13 namespace libcommunism::internal {
25 class SetJmp final: public CothreadImpl {
27 
28  public:
29  SetJmp(const Entry &entry, const size_t stackSize = 0);
30  SetJmp(const Entry &entry, std::span<uintptr_t> stack);
31  SetJmp(std::span<uintptr_t> stack) : CothreadImpl(stack) {}
32  ~SetJmp();
33 
34  void switchTo(CothreadImpl *from) override;
35 
36  private:
40  struct EntryContext {
42  SetJmp *impl{nullptr};
43 
45  Cothread::Entry entry;
47  EntryContext(SetJmp *_impl, const Cothread::Entry &_entry) : impl(_impl),
48  entry(_entry) {}
49  };
50 
62  static auto JmpBufFor(CothreadImpl *thread) {
63  return reinterpret_cast<sigjmp_buf *>(static_cast<SetJmp *>(thread)->stack.data());
64  }
65 
66  static void AllocMainCothread();
67  static void InvokeCothreadDidReturnHandler(Cothread *from);
68  static void SignalHandlerSetupThunk(int);
69 
70  void Prepare(SetJmp *thread, const Cothread::Entry &entry);
71 
72  public:
82  static constexpr const size_t kStackAlignment{64};
83 
90  static constexpr const size_t kMainStackSize{512};
91 
96  static constexpr const size_t kDefaultStackSize{sizeof(uintptr_t) * 0x10000};
97 
98  private:
110  static thread_local std::array<uintptr_t, kMainStackSize> gMainStack;
111 
117  static EntryContext *gCurrentlyPreparing;
118 
128  static std::mutex gSignalLock;
129 
130  private:
132  bool ownsStack{false};
133 };
134 }
135 
136 #endif
std::function< void()> Entry
Type alias for an entry point of a cothread.
Definition: Cothread.h:27
Context switching utilizing the C library setjmp() and longjmp() methods.
Definition: SetJmp.h:25
static constexpr const size_t kStackAlignment
Definition: SetJmp.h:82
SetJmp(const Entry &entry, const size_t stackSize=0)
Definition: SetJmp.cpp:36
void switchTo(CothreadImpl *from) override
Definition: SetJmp.cpp:93
static constexpr const size_t kDefaultStackSize
Definition: SetJmp.h:96
SetJmp(std::span< uintptr_t > stack)
Definition: SetJmp.h:31
static constexpr const size_t kMainStackSize
Definition: SetJmp.h:90
Implementation details (including architecture/platform specific code) for the library.
Definition: Common.h:11
CothreadImpl * AllocKernelThreadWrapper()
Definition: Common.cpp:134
Abstract interface for a platform implementation of cothreads.
Definition: CothreadImpl.h:18
CothreadImpl(const Cothread::Entry &entry, const size_t stackSize=0)
Definition: CothreadImpl.h:29
std::span< uintptr_t > stack
Stack used by this cothread, if any.
Definition: CothreadImpl.h:88