Last active
August 29, 2015 14:05
-
-
Save adityaramesh/7cf7ec54ce9e32041020 to your computer and use it in GitHub Desktop.
A simple "Hello, world" program using Mach threads.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unistd.h> | |
#include <mach/mach.h> | |
#include <mach/mach_vm.h> | |
#include <mach/mach_error.h> | |
#include <mach/mach_init.h> | |
#include <mach/mach_types.h> | |
#include <mach/mach_traps.h> | |
#include <mach/task.h> | |
#include <mach/thread_act.h> | |
#include <mach/thread_policy.h> | |
#include <mach/i386/thread_status.h> | |
void check(kern_return_t err) | |
{ | |
if (err == KERN_SUCCESS) return; | |
std::cerr << mach_error_string(err) << std::endl; | |
exit(EXIT_FAILURE); | |
} | |
void test() | |
{ | |
// pthread_set_self? | |
write(1, "Hello, world!\n", 14); | |
check(thread_terminate(mach_thread_self())); | |
} | |
int main() | |
{ | |
task_t task = mach_task_self(); | |
int stack_size = 65536; | |
vm_address_t stack = 0; | |
check(mach_vm_allocate(task, (mach_vm_offset_t*)&stack, stack_size, | |
VM_FLAGS_ANYWHERE)); | |
x86_thread_state64_t state; | |
mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT; | |
vm_address_t stack_ptr = stack + stack_size / 2 - 8; | |
state.__rip = (uintptr_t)test; | |
state.__rsp = (uintptr_t)stack_ptr; | |
state.__rbp = (uintptr_t)stack_ptr; | |
auto thread = thread_t{}; | |
check(thread_create_running(task, x86_THREAD_STATE64, | |
(thread_state_t)&state, x86_THREAD_STATE64_COUNT, &thread)); | |
// Give the thread a chance to run. | |
sleep(1); | |
printf("Done."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment