How to intercept EXC_BAD_INSTRUCTION when unwrapping Nil

无人久伴 提交于 2019-12-03 03:11:31

TL;DR: Signal handler works fine when debugger is not attached.


In order to see what was happening, I set up a small demo project where I registered a signal handler for SIGUSR1 (one of the 'user-defined' signals available) and subsequently sent said signal to my process using the kill() function:

kill(0, SIGUSR1);

At first, I wasn't able to have Xcode's debugger jump to my signal handler, and instead it would stop at the line with the kill() call, highlighting it in red just as in my question.

After reading this question and its answers, it struck me that the debugger must pretty much depend on signals in order to be able to stop/resume program execution e.g., at breakpoints.

Using the symbolic breakpoint specified in one of the answers:

process handle SIGUSR1 -n true -p true -s false

...I was able to make Xcode not stop on this command:

kill(pid, SIGUSR1);

...and instead jump to my signal handler, all while debugging. I could even step inside the signal handler and execute its statements one by one; display an alert view from within it, etc.

Although I am not able to achieve the same result with SIGTRAP (or even SIGABRT), my signal handler does get called (and my crash log does get saved to disk!) when I launch my app without a debugger attached (e.g., by tapping the app's icon on the home screen) and have it throw a Swift runtime error like the one I mentioned in my question.


My guess on why I was able to intercept unrecognized selector sent to instance... seems to be that, as an Objective-C exception, it is an entirely different beast from Unix signals, and has nothing to do with the workings of the debugger (unless you set up an exception breakpoint for "Objective-C exceptions"?).

The very fact that the handler is set with the unrelated function NSSetUncaughtExceptionHandler() should have been a hint...

(I'm pretty much talking out of my limited knowledge here, so please feel free to add answers/comments with corrections as you see fit)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!