我试图写一个简单的" Hello,world!"在x86_64上使用Mach线程的程序。不幸的是,程序在我的机器上崩溃并出现分段故障,我似乎无法解决问题。我无法在线找到关于Mach线程的大量文档,但我提到了以下C file,它也使用了Mach线程。
据我所知,我正确地做了一切。我怀疑分段错误是因为我没有正确设置线程的堆栈,但我采用了与参考文件相同的方法,它具有以下代码。
// This is for alignment. In particular note that the sizeof(void*) is necessary
// since it would usually specify the return address (i.e. we are aligning the call
// frame to a 16 byte boundary as required by the abi, but the stack pointer
// to point to the byte beyond that. Not doing this leads to funny behavior on
// the first access to an external function will fail due to stack misalignment
state.__rsp &= -16;
state.__rsp -= sizeof(void*);
你知道我可能做错了什么吗?
#include <cstdint>
#include <iostream>
#include <system_error>
#include <unistd.h>
#include <mach/mach_init.h>
#include <mach/mach_types.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;
}
auto code = std::error_code{err, std::system_category()};
switch (err) {
case KERN_FAILURE:
throw std::system_error{code, "failure"};
case KERN_INVALID_ARGUMENT:
throw std::system_error{code, "invalid argument"};
default:
throw std::system_error{code, "unknown error"};
}
}
void test()
{
std::cout << "Hello from thread." << std::endl;
}
int main()
{
auto page_size = ::getpagesize();
auto stack = new uint8_t[page_size];
auto thread = ::thread_t{};
auto task = ::mach_task_self();
check(::thread_create(task, &thread));
auto state = ::x86_thread_state64_t{};
auto count = ::mach_msg_type_number_t{x86_THREAD_STATE64_COUNT};
check(::thread_get_state(thread, x86_THREAD_STATE64,
(::thread_state_t)&state, &count));
auto stack_ptr = (uintptr_t)(stack + page_size);
stack_ptr &= -16;
stack_ptr -= sizeof(void*);
state.__rip = (uintptr_t)test;
state.__rsp = (uintptr_t)stack_ptr;
state.__rbp = (uintptr_t)stack_ptr;
check(::thread_set_state(thread, x86_THREAD_STATE64,
(::thread_state_t)&state, x86_THREAD_STATE64_COUNT));
check(::thread_resume(thread));
::sleep(1);
std::cout << "Done." << std::endl;
}
参考文件使用C ++ 11;如果使用GCC或Clang进行编译,则需要提供std=c++11
标志。