libcommunism
Userspace cooperative threading library
Common.cpp
Go to the documentation of this file.
1 
4 #include "Common.h"
5 #include "CothreadPrivate.h"
6 
7 #include <algorithm>
8 #include <array>
9 #include <cstddef>
10 #include <exception>
11 #include <functional>
12 #include <memory>
13 #include <stdexcept>
14 #include <thread>
15 
16 using namespace libcommunism;
17 using namespace libcommunism::internal;
18 
19 thread_local std::array<uintptr_t, Amd64::kMainStackSize> Amd64::gMainStack;
20 
32 Amd64::Amd64(const Entry &entry, const size_t stackSize) : CothreadImpl(entry, stackSize) {
33  void *buf{nullptr};
34 
35  // round down stack size to ensure it's aligned before allocating it
36  auto allocSize = stackSize & ~(kStackAlignment - 1);
37  allocSize = allocSize ? allocSize : kDefaultStackSize;
38 
39  buf = AllocStack(allocSize);
40 
41  // create it as if we had provided the memory in the first place
42  this->stack = {reinterpret_cast<uintptr_t *>(buf), allocSize / sizeof(uintptr_t)};
43  this->ownsStack = true;
44 
45  Prepare(this, entry);
46 }
47 
56 Amd64::Amd64(const Entry &entry, std::span<uintptr_t> _stack) : CothreadImpl(entry, _stack) {
57  ValidateStackSize(_stack.size() * sizeof(uintptr_t));
58  Prepare(this, entry);
59 }
60 
65  if(this->ownsStack) {
66  DeallocStack(this->stack.data());
67  }
68 }
69 
76  Switch(static_cast<Amd64 *>(from), this);
77 }
78 
82 void Amd64::CothreadReturned() {
84 }
85 
91 void Amd64::DereferenceCallInfo(CallInfo *info) {
92  info->entry();
93  delete info;
94 }
95 
96 
97 
105  return new Amd64(Amd64::gMainStack);
106 }
static Cothread * Current()
Definition: Cothread.cpp:117
Architecture specific methods for working with cothreads on amd64 based systems.
Definition: Common.h:16
Amd64(const Entry &entry, const size_t stackSize=0)
Definition: Common.cpp:32
static constexpr const size_t kStackAlignment
Definition: Common.h:137
void switchTo(CothreadImpl *from) override
Definition: Common.cpp:75
static constexpr const size_t kDefaultStackSize
Definition: Common.h:143
Implementation details (including architecture/platform specific code) for the library.
Definition: Common.h:11
std::function< void(libcommunism::Cothread *)> gReturnHandler
Definition: Cothread.cpp:72
Main namespace for the libcommunism library.
Definition: Common.h:11
CothreadImpl * AllocKernelThreadWrapper()
Definition: Common.cpp:134
Abstract interface for a platform implementation of cothreads.
Definition: CothreadImpl.h:18
std::span< uintptr_t > stack
Stack used by this cothread, if any.
Definition: CothreadImpl.h:88