Implement serial logging. Finish modularizing power management.
[monolithium.git] / sdk / thread.h
index b7b3cb06b2428a53e3d243da0f4c9e0c3d0fe628..e661bfb121921f25150aadf30c1ab38b4c932ecc 100644 (file)
@@ -24,6 +24,8 @@
 
 #include "defs.h"
 
+typedef dword_t (*thread_procedure_t)(void*);
+
 typedef qword_t affinity_t;
 
 typedef enum
@@ -51,6 +53,41 @@ typedef struct
     byte_t fpu_state[512];
 } thread_state_t;
 
+static inline void init_thread_stack(uintptr_t *stack_pointer, void *parameter)
+{
+    static const byte_t thread_end_code[] = {
+        /* push eax */
+        0x50,
+
+        /* push INVALID_HANDLE */
+        0x68,
+        INVALID_HANDLE & 0xFF,
+        (INVALID_HANDLE >> 8) & 0xFF,
+        (INVALID_HANDLE >> 16) & 0xFF,
+        (INVALID_HANDLE >> 24) & 0xFF,
+
+        /* mov eax, SYSCALL_TERMINATE_THREAD */
+        0xB8,
+        SYSCALL_TERMINATE_THREAD & 0xFF,
+        (SYSCALL_TERMINATE_THREAD >> 8) & 0xFF,
+        (SYSCALL_TERMINATE_THREAD >> 16) & 0xFF,
+        SYSCALL_TERMINATE_THREAD >> 24,
+
+        /* mov edx, esp */
+        0x8B, 0xD4,
+
+        /* int SYSCALL_INTERRUPT */
+        0xCD, SYSCALL_INTERRUPT
+    };
+
+    *stack_pointer -= (sizeof(thread_end_code) + sizeof(uintptr_t) - 1) & ~(sizeof(uintptr_t) - 1);
+    __builtin_memcpy((void*)*stack_pointer, thread_end_code, sizeof(thread_end_code));
+
+    uintptr_t end_code_addr = *stack_pointer;
+    push_to_stack(stack_pointer, (uintptr_t)parameter);
+    push_to_stack(stack_pointer, end_code_addr);
+}
+
 sysret_t syscall_open_thread(dword_t tid, handle_t *handle);
 sysret_t syscall_create_thread(handle_t process, thread_state_t *initial_state, dword_t flags, priority_t priority, handle_t *new_thread);
 sysret_t syscall_terminate_thread(handle_t thread, dword_t return_value);