How to intercept EXC_BAD_INSTRUCTION when unwrapping Nil

前端 未结 1 611
忘了有多久
忘了有多久 2021-02-06 00:31

I am building some rudimentary crash logging system based on this blog post (Yes, I am aware of PLCRashReporter, and No, I ca

相关标签:
1条回答
  • 2021-02-06 00:46

    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)

    0 讨论(0)
提交回复
热议问题