Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple "Hello, world" program using Mach threads.
#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
You can’t perform that action at this time.