I am writing a program which does unit testing via the CUTE library and have a function which just needs to be checked if the program crashes when calling it.
I'v already tried a try-catch block like :
try
{
myfunc();
}
catch(...)
{
}
But this just handles exceptions and is of no use when no exception is called (i.e. abort() ).
So is there a way to just check if there is a crash resp. informing me where the crash happened (line number, ...)?
By handling SIGABRT. Or maybe register your handler via atexit functions (see also
c++ abort override)
Just use the debugger in your IDE. Or else, use a debugging tool like GDB or Valgrind.
Related
In lldb I'd like to break before C++ throws the exception, on when the actual signal is generated. I'd like to do this for any type of exception.
The following command will break on the C++ throw catcher
break set -E c++
I'd like to break on the cause of the exception and ignore the C++ throw/catch as if the application was crashing. I'd also like to do this for applications without source.
Is there any lldb voodoo I can use here?
I'm not entirely sure what you are asking.
Exceptions throws in C++ do two things, create the exception object, and then directly call some runtime routine (__cxa_throw on most Unixen) to implement the unwinding. The latter is the point where the exception breakpoint stops. There isn't any more preliminary than this that you could hook onto.
You could try breaking when the exception object is allocated. On OS X & Linux this is __cxa_allocate_exception, but I don't know if that will always get called or if there are alternate ways to make the exception... I don't see how you would gain much from that, however, it's just a couple of instructions later that you'll see the call to the throw method.
But maybe if you describe the problem you are actually trying to solve, we can answer more helpfully...
We're on Windows and we want to get a crash dump (possibly using MiniDumpWriteDump) for all scenarios where our application exit's unexpectedly.
So far we have identified, and set up, the following:
SetUnhandledExceptionFilter for unhandled exception (Win32 as well as "normal" C++ ones.)
_set_invalid_parameter_handler for the CRT invalid argument handling
_set_abort_behaviorplus a SIGABRT handler to account for calls to abort()
Is there anything we missed? (Modulo some code non-legitimately calling ExitProcess, TerminateProcess or one of the exit variants.)
I'll note that this question here is orthogonal to how a crash dump is then obtained. E.g., if you want a crash dump in case of abort, you always must use _set_abort_behaviour because otherwise abort just exits.
I'll also note that on Windows7+, not setting SetUHEF and just setting up the "correct" WER dump settings in the registry is often a viable way.
I use exactly the ones you've listed, plus _set_purecall_handler, plus this handy snippet of code:
void EnableCrashingOnCrashes()
{
typedef BOOL (WINAPI *tGetPolicy)(LPDWORD lpFlags);
typedef BOOL (WINAPI *tSetPolicy)(DWORD dwFlags);
static const DWORD EXCEPTION_SWALLOWING = 0x1;
const HMODULE kernel32 = LoadLibraryA("kernel32.dll");
const tGetPolicy pGetPolicy = (tGetPolicy)GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy");
const tSetPolicy pSetPolicy = (tSetPolicy)GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy");
if(pGetPolicy && pSetPolicy)
{
DWORD dwFlags;
if(pGetPolicy(&dwFlags))
{
// Turn off the filter
pSetPolicy(dwFlags & ~EXCEPTION_SWALLOWING);
}
}
}
Source:
http://randomascii.wordpress.com/2012/07/05/when-even-crashing-doesnt-work/
These other articles on his site also helped me understand this:
http://randomascii.wordpress.com/2011/12/07/increased-reliability-through-more-crashes/
http://randomascii.wordpress.com/2012/07/22/more-adventures-in-failing-to-crash-properly/
SetUnhandledExceptionFilter is emphatically not enough to capture all unexpected exits. If an application accidentally calls a pure virtual function then a dialog will pop up. The application will hang, but not crash. Since there is no exception neither SetUnhandledExceptionFilter nor WER can help. There are a few variations on this theme.
Worse yet is the weirdness if you crash in a kernel callback such as a WindowProc. If this happens in a 32-bit application on 64-bit Windows then the exception is caught by the OS and execution continues. Yes, the crash is silently handed. I find that terrifying.
http://randomascii.wordpress.com/2012/07/05/when-even-crashing-doesnt-work/ should detail all of the tricks needed to handle these unusual cases.
To expand on all the answers here's what I found to work best for 100M+ installs:
SetErrorMode to prevent any WER dialogs showing up.
EnableCrashingOnCrashes
PreventSetUnhandledExceptionFilter
SetUnhandledExceptionFilter for system exceptions.
_set_invalid_parameter_handler for the CRT invalid argument handling
_set_abort_behavior plus a SIGABRT handler to account for calls to abort()
std::set_terminate and std::set_unexpected perhaps should also be mentioned.
And the most important part to get it all right:
all these handlers should call a function that executes under a mutex/critical section to ensure that if there are any other crashes happening in other threads at the same time they would all stop and wait instead of causing havoc.
signal handler for SIGABRT must set itself back as a SIGABRT handler! Without this if you get crashes happening at the same time from other threads you process will exit immediately without giving you any time to handle the crash.
actual handling of the error should ideally happen in another process, or at least in another thread that was started at the beginning of the process, otherwise you won't be able to handle low memory conditions or stackoverflow errors.
See setExceptionHandlers below for reference. Also, most likely you don't want to hook up all the handlers in debug builds or when IsDebuggerPresent.
#include <signal.h>
#include <windows.h>
#include <boost/thread/mutex.hpp>
void EnableCrashingOnCrashes();
void PreventSetUnhandledExceptionFilter();
static void exceptionHandler(EXCEPTION_POINTERS* excpInfo)
{
// your code to handle the exception. Ideally it should
// marshal the exception for processing to some other
// thread and waif for the thread to complete the job
}
static boost::mutex unhandledExceptionMx;
static LONG WINAPI unhandledException(EXCEPTION_POINTERS* excpInfo = NULL)
{
boost::mutex::scoped_lock lock(unhandledExceptionMx);
if (!excpInfo == NULL)
{
__try // Generate exception to get proper context in dump
{
RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
}
__except (exceptionHandler(GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER)
{
}
}
else
{
exceptionHandler(excpInfo);
}
return 0;
}
static void invalidParameter(const wchar_t* expr, const wchar_t* func,
const wchar_t* file, unsigned int line, uintptr_t reserved)
{
unhandledException();
}
static void pureVirtualCall()
{
unhandledException();
}
static void sigAbortHandler(int sig)
{
// this is required, otherwise if there is another thread
// simultaneously tries to abort process will be terminated
signal(SIGABRT, sigAbortHandler);
unhandledException();
}
static void setExceptionHandlers()
{
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter(unhandledException);
_set_invalid_parameter_handler(invalidParameter);
_set_purecall_handler(pureVirtualCall);
signal(SIGABRT, sigAbortHandler);
_set_abort_behavior(0, 0);
EnableCrashingOnCrashes();
PreventSetUnhandledExceptionFilter();
}
Tall order, just in brief:
You need not to use any other _set* functions, SetUnhandledExceptionFilter is enough for all.
C runtime functions like abort will disable the global exception handler, which you setup using SetUnhandledExceptionFilter. CRT will simply call this same function will NULL parameter, and your exception-handler is disabled (not called), if CRT is causing crash! What you can do? [X]
Disable all other running threads when the excption-handler gets called. Just lookup all threads using CreateToolhelp32Snapshot, and other functions. Look for this process, and suspend all other running threads (except current, ofcourse).
Use SEH or no-SEH, global-exception handler gets called unless CRT interfers. Not to worry (in MOST cases).
Do not any CLR in-between, it will not allow the exception handler to call, if any CLR/managed call (yes from C/C++) comes in between.
You cannot handle one exception - Stack Overflow! Think! Running under a debugger is only solution, see below.
There is more to it, which I haven't tried (not found usefulness) - Vectored Exception Handling.
One other approach is to run the application into a debugger, which you can craft yourself! In the debugger, you can catch ALL exceptions, just like VS debugger catches. See my article. But, you know, this is not proper approach.
EDIT: Just read the last content about process-termination. You shouldn't control that. In any case, you can just hook the required APIs, which would act as what you code for (like displaying message box).
[X] You need to use API hooking. I dont have link and details handy. You'd hook other related APIs, but primarily the SetUnhandledExceptionFilter (after you'd called it for you). You dummy (hooked) function will look like:
xxx SetUnhandledExceptionFilter_DUMMY(xxx)
{
// Dont do any thing
return NULL;
}
I dont have link and details of API hooking handy.
And why not attempt to make your application more safe?
Correct all warnings (yes, even level 4).
Use static analysis. VS itself has (in higher versions, though. Except 2012 - all variants have). Other SA tools are available.
Do careful code-reviewing. It pays!
Run and Debug your RELEASE build from the debugger. Use all features.
Look and correct all possible memory leaks.
Use defensive approach to programming. Rather than checking if null, defend it using ASSERT, or your own assert. Pack it with assertion, log, return from function.
I will add a workaround that one can use in certain scenarios when running on Windows 7:
Windows Error Reporting (WER) offers the option to write full memory dumps on app crash.
So, if you are fine with that, you "just" have to make sure that the crash scenarios you're actually interested in will trigger WER. ... Which, really, leads us back to this very question, but still ...
You can catch any exception with WER. As you have seen the CRT sometimes forces to call WER.
If you want to always catch excpetion in-process, you need to prevent the calling of SetUnhandledExceptionFilter(NULL) from the CRT. For more info see my blog entry: Improved “PreventSetUnhandledExceptionFilter”
Some C++ libraries call abort() function in the case of error (for example, SDL). No helpful debug information is provided in this case. It is not possible to catch abort call and to write some diagnostics log output. I would like to override this behaviour globally without rewriting/rebuilding these libraries. I would like to throw exception and handle it. Is it possible?
Note that abort raises the SIGABRT signal, as if it called raise(SIGABRT). You can install a signal handler that gets called in this situation, like so:
#include <signal.h>
extern "C" void my_function_to_handle_aborts(int signal_number)
{
/*Your code goes here. You can output debugging info.
If you return from this function, and it was called
because abort() was called, your program will exit or crash anyway
(with a dialog box on Windows).
*/
}
/*Do this early in your program's initialization */
signal(SIGABRT, &my_function_to_handle_aborts);
If you can't prevent the abort calls (say, they're due to bugs that creep in despite your best intentions), this might allow you to collect some more debugging information. This is portable ANSI C, so it works on Unix and Windows, and other platforms too, though what you do in the abort handler will often not be portable. Note that this handler is also called when an assert fails, or even by other runtime functions - say, if malloc detects heap corruption. So your program might be in a crazy state during that handler. You shouldn't allocate memory - use static buffers if possible. Just do the bare minimum to collect the information you need, get an error message to the user, and quit.
Certain platforms may allow their abort functions to be customized further. For example, on Windows, Visual C++ has a function _set_abort_behavior that lets you choose whether or not a message is displayed to the user, and whether crash dumps are collected.
According to the man page on Linux, abort() generates a SIGABRT to the process that can be caught by a signal handler. EDIT: Ben's confirmed this is possible on Windows too - see his comment below.
You could try writing your own and get the linker to call yours in place of std::abort. I'm not sure if it is possible however.
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 :$.
I have a Windows C++ console program, and if I don't call ReleaseDriver() at the end of my program, some pieces of hardware enter a bad state and can't be used again without rebooting.
I'd like to make sure ReleaseDriver() gets runs even if the program exits abnormally, for example if I hit Ctrl+C or close the console window.
I can use signal() to create a signal handler for SIGINT. This works fine, although as the program ends it pops up an annoying error "An unhandled Win32 exception occurred...".
I don't know how to handle the case of the console window being closed, and (more importantly) I don't know how to handle exceptions caused by bad memory accesses etc.
Thanks for any help!
Under Windows, you can create an unhandled exception filter by calling SetUnhandledExceptionFilter(). Once done, any time an exception is generated that is not handled somewhere in your application, your handler will be called.
Your handler can be used to release resources, generate dump files (see MiniDumpWriteDump), or whatever you need to make sure gets done.
Note that there are many 'gotchas' surrounding how you write your exception handler function. In particular:
You cannot call any CRT function, such as new
You cannot perform any stack-based allocation
If you do anything in your handler which causes an exception, Windows will immediately terminate your application by ripping the bones out of its back. You get no further chances to shut down gracefully.
You can call many Windows API functions. But you can't sprintf, new, delete... In short, if it isn't a WINAPI function, it probably isn't safe.
Because of all of the above, it is advisable to make all the variables in your handler function static variables. You won't be able to use sprintf, so you will have to format strings ahead of time, during initialization. Just remember that the machine is in a very unstable state when your handler is called.
If I'm not mistaken, you can detect if the console is closed or the program is terminated with Ctrl+C with SetConsoleCtrlHandler:
#include <windows.h>
BOOL CtrlHandler(DWORD)
{
MessageBox(NULL, "Program closed", "Message", MB_ICONEXCLAMATION | MB_OK);
exit(0);
}
int main()
{
SetConsoleCtrlHandler((PHANDLER_ROUTINE)&CtrlHandler, TRUE);
while (true);
}
If you are worried about exceptions, like bad_alloc, you can wrap main into a try block. Catch std::exception& which should ideally be the base class of all thrown exception, but you can also catch any C++ exception with catch (...). With those exceptions, though, not all is lost, and you should figure out what is being thrown and why.
Avoiding undefined behavior also helps. :)
You can't (guarantee code runs). You could lose power, then nothing will run. The L1 instruction cache of your CPU could get fried, then your code will fail in random ways.
The most sure way of running cleanup code is in a separate process that watches for exit of the first (just WaitForSingleObject on the process handle). A separate watchdog process is as close as you can get to a guarantee (but someone could still TerminateProcess your watchdog).