Debugging asserts in Qt Creator - c++

When I hit a normal assert statement while debugging with Visual Studio I get the option to break into the debugger so I can see the entire stack trace and the local variables, not just the assert message.
Is it possible to do this with Qt Creator+mingw32 and Q_ASSERT/Q_ASSERT_X?

It's possible. Somehow the feature stopped working for me, but basically what you want is to stop on qFatal().
To ensure this happens, in qt Creator go to Tools -> Options -> Debugger -> GDB and select
"Stop when a qFatal is issued"

You can install a handler for the messages/warnings that Qt emits, and do your own processing of them. See the documentation for qInstallMsgHandler and the example they give there. It should be easy to insert a break in a custom message handler (or indeed, just assert on your own at that point). The one small drawback is that you'll be a bit further on down the stack than where the error actually occurred, but it is a simple matter to just step up the stack until you are at the proper frame.

It's possible. I have coded a BreakInDebugger function by hand and an assert macro that calls the function.
e.g: #define MyAssert(X) (BreakInDebugger();Q_ASSERT(X))

Related

Can you cause Qt to assert, segfault, or otherwise crash when a QObject::connect() fails?

I'm using Qt 4.8.x so I don't have access to the new connect interface from Qt5, but I want to be alerted better when a signal/slot connection fails because I misspelled a signal or slot name.
Currently, all Qt does is spit out an error message when the connection is attempted. However, my program has a lot of output on stdout so it is easy to miss these errors sometimes. Is it possible to force my application to crash via assert, segfault, or other method, when a connect statement fails?
Yes: set the QT_FATAL_WARNINGS environment variable to a non-zero value.
You can do this during development in Qt Creator by going to the Projects pane, click Run, then under "Run Environment" click Details, then click Add.
Edit to add: you can of course also implement some wrappers for QObject::connect, that will check its return value and assert() if it returns false.
I think at least one of the solutions in this question: Qt GUI app: warning if QObject::connect() failed? does what you need.
In particular, by using QErrorMessage::qtHandler you should be able to intercept those warnings and do whatever you want with them.

Debugger question

I have a bug I am chasing (I think its a deadlock). When I run the code it hangs without the debugger flagging an error, so after a while I try pressing the pause (break all) button. The debugger then reports "The process appears to be deadlocked...". I then can see that all the threads are held up at lines saying EnterCriticalSection except for one which is already inside a critical section. When I look at the thread that is inside the C.S. with the debugger I see a green arrow, accompanied by a tiny blue circle pointing at a line with GetWindowText... as below:
// stuff A
{
GetWindowText(editwin[a].child_window_handle,existing_text,MAX_TEXT_SIZE-1);
}
// stuff B
If I hover the mouse over the green arrow I see the text "this is the next statement to execute when this thread returns from the current function". Now this has stumped me because I don't know if it means that it is stuck inside "stuff A" and is waiting to come back or its stuck inside GetWindowText and has somehow got stuck inside that. The arguments to GetWindowText all look sensible to me. If I click on "step into" I get the message "Unable to step. The process has been soft broken".
EDIT: stuff A is in fact the statement:
if (buf_ptr != NULL)
Usually a green arrow beside a line of code means "this is the next line that would be executed, if not for the fact we're stuck somewhere in a deeper stack frame." However, VS makes it impossible to say for sure based on the info provided so far...
[EDIT - of course, deep knowledge of Win32 can provide a very good guess - see the answer by "mos" for a likely explanation based on the GetWindowText() API's known pitfalls]
As mentioned, what Visual Studio shows you is sometimes misleading. To get a closer view of exactly what is happening you need to turn off some non-helpful "features" that VS enables by default. In Tools -> Options -> Debugging -> General, make sure:
Enable address-level debugging = ON
Enable Just My Code = OFF
Enable Source Server support = ON
This should allow you to:
1) break on / step over / etc the exact instruction that's causing the deadlock
2) see the full stack trace up to that point, regardless of module(s)
3) see source code whenever available, assuming your symbol & source servers are configured correctly
Your problem is that GetWindowText actually sends a message to the other window and waits for it to return. If that window is owned by another thread that is waiting for a critical section, GetWindowText will wait forever.
You're stuck inside GetWindowText, and have created a deadlock.
As the previous responses suggest, your code is stuck inside "Stuff A".
Can I suggest another tool for your tool-belt?
I usually find it much easier to debug native synchronization problems using WinDbg.
just launch your program in WinDbg, point to the correct symbols and all the info will be right there for your investigation using the !locks, !cs and k commands.
If you're new to WinDbg, you'll find that the internet is full with information about it. I recommend reading Advanced Windows Debugging as well.
It's a little bit difficult to start, comparing to the user friendly VS Debugger but every minute you'll invest in learning how to use it will save you hours of debugging further down the road.
Assuming your question is "Is this normal", then yes, the debugger usually shows the statement after the one stuck on a critical section.

Visual Studio: breakpoint excluding calls from a specific function

I want to set a breakpoint in unmanaged C++, in Visual Studio 2005, but I would like to ignore this breakpoint if the call stack is in a specific function. Is there a way to do this?
If you have a commercial edition of Visual Studio, you should be able to set a breakpoint early in the calling routine, then change its "When Hit..." behaviour to "Run a macro". You'll need to write a macro that programmatically disables the breakpoint in the called function -- use this as the macro to run. (Hopefully someone else can describe how such a macro can be written.) Then set other breakpoints on all exit points of the calling function, and change their behaviour to reenable the breakpoint in the called function.
If you have an Express Edition, you'll find that the "Run a macro" checkbox is greyed out unfortunately. In this case, if you have access to the source code for the calling function, I suggest the following:
Make a global int variable, bp_enabled, initially set to 1.
--bp_enabled on the first line of calling_function().
++bp_enabled at all exit points of calling_function().
Change the "Condition..." properties of the breakpoint in the called function to break only when bp_enabled == 1. (Go to Debug | Windows | Breakpoints, then right-click the breakpoint.)
A bit of a hack, but it gets the job done.
[EDIT: Fixed to work properly even if calling_function() happens to call itself recursively (either directly or indirectly)...]
You could put a DebuggerStepThrough attribute on the calling method, altho this will stop all breakpoints being hit on the calling method, rather than just the specific method
You could put breaks on all the lines that call your method in question (except in that one caller routine you don't want to stop). I can see this being difficult if the routine is called from a lot of places, or invoked in non-obvious ways.
Changing the code just for debugging seems like the easiest - if possible.
Update: OP initially didn't make it clear at the beginning unmanaged C++ was being used. So this answer is pretty useless now because it'll only work with managed code. That said I'll leave it be in case someone stumbles over it and finds it usefulor didn't know about JMC:
Whilst DebuggerStepThrough is still a valid method to prevent stepping into code there are times when you do want to step in. This means having to locate and comment out the DebuggerStepThrough attribute.
.NET 2.0 introduced a new attribute: DebuggerNonUserCode. This works in conjunction with the Debug Just My Code setting in Tools->Options->Debugging->General->Enable Just My Code.
If Enable Just My Code is checked then any method decorated with the DebuggerNonUserCode attribute won't be stepped into. If you do want to re-enable debugging of code marked with DebuggerNonUserCode periodically then just uncheck this setting. This saves some time having to locate and comment out code you'd normally not be interested in stepping through.
To use either attribute just decorate the methods of your choosing like this:
// The .NET 1.1 way
[DebuggerStepThrough]
public static void IgnoreMeAlways()
{
Console.WriteLine("Hello...where is everybody!");
}
//The .NET2.0/VS2005/2008 way. Use in conjunction with Debug Just My Code
[DebuggerNonUserCode]
public static void NonUserCodeSomeTimes()
{
Console.WriteLine("Longtime no see");
}

Can I set Visual Studio 2005 to ignore assertions in a specific region of code while debugging

Here's the scenario. I'm debugging my own app (C/C++) which is using some library developed by another team in the company. An assertion fails when my code generates some edge case. Its a pain because the assertion is not formulated correctly so the library function is working OK but I get all these interruptions where I just have to continue (lots as its in a loop) so I can get to the stuff I'm actually interested in. I have to use the debug version of the library when debugging for other reasons. The other team wont fix this till next release (hey, it works on our machine).
Can I tell the debugger to ignore the breakpoints asserted by this section of code (i.e. can it auto-continue for me).
If the code is triggering breakpoints on its own (by __debugbreak or int 3), you cannot use conditional breakpoints, as the breakpoints are not know to Visual Studio at all. However, you may be able to disable any such breakpoints you are not interested in by modifying the code from the debugger. Probably not what you want, because you need to repeat this in each debugging session, however still may be better than nothing. For more information read How to disable a programmatical breakpoint / assert?.
There's no good way to automatically ignore ASSERT() failures in a debug library. If that's the one you have to use, you're just going to have to convince the other team that this needs fixed now, or if you have the source for this library, you could fix or remove the assertions yourself just to get your work done in the meantime.
You can add an exception handler around the call(s) to the library, catch the EXCEPTION_BREAKPOINT exception and do nothing.
Example 2 in the following link seems to be what you want to do:
http://msdn.microsoft.com/en-us/library/ms681409(VS.85).aspx
You can use conditional breakpoints. Some links:
http://support.microsoft.com/kb/308469
http://dotnettipoftheday.org/tips/conditional_breakpoint.aspx

How can I debug a win32 process that unexpectedly terminates silently?

I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...
On the one occasion the crash occurred under the debugger, the debugger did not break---it showed the application still running. When I manually paused execution, I found that my process no longer had any threads.
How can I capture the reason this process is terminating?
You could try using the adplus utility in the windows debugging tool package.
adplus -crash -p yourprocessid
The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes.
If you are using Visual Studio 2003 or later, you should enable the debuggers "First Chance Exception" handler feature by turning on ALL the Debug Exception Break options found under the Debug Menu | Exceptions Dialog. Turn on EVERY option before starting the debug build of the process within the debugger.
By default most of these First Chance Exception handlers in the debugger are turned off, so if Windows or your code throws an exception, the debugger expects your application to handle it.
The First Chance Exception system allows debuggers to intercept EVERY possible exception thrown by the Process and/or System.
http://support.microsoft.com/kb/105675
All the other ideas posted are good.
But it also sounds like the application is calling abort() or terminate().
If you run it in the debugger set a breakpoint on both these methods and exit() just for good measure.
Here is a list of situations that will cause terminate to be called because of exceptions going wrong.
See also:
Why destructor is not called on exception?
This shows that an application will terminate() if an exceptions is not caught. So stick a catch block in main() that reports the error (to a log file) then re-throw.
int main()
{
try
{
// Do your code here.
}
catch(...)
{
// Log Error;
throw; // re-throw the error for the de-bugger.
}
}
Well, the problem is you are getting an access violation. You may want to attach with WinDBG and turn on all of the exception filters. It may still not help - my guess is you are getting memory corruption that isn't throwing an exception.
You may want to look at enabling full pageheap checking
You might also want to check out this older question about heap corruption for some ideas on tools.
The most common cause for this kind of sudden disappearance is a stack overflow, usually caused by some kind of infinite recursion (which may, of course, involve a chain of several functions calling each other).
Is that a possibility in your app?
You could check the Windows Logs in Event Viewer on Windows.
First of all I want to say that I've only a moderate experience on windows development.
After that I think this is a typical case where a log may help.
Normally debugging and logging supply orthogonal info. If your debugger is useless probably the log will help you.
This could be a call to _exit() or some Windows equivalent. Try setting a breakpoint on _exit...
Have you tried PC Lint etc and run it over your code?
Try compiling with maximum warnings
If this is a .NET app - use FX Cop.
Possible causes come to mind.
TerminateProcess()
Stack overflow exception
Exception while handling an exception
The last one in particular results in immediate failure of the application.
The stack overflow - you may get a notification of this, but unlikely.
Drop into the debugger, change all exception notifications to "stop always" rather than "stop if not handled" then do what you do to cause the program failure. The debugger will stop if you get an exception and you can decide if this is the exception you are looking for.
I spent a couple hours trying to dig into this on Visual Studio 2017 running a 64-bit application on Windows 7. I ended up having to set a breakpoint on the RtlReportSilentProcessExit function, which lives in the ntdll.dll file. Just the base function name was enough for Visual Studio to find it.
That said, after I let Visual Studio automatically download symbols for the C standard library, it also automatically stopped on the runtime exception that caused the problem.