C++ 马赫螺纹不适用于x86_64
我正在尝试使用x86_64上的Mach线程编写一个简单的“Hello,world!”程序。不幸的是,程序在我的机器上由于分段错误而崩溃,我似乎无法解决这个问题。我在网上找不到太多关于Mach线程的文档,但我参考了以下也使用Mach线程的文档 据我所知,我做的每件事都是正确的。我怀疑分段错误是因为我没有正确设置线程堆栈,但我采用了与参考文件相同的方法,其中包含以下代码C++ 马赫螺纹不适用于x86_64,c++,multithreading,macos,mach,C++,Multithreading,Macos,Mach,我正在尝试使用x86_64上的Mach线程编写一个简单的“Hello,world!”程序。不幸的是,程序在我的机器上由于分段错误而崩溃,我似乎无法解决这个问题。我在网上找不到太多关于Mach线程的文档,但我参考了以下也使用Mach线程的文档 据我所知,我做的每件事都是正确的。我怀疑分段错误是因为我没有正确设置线程堆栈,但我采用了与参考文件相同的方法,其中包含以下代码 // This is for alignment. In particular note that the sizeof(void
// 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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效检查(内核返回错误)
{
if(err==KERN_SUCCESS){
返回;
}
自动代码=std::error\u code{err,std::system\u category()};
开关(错误){
案例KERN_故障:
抛出std::system_错误{code,“failure”};
case KERN_无效_参数:
抛出std::system_错误{code,“无效参数”};
违约:
抛出std::系统错误{code,“未知错误”};
}
}
无效测试()
{
std::cout它是如何崩溃的?这是你的一个例外吗?@GradyPlayer不,这是一个分段错误。它发生在调用sleep之后,可能是因为创建的线程触发了访问冲突。