How to trap errors in DLL - c++

We have a .NET program that calls major functionality in unmanaged C++. I have a global exception catcher on the .NET side to catch any unhandled errors, but errors such as access violations in the unmanaged C++ DLLs can bring the program down without any logging. What is the best way to add "global" exception catcher in a DLL? Can I do this in DllMain?

You can use the /EHa exception handling flag, which will cause your C++ catch (...) to also catch structured exceptions, i.e. access violations. The downside of this is that you can't see what the exception was.
Alternatively, you can use a structed exception handler, __try { } __except(FILTER) { }, to handle structured exceptions. This allows you to output what type of exception was caught. However, there are limitations on what you can do in a function with a __try, such as no C++ exception handling or objects with destructors.
You can, however, get around the __try limitation by just calling a function containing the C++ exception handling and original code.
void main() {
__try {
Foo();
}
__except(EXCEPTION_EXECUTE_HANDLER) {
// Log some error regarding the structured exception
}
return 0;
}
void Foo() {
try {
SomeCPPObject bar(1,2);
DoSomeStuff();
}
catch (const std::exception&) {
// Log the C++ exception
}
}
Be careful, however, as you usually should not continue execution after a structured exception has been raised, as the state of your program could be completely destroyed. It's best to only use this type of exception handling to log an error before exiting.

The CLR cannot trap any hardware exceptions that are raised in threads started by the native code. The only way to do so is by using SetUnhandledExceptionFilter(), the callback you register is called by Windows before it is about to tear down the process.
Using this in a program that also has managed code is filled with traps and pitfalls. The CLR uses it too, it has to in order to generate exceptions like NullReferenceException and DivideByZeroException. You have to be very careful to not break that. Doing something like calling GetThreadId() and only filter exceptions of threads that you know are native ones is important. Next thing you'd do is, say, use MiniDumpWriteDump() to generate a minidump so that you can debug the crash.

Related

catch(...) is not catching an exception, my program is still crashing

I'm having a problem with a tester that my application crashes in initialization. I added more logging and exception handling but it still crashes with the generic "this program has stopped working" message rather than triggering my error handling.
Given my main() looks like this and has catch(...) under what circumstances would this not be triggered?
try{
simed::CArmApp app(0, cmd);
for(bool done = false;!done;)
{
done = !app.frame();
}
} catch(const std::runtime_error &e){
handleApplicationError(e.what());
return -1;
} catch(...) {
handleApplicationError("Unknown Error");
return -999;
}
My code is calling into a library doing OpenGL rendering which is where I believe things are going wrong.
If a C++ catch(...) block is not catching errors maybe it is because of a Windows error.
On Windows there is a concept called Structured Exception Handling which is where the OS raises "exceptions" when bad things happen such as dereferencing a pointer that is invalid, dividing by zero etc. I say "exceptions" because these are not C++ exceptions; rather these are critical errors that Windows defines in a C-style fashion - this is because Win32 was written in C so C++ exceptions were not viable.
See also:
Difference between a C++ exception and Structured Exception
try-except Statement
Method of getting a stack trace from an EXCEPTION_POINTERS struct
Update based on comments
If you want both C++ exception handing and SEH perhaps you could try the following (untested) code:
__try
{
try
{
// Your code here...
}
catch (std::exception& e)
{
// C++ exception handling
}
}
__except(HandleStructuredException())
{
// SEH handling
}
If an exception is thrown by the destructor of an object that is destroyed as a result of the stack unwinding to handle a different exception, the program will exit, catch(...) or not.
So far I know, there can be at least two situations where catch(...) cannot actually catch
More than 1 unhandled Exception: when an exception is raised before a previously occurred exception is handled, then c++ can not handle it, and application will crash.
Throwing exception that is not in exception specification list: if any method throws an exception which is not in the exception specification list (in any) then unexpected will be called which calls abort.
Do you declare any global objects?
If you have any objects created outside your main loop, that could explain why it is not caught ( it is not in your try-catch ).

Convert std::exception to EXCEPTION_POINTERS

I may be completely misunderstanding how to use the Google Breakpad API, and am open to comments / suggestions / rude remarks if that is the case. I am trying to call the following C++ function:
bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo);
I have a reference to a std::exception:
try {
return QApplication::notify(receiver, event);
} catch (std::exception &ex) {
eh_.WriteMinidumpForException(?????);
// ... do some more stuff and ultimately kill this process
}
(eh_ is a google_breakpad::ExceptionHandler.)
What do I put in the ?????
Background: The reason this is necessary (I think) is that Qt will not support an exception thrown in an event handler. It will not propagate correctly, and thus the minidump that Breakpad produces is completely useless because the actual context of the exception has been lost. Instead, you must catch all exceptions and handle them in the override of QApplication::notify(), which is what I am trying to do. In the case of an exception, I want to immediately write my minidump for that exception (which is sounds like WriteMinidumpForException will do) and then notify the user and quit the application. But I am not sure what to pass as the EXCEPTION_POINTERS* parameter.
In the MSVC compiler, C++ exceptions piggy-back onto the native Windows exception plumbing (SEH, Structured Exception Handling). There's a pretty big impedance mismatch though, the concept of an exception filter is doesn't have a good match in C++. By the time the catch handler catches an exception, the SEH exception is already handled and the stack unwound. The EXCEPTION_POINTERS info is gonzo. The exception filters actually exist, that's how it filters for the specific type you want to catch, they are however auto-generated by the compiler. No reasonable C++ syntax exists to make them useful.
You need to dip into the compiler support for handling SEH exceptions. Use the __try, __except keywords (__finally is optional) and have your filter catch the exception code for a C++ exception, 0xe04d5343 ('MSC'). You do however lose the ability to catch a specific C++ exception type, that plumbing is buried in the CRT without source. Put a C++ try inside the __try to fix that so your __except only sees exceptions that the C++ code didn't filter.
Using SetUnhandledExceptionFilter() is another way to do this btw, you really should consider it to act as the ultimate backstop of any unhandled exception, independent of the code location. It is the best way to create a minidump of a crashing app. Last but not least, creating a minidump of a crashing app inside the process itself isn't the best approach. There are plenty of odds that this won't work well, the process state can be corrupted pretty badly. One failure mode is having the process heap locked. Not unlikely considering that heap damage is a very common crash reason. Fix that with a "guard process", use a named event to signal it to make a minidump. Your exception filter only needs to set the event, that always works.
Windows SEH and c++ exceptions are not intertwined in any way - the easy way to solve this is to use your own __try __except wrapping e.g. a dereference of a null pointer.
Something like:
__try {
* (int *) 0 = 0;
}
__except
(
eh_.WriteMinidumpForException(GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER
)
{
}

Win32 Thread Exits Unexpectedly

I'm writing a C++ application. I realized that one of my worker threads may terminate unexpectedly. The (VS 2005) debug log says:
The thread 'Win32 Thread' (0x5d98) has
exited with code -858993460
(0xcccccccc).
I surrounded all the worker thread code with a try/catch block. So, if the reason was an exception, I would catch it. But I can't:
try{
...
Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here
...
} catch(exception& e) {
...
}
I have ten threads running concurrently, and only one of them gets crashed after some time, while the others continue running (and getting new [OCCI] connections).
Is there an exception type that is not caught by "exception"? Or what do I not know about threads/exceptions?
Thanks.
Not all errors raise C++ exceptions that can be caught with the C++ try...catch mechanism. For example, division by zero will not raise a C++ exception, but will cause undefined behaviour which may well make your application exit.
However, your code may be throwing things that are not derived from std::exception , so you may want to rewrite:
try{
Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here
}
catch(exception& e) {
// handle things derived from std::exception
}
catch ( ... ) {
// handle things that are not so derived
}
which will deal with things like throw "eeek!";
Also, but nothing to do with the problem, you should normally catch exceptins via a const reference.
Is there an exception type that is not caught by "exception"?
Yes, SEH exceptions. To catch them you need to either use __try/__except MSVC extension (see Structured Exception Handling), or write a global SEH/VEH handler (see SetUnhandledExceptionFilter and AddVectoredExceptionHandler).
The easiest way to find the problem would be to run your application under a debugger and enable breaking on Win32 Exceptions. Whenever a Win32 Exception is encountered, the application would break into the debugger and you can find out whats going wrong.
If you are not debugging and want to catch a win32 structured exception, you have to use _set_se_translator api to set a translator function. The registered function will be called whenever there is a Win32 exception and you get a chance to convert it to a C++ exception of your choice.
catch(exception& e) catches C++ exceptions derived from std::exception, and nothing else.
It doesn't catch C++ exceptions that are not derived from that class (If I do throw 42, it won't be caught for example), and it doesn't catch exceptions or errors at the system level.
Windows uses Structured Exception Handling (SEH) to signal errors, and those are not caught with a plain C++ catch statement. This might include errors like division by zero, as well as access violations or pretty much anything else that might go wrong at the OS or hardware level.
The docs have a nice explanation of how to catch SEH exceptions.
I found an important clue. When you close a handle with CloseHandle function, the thread exits with code 0xCCCCCCCC. With the help of this clue, I realized that in a very rare situation, I close my thread's handle even though the thread's working. Why does it exit exactly while getting connection? That also has an explanation, but it's related to the structure of the code, which may be difficult to explain here.
Thank you all, who brainstormed with me on the exceptions issue :$.

using catch(...) (ellipsis) for post-mortem analysis

Someone in a different question suggested using catch(...) to capture all otherwise unhandled - unexpected/unforseen exceptions by surrounding the whole main() with the try{}catch(...){} block.
It sounds like an interesting idea that could save a lot of time debugging the program and leave at least a hint of what happened.
The essence of the question is what information can be recovered that way (other than whatever debug globals I leave behind), and how to recover it (how to access and recognize whatever catch was called with)
Also, what caveats are connected with it. In particular:
will it play nice with threads that sprout later?
will it not break handling segfaults (captured elsewhere as signal)
will it not affect other try...catch blocks inevitably nested inside, that are there to handle expected exceptions?
Yes it is a good idea.
If you let an exception escape main it is implementation defined weather the stack is unwound before the application is shut down. So in my opinion it is essential you catch all exceptions in main.
The question then becomes what to do with them.
Some OS (See MS and SE) provide some extra debugging facilities so it is useful to just re-throw the exception after you catch it (because the stack has been unwound now anyway).
int main()
{
try
{
/// All real code
}
// I see little point in catching other exceptions at this point
// (apart from better logging maybe). If the exception could have been caught
// and fixed you should have done it before here.
catch(std::exception const& e)
{
// Log e.what() Slightly better error message than ...
throw;
}
catch(...) // Catch all exceptions. Force the stack to unwind correctly.
{
// You may want to log something it seems polite.
throw; // Re-throw the exception so OS gives you a debug opportunity.
}
}
will it play nice with threads that sprout later?
It should have no affect on threads. Usually you have to manually join any child threads to make sure that they have exited. The exact details of what happens to child threads when main exits is not well defined (so read your documentation) but usually all child threads will die instantly (a nasty and horrible death that does not involve unwinding their stacks).
If you are talking about exceptions in child threads. Again this is not well defined (so read your documentation) but if a thread exits via an exception (ie the function used to start the thread exits because of an exception and not a return) then this usually causes the application to terminate (same affect as above). So it is always best to stop ALL exceptions from exiting a thread.
will it not break handling segfaults (captured elsewhere as signal)
Signals are not affected by the exception handling mechanism.
But because signal handlers may place an odd structure on the stack (for their own return handling back to normal code) it is not a good idea to throw an exception from within a signal handler as this may cause unexpected results (and is definitely not portable).
will it not affect other try...catch blocks inevitably nested inside, that are there to handle expected exceptions?
Should have no effect on other handlers.
As far as I remember, catch(...) on Win32 catches also SEH exceptions, and you do not want to do that. If you get a SEH exception it's because something very scary happened (mainly access violations), so you can't trust your environment anymore. Almost everything you could do may fail with another SEH exception, so it's not even worth trying. Moreover, some SEH exceptions are intended to be caught by the system; more on this here.
So, my advice is to use a base exception class (e.g. std::exception) for all your exceptions, and catch just that type in the "catchall"; your code cannot be prepared to deal with other kind of exceptions, since they are unknown by definition.
A global try catch block is useful for production systems, in order to avoid displaying a nasty message to the user. During development I believe that are best avoided.
Regarding your questions:
I believe that a global catch block won't catch exceptions in another thread. Each thread has its own stack space.
I am not sure about this.
Nested try...catch blocks aren't affected and will execute as usual. An exception propagates up the stack, until it finds a try block.
You could try a solution I use if you're making a .net application. That captures all unhandled exceptions. I generally only enable the code (with #ifndef DEBUG) for production code when I'm not using the debugger.
It's worth pointing out as kgiannakakis mentions that you can't capture exceptions in other threads, but you can use the same try-catch scheme in those threads and post the exceptions back to the main thread where you can re-throw them to get a full stack track of what went wrong.
and how to recover it (how to access
and recognize whatever catch was
called with)
If you mean how to recover the type of exception that was thrown, you can chain catch blocks for specific types (proceeding from more specific to more general) before falling back to catch (...):
try {
...
} catch (const SomeCustomException& e) {
...
} catch (const std::bad_alloc& e) {
...
} catch (const std::runtime_error& e) {
// Show some diagnosic for generic runtime errors...
} catch (const std::exception& e) {
// Show some diagnosic for any other unhandled std::exceptions...
} catch (...) {
// Fallback for unknown errors.
// Possibly rethrow or omit this if you think the OS can do something with it.
}
Note that if you find yourself doing this in multiple places and want to consolidate code (maybe multiple main functions for separate programs), you can write a function:
void MyExceptionHandler() {
try {
throw; // Rethrow the last exception.
} catch (const SomeCustomException& e) {
...
}
...
}
int main(int argc, char** argv) {
try {
...
} catch (...) {
MyExceptionHandler();
}
}
A catch-all will not be terribly useful since there is no type/object information that you can query. However, if you can make sure all exceptions raised by your application are derived from a single base object, you can use a catch block for the base exception. But then that wouldn't be a catch-all.

Does it make sense to catch exceptions in the main(...)?

I found some code in a project which looks like that :
int main(int argc, char *argv[])
{
// some stuff
try {
theApp.Run();
} catch (std::exception& exc) {
cerr << exc.what() << std::endl;
exit(EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed.
Do you see any good reason to catch exceptions here ?
EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here...
If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called.
So, if you aren't running under the debugger, it's probably wise to catch everything: (...) as well as std::exception. Then your application code can clean up with RAII even on a fatal exception. In many such cases you don't actually need to clean up, since the OS will do it for you. But for instance you might prefer to disconnect cleanly from remote services where possible, and there might be resources external to the process, such as named pipes/mutexes, that you'd prefer to destroy rather than leaking.
Rethrowing the exception in main seems to me of limited use, since you've already lost the context in which it was originally thrown. I suppose that trapping an uncaught exception in the debugger is noisier than just logging the fault to std::cerr, so rethrowing would be the smart move if there's a chance of missing the logging.
If you want the debugger to trap unexpected conditions in debug mode, which in release mode throw an exception that eventually results in an exit, then there are other ways to do that than leaving the exception uncaught so that the debugger sees it. For example, you could use assert macros. Of course, that doesn't help with unexpected and unpredictable conditions, like hardware exceptions if you're using SEH on .NET.
Why do you say that the exception would be printed? This is not the typical behavior of the C++ runtime. At best, you can expect that its type gets printed.
In addition, this program leaves a "failure" status, whereas an exception might cause a termination-through-abort status (i.e. with a signal indicated in the exit code).
Try-catch in the main function hides the exception from debugger. I would say, it isn't good.
On the other hand, customers are not expected to have debuggers, so catching exceptions is nice. So it is good.
Personally, I catch all exceptions in main function, when making a release build, and I don't do that, when building a debug configuration.
A simple example of a situation where the stack did not unwind:
Why destructor is not called on exception?
A list of situations where exceptions may cause the application to terminate rather than unwind the stack.
Why destructor is not called on exception?
If an exception is not caught at any level and would escape main() then the implementation is allowed to call terminate() rather that unwinding the stack (yes this caught me by surprise as well).
As a result I always catch all exceptions in main().
int main()
{
try
{
}
catch(std::exception const& e)
{ /* LOG */
// optimally rethrow
}
catch(...) // Catch anything else.
{ /* LOG */
// optimally rethrow
}
}
To help with catching problems during debugging. Derive your exceptions from std::exception and then stick the break point in the constructor for std::exception.
This is a global catch block. It is common for displaying a nice and user understood message ('Internal error') instead of a cryptic exception print-out. This may be not evident from the specific code block, but it is in general a good idea.
Have a look at the C++ bible i.e. Stroustrup, he has an example which is also repeated in Applied C++ programming. The reasoning is:
int main(void)
{
try
{
// your code
}
catch ( /* YourPossibleExceptions i.e. barfs you expect may occur */ )
{
}
catch ( ... ) // unexpected errors, so you can exit gracefully
{
}
}
According the the Windows spec, the main isn't allowed to throw.
(practically it results into the message that asks if you want to send the bug-report to Microsoft)