Handling badly behaved libraries that terminate process - c++

I'm using LLVM right now. It has a disgusting habit of terminating the process on improper input, so that all the useful context and error messages and pretty much everything else of value is destroyed.
How can I intercept these process terminating calls so that I can perform some useful debugging? VS/Windows-specific answers are fine.

Can't you do something with std::set_terminate, set_unexpected (only for unexpected exception) and atexit ?

You can set up hooks for various things like abort, signal, unhandled exceptions and other unusual ways of exiting a program. If you provide your own handlers for there, you can just set a breakpoint in them to catch what's happening with a debugger attached, or save out minidumps/callstacks for when you're not attached.
There's lots of information on this kind of thing here:
http://randomascii.wordpress.com/2012/07/22/more-adventures-in-failing-to-crash-properly/

Related

How can I block in my Qt application signal SIGSEGV from cURL library?

My Qt app uses cURL library to send HTTP requests and sometimes cURL sends SIGSEGV and after that my app crashes.
Is it possible to catch this signal and prevent segmentation fault ?
TL;DR:
Don't attempt to block or ignore SIGSEGV. It will just bring you pain.
Explanation:
SIGSEGV means very bad things have happened, and your program has wandered into memory that it is not allowed to access. This means your program is utterly hosed.
Pardon my Canadian.
Your program is broken. You can't trust it to behave in any rational fashion anymore and should actually thank that SIGSEGV for letting you know this. As much as you don't want to see SIGSEGV, it's a hell of a lot better than the alternative of a broken program continuing to run and spewing out false information.
You can catch a SIGSEGV with a signal handler, but say you do catch and try to handle it. Odds are the program goes right back into the code that triggered the SIGSEGV and very likely raises it again as soon as the signal handler. Or does something else weird. Possibly something worse.
It's not really even worth catching SIGSEGV with a signal handler to make an attempt to output a message, because what's the message going to say? "Oh Smurf. Something very bad happened."?
So, yes, you can catch it, but you can't do anything to recover. The program is already too damaged to continue. That leaves preventing SIGSEGV in the first place, and that means fixing your code.
The best thing you can do is determine why the program crashed. The easiest way to do that is run your program with whatever debugger came with your development environment, wait for the crash, then inspect the backtrace for hints on how the program came to meet its doom.
Typically a link to Eric Lippert's How to debug small programs can be found right about here, and I can't think of a good reason to leave it out.
One other thing, though. cURL is a pretty solid library. Odds are overwhelmingly good that you are using it wrong or passed it bad information: a dead pointer, an unterminated C-style string, an pointer to an explosive function. I'd start by looking at how you are using cURL.
No, it's not. Instead, fix the bug and prevent the segmentation fault that way. Presumably your platform supplies some kind of debugger.

Is there a single catch-all-failures hook in c++?

I want that when and if the program will fail than it will be caught at this handler in order to do some guard notifications.
Is there a bottom handler or list of handlers that I need to register in order to be sure that a program cannot crash without passing through my handler?
Running on ubuntu and solution needed only to ubuntu
I need all kind of failure like exception memory allocation ...
The simple answer is that there is no single point where you can handle all errors in the program. You can add a try/catch (...) at in main to handle exceptions that occur after main is entered and before it completes. You can also add a handler for terminate in C++. Then depending on the OS you will also need to handle other situations differently (invalid memory references can be handled in unix/linux by handling SIG_SEGV, but that will not work in Windows --AFAIK; some other errors might trigger different signals that could or not be handled...) Further than that, there might be errors that still get unnoticed (say an invalid memory access that happens to hit a valid memory address... the program will be incorrect, but the error might go undetected)
C++ does not run in a virtual sandbox, thus there is nothing built-in to the language to catch this. You can certainly build one yourself (for example using exceptions), but it's up to your code to construct this from the foundation up.
The platform you're running on may have something you can use though. For example in Windows there is SetUnhandledExceptionFilter.
Of course all of this still depends on what it means to "crash".
On process startup, call fork. Use the parent to monitor the child. If it encounters a fatal error, the process will go away. You can detect this and do whatever you need to do when that happens. If the child wishes to terminate normally, it can simply kill its parent before terminating.
For a normal program exit you can register a handler with std::atexit().
For a program exit because of uncaught exceptions/... you can register a handler with std::set_terminate. If by "exception memory allocation" you mean a std::bad_alloc exception, than this handler should be triggered.
In Linux You need to respond to SIGABRT Signal. Your callback will be called whenever your app gets SIGABRT signal
signal(SIGABRT, &callback);
There are different Signals for different Scenarios such as SIGSEGV, SIGBUS that you ned to hook. you better hook them in different callbacks and check which error goes into what. because one error might come due to multiple problems.
No. If the process is killed with a SIGKILL, for example, no handler will be run.
P.S. FYI, this has nothing to do with the SPOF.
You can put a try/catch(...) block at the top level to catch all exceptions. But there are other ways for the program to be terminated and the ways of catching these aren't portable. On Unix-based systems you'll have to create signal handlers but even those won't stop kill -9.

Function guaranteed to be called in C++ during abrupt termination or exit

What function in C++ is guaranteed to be called during abrupt termination or exit which can perform the clean up activity ..
Depending on what you mean by "abrupt termination" there are several different options:
Global destructors will be called upon normal termination (return from main, or call to exit()).
atexit() registers a function to be called on normal termination.
std::set_terminate registers a function that will be called when an exception is thrown but not caught, or when "exception handling has to be terminated for some other reason".
sigaction() registers functions to be called when your program receives signals, many of which will normally abruptly terminate your program. Signal handlers may be called when the program is in an internally-inconsistent state, and therefore are extremely limited in what they can do. For instance, they cannot do anything that might allocate memory. Also, this API is not available on Windows; there are equivalents but I am not familiar with them.
Note that all operating systems in common use provide at least one way to abruptly terminate your program that cannot be intercepted from your code. For instance, Unix has signal 9 (SIGKILL) which you can't register a handler for. This is a feature, not a bug. You, the user, need a way to make a process go away even if it has done everything in its power to make itself indestructible. Furthermore, no code can protect your process when the user's pet rabbit gnaws through the power cord on the computer. Because of this, it might be a better use of your time to design your program to recover from crashes cleanly, rather than trying to clean up when a crash happens. See this article on "crash-only design" for more about that.
Read about atexit here. However it will not be called in all cases (for example, calling abort will not trigger the function you registered with atexit).
You can implement your own signal handler, then all the signals will pass there and you can do whatever for each of them.
You are looking for set_terminate().
http://www.cplusplus.com/reference/std/exception/set_terminate/
There are other similar function in the same header, that are usable for complementary scenarios.
int main()
{
try
{
// all your code here
}
catch(...)
{
// cleanup
}
return 0;
}
What environment you're working in? by abrupt do you mean Ctrl+C or kill -9 signal?
On unix/linux you can mask some signals and provide handlers, but as far as I am aware, you cannot mask all signal (9 is an example of a signal that can't be masked, and it'll kill your process abruptly)
Some even lower level overriding on OS operation could be available, but I'm not familiar with that.
I am not an expert and I just know some few things about C++, but I know you can create handles in Unix and C in order to detect a concrete signal and then, execute a function and later, terminate the program by "exit(n)" for example.
You can do it using signal or sigaction, but the problem is that you only can use this method for any signal except SIGKILL or SIGSTOP.
Are you familiar with signal handling? I would recommend that you study that first and then come back with questions regarding it. It looks like a couple people have already alluded to it, but here is a good resource to check:
http://www.gnu.org/s/hello/manual/libc/Signal-Handling.html
Writing your own signal handlers will allow you to determine what you want to do when a particular signal is caught. As stated, there are some that can't be overridden, and for good reason. You don't want to let someone override kill -9 simply because a program that's impossible to kill could be created. However, a straight kill signal or something such as ctrl-c, ctrl-d, etc, can be caught and handled in the way of your choosing.
There is no function that captures all scenarios and works on all platfroms. If you need something for Windows you will have to handle SEH(Structured exception handling) as well. You will have to define and set handlers for various scenarios(SEH, C++ Exceptions, SIGABRT, Terminate etc.) that execute common cleanup code and. Check zack's response here for handling SIGABRT signals.
For SEH you can add a SE converter to handle SE excpetions and convert them to C++ exceptions, look at _set_se_translator for more information about how to handle SEH exceptions.
You can refer to this documentation for set_terminate handler and this is a good reference for set_unexpected.
You will have to write your own handler that will be called for every scenario.
In the end I would reccomend using some existing libraries for this purpose, I like crashrprt.

Catch unhandled exception of invisible thread

In my C++ application i use an activeX component that runs its own thread (or several I don't know). Sometimes this components throws exceptions. I would like to catch these exceptions and do recovery instead of my entire application crashing. But since I don't have access to its source code or thread I am unsure how it would be done.
The only solution I can think of is to run it in its own process. Using something like CreateProcess and then CreateRemoteThread, unsure how it could be implemented.
Any suggestion on how to go about solving this?
If the ActiveX component is launching its own threads, then there isn't a lot that you can do. You could set a global exception handler and try to swallow exceptions, but this creates a high likelihood that your program state will become corrupted and lead to bizarre "impossible" crashes down the road.
Running the buggy component in a separate process is the most robust solution, as you'll be able to identify and recover from fatal errors without compromising your own program state.
Try setting up an exception filter with SetUnhandledExceptionFilter().

How can I catch an application crash or exit in mshtml?

Our application is using mshtml. That dll is causing our application to exit ungracefully due to well known problems in mshtml since we don't install newer browsers on users' machines. We just use what they have already.
The SetUnhandledExceptionFilter() does not handle this, nor does a try/catch block around the calls into mshtml. The exception filter does catch other exceptions.
The exception settings are /EHa.
When I remote debug the crash I see:
unhandled exception - access violation
In mshtml but if I don't attach to the process with a debugger, the application just exits.
What do we need to do to catch the exception?
Edit:
This is an old version of IE6.
Seems to be that MSHTML functions passes necessary data to a separate thread. That separate thread processes your request and the exception takes place. That's why you cannot catch exception via try/catch block. You should check it in the debugger. If that is true the only way to catch exceptions from other threads is to set hooks for TerminateThread and TerminateProcess functions. Check out CApiHook class by Jeffrey Richter for that purpose(or other implementations). But it will make your program to be incompatible with /NXCOMPAT compiler flag.
Your second option is to install all important OS updates.
Almost there. It's not SetUnhandledExceptionFilter() but AddVectoredExceptionHandler you want. With that said, you can get the first shot at this exception.
Of course I'm wondering what you're going to do afterwards. TerminateThread is probably the only option you have, but that may very well deadlock MSHTML. So that needs killing too.