Can gdb be used to backtrace when exceptions are caught? - c++

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

Related

Find Source of STL::Exception in basic_string

I am trying to track the source of a std::exception, in basic_string::erase, I wrapped all the locations where I am calling erase directly in try/catch and am not seeing any of these catch blocks be hit, so it must be being called internally from another basic_string method. The exception appears to be the result of a race condition in the code i am working with, so it is very difficult to reproduce, any thoughts on how I could detect and or get a stack trace from this exception? btw this is c++ code on an x86 linux box.
Thank you
You should try
(gdb) catch throw
Then gdb will trigger breakpoint each time exception is thrown. You'll see a callstack.
EDIT: This post is a good bunch of tricks for debugging exceptions: GDB: How to break when a specific exception type is thrown?

DUMP in unhandled C++ exception

In MSVC, how can I make any unhandled C++ exception (std::runtime_error, for instance) crash my release-compiled program so that it generates a dump with the full stack from the exception throw location?
I have installed NTSD in the AeDebug registry and can generate good dumps for things like memory access violation, so the matter here comes down to crashing the program correctly, I suppose.
Thanks in advance.
I finally cracked it down.
Use the set_terminate() function to register a handler for every thread
In you main function(), make it impossible for external DLLs (event Windows') to successfully call SetUnhandledExceptionFilter(). A great article on how to do that here: http://www.debuginfo.com/articles/debugfilters.html#overwrite .
As for the handle itself, it is quite straightforward:
void Terminate()
{
OutputDebugStringA("Terminate\r\n");
RaiseException(0xE0000010, EXCEPTION_NONCONTINUABLE, 0, 0);
}
Calling RaiseException() like the above example is enough to make the process crash and produce my mush desired dump.
Just so you know, the problem I was having was:
The IPHelper Windows API loads dynamically another Windows DLL
This DLL uses Windows own version of the C runtime (MSVCRT instead of MSVCRT90)
The new C++ runtime calls SetUnhandledExceptionFilter() on startup to catch C++ exceptions. Since the latest filter for C++ exceptions is the one who gets to call the handle set by set_terminate(), my handle wasn't called.
SetUnhandledExceptionFilter and DebugBreak should probably do the job.
Edit: oops, rereading, you want to deal with uncaught C++ exceptions. That would be a bit trickier to do well -- by the time you (normally) get wind of a C++ exception, it's already unwound the stack back to the level of the handler. You don't have any real way to know an exception has been thrown until a catch is invoked, but by then the stack has been unwound.
Look into using the Windows Debugger.
Windbg – wraps KD and NTSD with a decent UI.
Also check out ADPlus that comes with the Windows Debugger.
Here is a good place to start learning how to use it.

Can I stop COM from swallowing uncaught C++ exceptions in the callee process?

I am maintaining a project which uses inter-process COM with C++. At the top level of the callee functions there are try/catch statements directly before the return back through COM. The catch converts any C++ exceptions into custom error codes that are passed back to the caller through the COM layer.
For the purpose of debugging I want to disable this try/catch, and simply let the exception cause a crash in the callee process (as would normally happen with an uncaught C++ exception). Unfortunately for me the COM boundary seems to swallow these uncaught C++ exceptions and I don't get a crash.
Is there a way to change this behaviour in COM? Ie, I want it to allow the uncaught C++ exception to cause a crash in the callee process.
I want this to happen so that I can attach a debugger and see the context in which the exception is thrown. If I simply leave our try/catch in place, and breakpoint on the catch, then the stack has already unwound, and so this is too late for me.
The original "COM masters" who wrote this application are all either unavailable or can't remember enough details.
This just in, a year and a half after the question was asked -
Raymond Chen has written a post about "How to turn off the exception handler that COM 'helpfully' wraps around your server". Seems like the ultimate answer to the question. If not for the OP, for future readers.
I don't think you can disable this behaviour, however there is a way around it if you are using Visual Studio and don't mind getting flooded in exceptions. If you go to Debug>Exceptions in VS and select "When the exception is thrown>Break into the Debugger" for C++ exceptions, it will drop into the debugger at the point the exception is thrown. Unfortunately you then get to work out which exceptions you can ignore and which ones are of interest to you.
The default setting for this is "Continue" with "If the exception is not handled" being set to "break into the debugger". If it doesn't do that already this would suggest that you'll have to find out exactly where the exceptions are being caught.
If I understand correctly, your problem is essentially the inability to get a stack trace from a C++ exception. I've never tried it myself, but it should actually be possible to get the stack trace even from within the catch block.
See: Getting an exception call stack from the catch block
The article describes the process of getting the stack trace using a debugger, but if you don't want one to be attached you can create a dump in the catch clause (one way, another), and then go through the process on your leisure.
Have a look at Vectored Exception Handlers -- depending on your exact use case, VEH could be used to intercept SEH exception handling and force crashes/dumps/whatever.
You can set up a level 2 break in debugger with sxe/sxd -c2 eh that will catch only unhandled C++ exceptions. You can also attach the debugger on the fly to your process at load time using GFlags. Of course you'd have to give up the mickey mouse debugger and use the real deal.
What you need is to enable "break when an exception is thrown" in your debugger. This way you will stop immediately when an exception is thrown and have the entire call stack at your service.

Run an Application in GDB Until an Exception Occurs

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

I can't get my debugger to stop breaking on first-chance exceptions

I'm using Visual C++ 2003 to debug a program remotely via TCP/IP.
I had set the Win32 exception c00000005, "Access violation," to break into the debugger when thrown. Then, I set it back to "Use parent setting." The setting for the parent, Win32 Exceptions, is to continue when the exception is thrown.
Now, when I debug the program, it breaks each time that exception is thrown, forcing me to click Continue to let it keep debugging. How do I get it to stop breaking like this?
I'd like to support Will Dean's answer
An access violation sounds like an actual bug in your code. It's not something I'd expect the underlying C/++ Runtime to be throwing and catching internally.
The 'first-chance-exceptions' feature is so you can intercept things which get 'caught' in code, using the debugger, and have a look. If there's nothing 'catching' that exception (which makes sense, why on earth would you catch and ignore access violations?), then it will trigger the debugger regardless of what options you may have set.
Is this an exception that your code would actually handle if you weren't running in the debugger?
Ctrl+Alt+E (or Debug\Exceptions)
From there you can select which exceptions break.