MacOS Monterey 下启用 core dump

写在前面

在 MacOS Monterey 下,应用程序崩溃时,可以用 core dump 来调试。

启用 core dump

启用 core dump 功能:

sudo sysctl kern.coredump=1

确保你对 /cores 目录可写:

touch /cores/x
rm /cores/x

如果报错了,可以通过以下命令增加写权限:

sudo chmod 1775 /cores
sudo chmod o+w  /cores

创建 tmp.entitlements,这是为了后面对可执行程序进行重新签名时使用。

/usr/libexec/PlistBuddy -c "Add :com.apple.security.get-task-allow bool true" tmp.entitlements
File Doesn't Exist, Will Create: tmp.entitlements

上述准备工作只需要做一次即可。

产生 core dump

编写一个测试程序:

#include <stdlib.h>

int main() {
    system("ulimit -c unlimited");

    int *p = (void*)0;
    *p = 0;
    return 0;
}

编译程序,-g 让使得目标文件包含调试信息:

gcc -g test.c -o test

使用 tmp.entitlements 对程序进行重新签名:

codesign -s - -f --entitlements tmp.entitlements test
test: replacing existing signature

运行程序,制作事故现场:

./test
[1]    15049 segmentation fault (core dumped)  ./test

确保有 core dumped 字样输出,检查 core dump 文件:

$ ls -la /cores
drwxrwxrwt   4 root     admin         128 Jan 30 10:50 .
drwxr-xr-x  20 root     wheel         640 Dec  8 07:39 ..
-r--------   1 kamidox  admin  2968027136 Jan 30 10:50 core.15049

分析 core dump

使用 lldb 分析 core dump:

lldb -c /cores/core.15049
(lldb) target create --core "/cores/core.15049"
Core file '/cores/core.15049' (arm64) was loaded.

(lldb) bt
* thread #1, stop reason = signal SIGSTOP
  * frame #0: 0x000000010453ff88 test`main at test.c:7:8
    frame #1: 0x00000001048c90f4 dyld`start + 520
(lldb)

从输出 test.c:7:8 可以看到,第 7 行的程序导致程序崩溃。

参考资料

  1. https://blog.csdn.net/justidle/article/details/108459488
  2. https://stackoverflow.com/questions/70643336/core-dumps-arent-written-to-cores-on-mac-os-monterey

(完)


Post by Joey Huang under tools on 2022-01-30(Sunday) 09:38. Tags: tools,


Powered by Pelican and Zurb Foundation. Theme by Kenton Hamaluik.