我想使用 Mach异常端口 来处理在macOS上运行的所有任务(进程)的异常。 我的理解是,此时应使用 host_set_exception_ports
。但是,即使我用 sudo
执行程序,host_set_exception_ports
也返回 KERN_NO_ACCESS
(错误代码8)。我的实验性代码可以使用 task_set_exception_ports
处理单个任务的异常。
我已经查看了 host_set_exception_ports
的Mach内核代码。有一行代码从该函数返回 KERN_NO_ACCESS
。我有点难以理解那里发生了什么。它似乎检查我传递给 host_set_exception_ports
的异常掩码。我使用不同的异常掩码进行测试,但始终获得相同的负面结果。
我的问题:这是否意味着在用户空间应用程序中使用 host_set_exception_ports
存在一般限制?如果没有,我该如何在我的应用程序中设置主机异常端口以接收系统范围的异常?
下面的程序是一个最小示例,展示了该行为,否则没有太多用处。使用 gcc example.c
编译该程序,使用 sudo ./a.out
执行它。
#include <mach/mach.h>
#include <stdio.h>
#include <stdlib.h>
void catchMachExceptions() {
mach_port_t exception_port;
kern_return_t rc;
rc = mach_port_allocate(mach_task_self(),
MACH_PORT_RIGHT_RECEIVE,
&exception_port);
if (rc != KERN_SUCCESS) {
fprintf(stderr, "Unable to allocate exception port: %d\n", rc);
exit(-1);
}
rc = mach_port_insert_right(mach_task_self(),
exception_port,
exception_port,
MACH_MSG_TYPE_MAKE_SEND);
if (rc != KERN_SUCCESS) {
fprintf(stderr, "Unable to insert right: %d\n", rc);
exit(-1);
}
rc = host_set_exception_ports(mach_host_self(),
EXC_MASK_ALL,
exception_port,
EXCEPTION_STATE_IDENTITY,
MACHINE_THREAD_STATE);
if (rc != KERN_SUCCESS) {
fprintf(stderr, "Unable to set exception: %d\n", rc);
exit(-1);
}
}
int main(int argc, char **argv) {
catchMachExceptions();
}
host_set_exception_ports
存在一般限制"的答案是肯定的。 - Myst