Run an Application in GDB Until an Exception Occurs - c++

I'm working on a multithreaded application, and I want to debug it using GDB.
Problem is, one of my threads keeps dying with the message:
pure virtual method called
terminate called without an active exception
Abort
I know the cause of that message, but I have no idea where in my thread it occurs. A backtrace would really be helpful.
When I run my app in GDB, it pauses every time a thread is suspended or resumed. I want my app to continue running normally until one of the threads dies with that exception, at which point everything should halt so that I can get a backtrace.

You can try using a "catchpoint" (catch throw) to stop the debugger at the point where the exception is generated.
The following excerpt From the gdb manual describes the catchpoint feature.
5.1.3 Setting catchpoints
You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++ exceptions or the loading of a shared library. Use the catch command to set a catchpoint.
catch event
Stop when event occurs. event can be any of the following:
throw
The throwing of a C++ exception.
catch
The catching of a C++ exception.
exec
A call to exec. This is currently only available for HP-UX.
fork
A call to fork. This is currently only available for HP-UX.
vfork
A call to vfork. This is currently only available for HP-UX.
load or load libname
The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX.
unload or unload libname
The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.
tcatch event
Set a catchpoint that is enabled only for one stop. The catchpoint is automatically deleted after the first time the event is caught.
Use the info break command to list the current catchpoints.
There are currently some limitations to C++ exception handling (catch throw and catch catch) in GDB:
If you call a function interactively, GDB normally returns control to you when the function has finished executing. If the call raises an exception, however, the call may bypass the mechanism that returns control to you and cause your program either to abort or to simply continue running until it hits a breakpoint, catches a signal that GDB is listening for, or exits. This is the case even if you set a catchpoint for the exception; catchpoints on exceptions are disabled within interactive calls.
You cannot raise an exception interactively.
You cannot install an exception handler interactively.
Sometimes catch is not the best way to debug exception handling: if you need to know exactly where an exception is raised, it is better to stop before the exception handler is called, since that way you can see the stack before any unwinding takes place. If you set a breakpoint in an exception handler instead, it may not be easy to find out where the exception was raised.
To stop just before an exception handler is called, you need some knowledge of the implementation. In the case of GNU C++, exceptions are raised by calling a library function named __raise_exception which has the following ANSI C interface:
/* addr is where the exception identifier is stored.
id is the exception identifier. */
void __raise_exception (void **addr, void *id);
To make the debugger catch all exceptions before any stack unwinding takes place, set a breakpoint on __raise_exception (see section Breakpoints; watchpoints; and exceptions).
With a conditional breakpoint (see section Break conditions) that depends on the value of id, you can stop your program when a specific exception is raised. You can use multiple conditional breakpoints to stop your program when any of a number of exceptions are raised.

FWIW, apparently, in gcc 4.1, the appropriate function name has changed and one must set a breakpoint in this function.
__cxa_pure_virtual

Only below one worked for me with gdb 8.3:
break _Unwind_RaiseException
"catch throw" or "break __cxx_throw" didn't work for me.

Set a breakpoint on __pure_virtual

Related

Two identical call stacks differ as they are shown by debugger

In my code I have a bug: I lock std::mutex twice.
I always run a debug version of my app.
There are 2 run cases:
I run it under the debugger. In this case I get exception with the following stack trace. It is ok.
I just run it without the debugger. I get Microsoft Visual C++ Runtime Library Debug Error window.
Then I connect the debugger to the process and click Retry.
I get the following stack trace which is really showing nothing:
Exactly the same bug. Two different stack traces. Why?
Addition #1: I have all the symbols specified correctly (including Microsoft Windows's one).
In the first stack you are in the application at the place the exception was raised. I guess you had set some form of 'break on exception' in debugger.
In the second stack you are in the application at the place the exception was caught. This occurs after the raise, in a catch block. Looks like you are in the catch block of the _Call_func frame.
So the two cases look different because they are different. Although is the same incident, you are looking at it in different moments.
If I'd venture a guess you have a callback of some sort in which you do not have a try/catch block and let exception propagate to CRT, which dutifully aborts the process because of unhandled exception.
Mandatory reading: A Crash Course on the Depths of Win32™ Structured Exception Handling to understand what occurred between the the two momements and how the first stack would transition into the second, if let unwind and proceed.
Exception Dispatching is causing this behavior:
When an exception occurs in user-mode code, the system uses the following search order to find an exception handler:
If the process is being debugged, the system notifies the debugger. For more information, see Debugger Exception Handling.
If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then searches through preceding stack frames in reverse order.
If no frame-based handler can be found, or no frame-based handler handles the exception, but the process is being debugged, the system notifies the debugger a second time.
If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.
In the first example, the debugger stops at 1), in the second example, the system stops at 4) and would usually kill the process. But since you have Visual Studio installed, it thinks you could be a developer and asks you to debug.
Between 1) where the exception is thrown and 4) where the process is about to die, a lot of things happened and the call stack is different.

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.

Can gdb be used to backtrace when exceptions are caught?

I have just started using c++ exceptions and want to get it right. What I have in mind is to generate some sort of backtrace information when exceptions are caught. Initially I had ideas similar to Call-stack for exceptions in C++ but eventually figured out that's not quite good.
I have also read How to generate a stacktrace when my gcc C++ app crashes but do not want to add more complexity to my current project. Since, I only need the backtracing when in debug mode, I was hoping I could be using gdb for that purpose.
My strategy has been to insert breakpoint in the catch block and then go up through the call stack to exactly pinpoint why the exception was thrown in the first place (or what caused it)? Unfortunatly, I cannot seem to be able to do this since when gdb reaches the breakpoint, it clears the call stack and I can only see main (that's where I catch). Is this supposed to happen or am I doing something wrong here?
Edit:
I just like to summarize the methods here for other folks:
1st Method (by paulsm4). Set a catchpoint via catch throw for catching on throw or catch catch for catching on catch! Then call backtrace
2nd Method (by aschepler) Set a breakpoint on __cxa_throw and then backtrace
3rd Method (in Qt Creator -- if you happen to use) You can easily set a breakpoint on throw or catch!
Edit_2: Using Qt Creator debugger, it seems that setting a breakpoint on __cxa_begin_catch is also an equivalent to catch catch :)
This this:
http://sourceware.org/gdb/onlinedocs/gdb/Set-Catchpoints.html
You can use catchpoints to cause the debugger to stop for certain
kinds of program events, such as C++ exceptions or the loading of a
shared library. Use the catch command to set a catchpoint.
So the answer should be "yes", and it should avoid the problems with the two links you cited.
Please post back if it helped! Personally, I've never tried this GDB feature myself :)
Summary of answers from the comments:
1st Method (by paulsm4). Set a catchpoint via catch throw for catching on throw or catch catch for catching on catch! Then call backtrace
2nd Method (by aschepler) Set a breakpoint on __cxa_throw and then backtrace
3rd Method (in Qt Creator -- if you happen to use) You can easily set a breakpoint on throw or catch!
Using Qt Creator debugger, it seems that setting a breakpoint on __cxa_begin_catch is also an equivalent to catch catch

Capturing OpenMP exceptions with SetUnhandledExceptionFilter

I have an exception handler set up using SetUnhandledExceptionFilter, which works fine. However, if I throw an exception from within OpenMP code, I get the standard "the application crashed" window and the handler is not called -- however, I can attach a debugger just fine and see that the call stack is ending with _CxxThrowException and continues into KernelBase.dll!RaiseException. I know that an OpenMP program which throws exceptions inside the parallel regions is wrong, but I'd still like to get a crash dump. How can I get my exception handler get called in this case?
Should be possible, especially as the debugger manges to get an "Unhandled exception" window, when attached to the application after the crash (i.e. I can get a nice stack trace and stuff.) This is on Windows 7 with VC++ 2010.
(Eventually, each thread actually calls my exception handler. If it crashes, and I select 'Debug', and then continue on each unhandled exception, the handler eventually gets called and it also manages to write out a meaningful minidump. Wtf?)
Interesting. Going out on a limb, I'll wager that the OpenMP concurrency runtime doesn't honor the SetUnhandledExceptionFilter (which will work for "standard" threads), and isn't integrated into this feature of Structured Exception Handling.
Note this warning from the MSDN page on Exception Handling in the Concurrency Runtime
To prevent abnormal termination of your application, make sure that your code handles exceptions when it calls into the runtime. Also handle exceptions when you call into external code that uses the Concurrency Runtime, for example, a third-party library.
Perhaps you can try wrapping your OpenMP stuff in the style of exception handling outlined above, and then see if you can re-package and throw it (outside of OpenMP context) to get caught by the filter?

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.