Is there a single catch-all-failures hook in c++? - 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.

Related

Windows: Handle segfaults in all threads

I'm looking for a way to catch segfaults and other errors anywhere in a program (which uses multiple threads, some of which are created by external libraries). I'm using Visual Studio 2013 with the Intel C++ Compiler 2015.
Some external DLL's - in some cases I've even seen this with Windows drivers - can contain bugs that are out of my control, and my software runs 24/7 - I need to be able to log a crash somewhere and restart my software.
So far, I found that you can set a signal handler which handles SIGSEGV and other signals. Based on what I read, under Linux this would do exactly what I need (handle this signal for all threads), but under Windows you need to set the signal handler for each thread separately. Since I'm not the one who creates all the threads (if I was, I could just use __try/__catch), this isn't really an option. On top of that, I'm seeing that when I set a signal handler in a thread and then cause a SIGSEGV it doesn't get handled by the handler, while the exact same code works fine in the main thread - not sure what's going on there (but even a fix for that wouldn't help, since I don't create all the threads, and looping through all existing threads in my process to set handlers sounds like a very bad idea).
So, is there a way to do this? Googling and searching here did not help - I found several people with similar questions but no answers that are usable in my situation.
Note: What I have now, which works perfectly in the main thread but not at all if I copy this same block of code to any thread:
SignalHandlerPointer previousHandlerSEGV = signal(SIGSEGV, SignalHandler);
int *a;
a = NULL;
*a = 0;
To get notified about all unhandled exceptions in a process you can call SetUnhandledExceptionFilter. The functionality is documented as:
Issuing SetUnhandledExceptionFilter replaces the existing top-level exception filter for all existing and all future threads in the calling process.
Inside the exception filter it is recommended to trigger a call to MiniDumpWriteDump (in an external process), to produce a mini dump for off-line analysis. You get to control the amount of information that is written into the mini dump (e.g. threads, modules, call stacks, memory). Most importantly, you can dump the call stack of the thread that raised the uncaught exception, at the time the exception is raised.
As an alternative, I believe some/most/all of this can be done automatically by registering for application recovery and restart.

Handling badly behaved libraries that terminate process

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/

Make Control-C behave like uncaught exception

Is there a way to make Control-C act like an exception was thrown. i.e. basically the program exits, but on the way up all the destructors are called?
Well, you need a signal handler catch SIGINT (SIGTERM, HUP why not as well?). You don't want to use threads for something simple like this, so use the standard "self-pipe trick": write a byte (the signal value) to one end of a socketpair in your signal handler, and your main loop (there's always a select loop in there somewhere) will asynchronously read the value back. It's at that point you throw, run away, follow ordinary quit procedure, do whatever you like. Everything gets unwound and destructed just as if you were quitting for any other reason in your main application loop.
This is generally impossible or hard to do. I believe that on some systems, like GNU/Linux, you could do that if you supplied -fnon-call-exceptions -fasynchronous-unwind-tables flags to GCC (untested).
Other than the above, you have basically two options:
Either you set some sort of flag in your signal handler that you will check somewhere else to see if SIGINT has been delivered. This is useful for both *NIX and Windows platforms.
On *NIX, if you are using threads in your application already, you can handle SIGINT using, e.g., sigwait() in a separate thread as a synchronous event and force your whole application to terminate orderly.
I would suggest using the 2nd option as that is usable as general approach to the problem on Windows as well. Windows inject a thread into application that execute a user supplied handle for Ctrl-C or Ctrl-Break. If you use the 2nd option, your application will be IMHO more portable.

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.

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.