diff options
author | johannst <johannes.stoelp@gmail.com> | 2020-09-29 02:06:41 +0200 |
---|---|---|
committer | johannst <johannes.stoelp@gmail.com> | 2020-09-29 02:06:41 +0200 |
commit | fc83627b14536d0b13b2dd751d09cecbea9db378 (patch) | |
tree | 68d42350261fb7769615ceaa8af4187eb2dc571e /lib/arch/x86_64/init_stack.cc | |
parent | 38d7af6768871a5d285e776bbcfe18b6e7440cfb (diff) | |
download | matcha-threads-fc83627b14536d0b13b2dd751d09cecbea9db378.tar.gz matcha-threads-fc83627b14536d0b13b2dd751d09cecbea9db378.zip |
move thread init into arch/
Diffstat (limited to 'lib/arch/x86_64/init_stack.cc')
-rw-r--r-- | lib/arch/x86_64/init_stack.cc | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/lib/arch/x86_64/init_stack.cc b/lib/arch/x86_64/init_stack.cc new file mode 100644 index 0000000..748fb56 --- /dev/null +++ b/lib/arch/x86_64/init_stack.cc @@ -0,0 +1,33 @@ +#include <cassert> +#include <cstdint> // uintN_t + +extern "C" void thread_create(); + +void* init_stack(void* stack_ptr, void (*entry)(void*), void* ctx) { + static_assert(sizeof(uint64_t) == sizeof(std::uintptr_t), "Pointer must be 64bit!"); + + // Setup initial stack frame which will be popped when yielding + // first time into the thread. + // Basic idea is to yield into Thread::entry() function which will + // then call the user function. + + uint64_t* stack = static_cast<uint64_t*>(stack_ptr); + // Arguments for `thread_create`. + *(--stack) = reinterpret_cast<uint64_t>(ctx); + *(--stack) = reinterpret_cast<uint64_t>(entry); + + // Yield epilogue. + *(--stack) = reinterpret_cast<uint64_t>(thread_create); // Return address + *(--stack) = static_cast<uint64_t>(0); // rbp + + // Callee saved registers. + *(--stack) = static_cast<uint64_t>(0); // rbx + *(--stack) = reinterpret_cast<uint64_t>(static_cast<uint64_t*>(stack_ptr) - 4); // rbp + *(--stack) = static_cast<uint64_t>(0); // r12 + *(--stack) = static_cast<uint64_t>(0); // r13 + *(--stack) = static_cast<uint64_t>(0); // r14 + *(--stack) = static_cast<uint64_t>(0); // r15 + + assert((reinterpret_cast<std::uintptr_t>(stack) & 0xf) == 0); // 16byte aligned + return static_cast<void*>(stack); +} |