How can I efficiently catch and handle segmentation faults from C in a
CFM OSX Carbon application?
Background: I am making an OSX CFM Carbon application. I must call a
library function from a third party. Because of threading issues, the
function can occasionally crash. The function is a black box to me.
I want to be able to call the function but be able to "catch" if it
has crashed and supply an alternative return.
In Windows, I can use the simple Visual C and Intel C compilers
__try{} and __except.
/* Working Windows Example */
__try { x=DangerousFunction(y);}
__except(EXCEPTION_EXECUTE_HANDLER) {x=0.0;} /* whups, func crashed! */
I am trying to make the same kind of crash-catcher for OSX. I am using
pure C on a very large application. I call the function millions of
times per second, so efficiency is important too.
Here's what I have experimented with:
1) C++ exceptions. I am not sure if C++ exceptions catch the segfault
crashes. And my app is currently C. I could try wrappers and #ifdefs
to make it C++ but this is a lot of work for the app, and I don't
think C++ exceptions will catch the crash.
2) signal + setjump + longjmp. I thought this would work... it's what
it's designed for. But I set up my SEGV error handler [in fact I set
it up for every signal!] and it's never called during the crash. I can
manually test (and succeed) when calling raise(SEGV). But the crashes
don't seem to actually call it. My thoughts are that CFM applications
do NOT have access to the full BSD signals, only a subset, and that
Mach applications are necessary for the Real Thing.
3) MPSetExceptionHandler. Not well documented. I attempted to set a
handler. It compiled and ran, but did not catch the segfault. |