VS2010 C++ Debugging Issues - Advanced Ways to Debug and Application? - c++

We have a program which is proving difficult to debug. The MFC application runs fine for a few hours but over a day it will crash. Sometimes it will not throw any errors and simply exit the "dlg.DoModal()" section of our code without the user (or any obvious part of the code) closing the dialog. Other times it will crash and throw an error outside of our code and have a horrendous call stack that has nothing to do with our code, it has a lot of calls to system DLLs however.
A bit of background to our problem.
We are trying to develop a MFC bases C++ application (with a dialog). We have multiple threads and the code is rather large which makes debugging a nightmare. We have been experiencing intermittent crashes that we have been unable to locate the source of so far.
We are well past the use of breakpoints for debugging as we are pretty sure it is an issue somewhere in MFC, maybe not a bug but more a problem with the way we are using MFC.
Now we've tried simple things to help us like:
Enable all debug exceptions:
Debug -> Exceptions and then checking all the boxes so that we can
trap silly mistakes.
This proved helpful but we've now corrected all the errors it throws
within a few hours of running.
Search for memory leaks
We then tried Visual Leak Detector (which works beautifully by the
way) located here: http://vld.codeplex.com/ Our code now reports no
memory leaks so it is not an obvious memory leak issue. We have
included vld.h in the very top of our code near the entry point.
Adding Microsoft Symbol Server to obtain debug symbol files.
We then tried making our call stacks more human readable by using MS
Symbol servers shown in these tutorials:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/3f1825e1-6770-48c0-91b0-12d8946ab259/2-how-do-i-configure-visual-studio-to-use-microsoft-symbol-server?forum=vsdebug and http://support.microsoft.com/kb/311503
This ultimately did nothing as it still doesn't tell you enough about any errors.
Using the Thread window to see all call stacks, and using the
Parallel Stack window
We have been using the Thread and Parallel stack windows to aid our
debugging but ultimately they have proved nothing more than pretty
pictures and fancily formatted call stacks that makes you feel good
more than anything. We have been using the tutorial here which has
been very handy
http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-A-Beginn
Now for the more interesting things we've tried that do not throw errors straight away but can be detected as problems:
GDI Objects not being destroyed
This one is not obvious in VS2010 as an issue. Basically if you use a call like "CDC* pDC = lChild->GetDC();" and do not use the call "ReleaseDC(pDC);" then you have just created a GDI Object that will not be destroyed until your program terminates. VS2010 is a bit dumb in this regard and will keep creating these objects until your program crashes, and the call stack will look horrible and you will probably have no idea why it has crashed.
To find this issue, start Windows Task Manager -> Click Processes Tab -> Click the View Toolbar item -> Select Columns. Now check Handles, Threads, User Objects, and GDI Objects. Now start your program, find it's process in the list under Image Name, and watch to see if the GDI Objects column keeps growing or stabilizes.
Objects Not being destroyed
This is another not so obvious error, if you create a bitmap like this: "reinterpret_cast(LoadImage( GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_BITMAPNPR), IMAGE_BITMAP, 0, 0, 0))" and assign it straight to a picture control, the bitmap will not be destroyed if you assign another bitmap to this picture control using similar code. Instead you need to assign the above to a HBITMAP variable which you then need to destroy when you are done.
This situation can also arise if you create a font or colour in a similar fashion.
Now with all that being said, we have tried all the methods above and we still can't find our issue. Sometimes our program will exit normally and we won't be given any debug info (this is usually after is has been running overnight), other times our program will lockup the PC (tested on multiple PCs), other times it will throw an error but we can't locate the culprit because it simply points to the ".DoModal()" part of our code and the rest is native windows DLLs which is useless for debugging purposes.
We suspect something is either being created and not destroyed properly but we aren't sure what and VS2010 is not telling us anything useful to point us in the right direction.
Does anyone have any ideas? How do we trap errors that aren't obvious to VS2010? Or rather how do we easily trap "GDI leaks" and the like?
Thanks in advance
Edit:
We've been using Microsoft's Application Verifier, it's found a few errors so far. To use it download it here http://www.microsoft.com/en-us/download/details.aspx?id=20028 run Application Verifier, add your .exe file in your Debug or Release directories and run the program in VS2010 as normal. VS2010 will break when Application Verifier 'sees' an error. It hasn't found anything too outrageous yet so I assume that we still have issues with our code.

Related

Bizarre behavior with Visual Studio's debugger; "The network location cannot be reached" (ERROR_NETWORK_UNREACHABLE)

I've experienced this with every version of Visual Studio starting from 2012 (2012, 2013, 2015 Preview), on multiple computers and multiple projects, but I haven't figured out how to fix it:
Whenever I'm debugging a 64-bit(?) C++ console program, after a few minutes and seemingly completely randomly (when I'm not clicking or typing anything), the console window for the program spontaneously closes and I can no longer debug or step through the program with Visual Studio. When I press Stop and attempt to restart debugging, I usually get ERROR_NETWORK_UNREACHABLE:
// MessageId: ERROR_NETWORK_UNREACHABLE
// MessageText:
// The network location cannot be reached. For information about network troubleshooting, see Windows Help.
#define ERROR_NETWORK_UNREACHABLE 1231L
If I try to attach to the process manually I get the error:
Unable to attach to the process.
The only fix I've found for this is to restart Visual Studio. I can't find any other way to fix it, and I've tried running Process Monitor but haven't found anything.
What causes this problem and how can I fix it?
(?) Upon further checking it seems that this only happens in 64-bit mode, but I'm not 100% sure.
Ok, this is just so wrong
I also have issues with this bug, and in my case it occurred every other debug session. Which meant debug -> stop -> debug -> bug -> restart visual studio -> go to start (repeat every minute during the whole day).
Needless to say I was driven to find a solution. So yesterday I tried procmon, spend hours looking at API monitor differences, looked at plugins, netstat, etc, etc, etc. And found nothing. I gave up.
Today
Until today.
To track down a stupid bug in my program today, I launched appverifier. For my application, I ran the 'basics' tests and clicked save. After a few hours this led me to the bug in my program, which was something like this (extremely simplified version):
void* dst = _aligned_malloc(4096, 32);
memcpy(dst, src, 8192);
Obviously this is a bug and obviously it needed fixing. I noticed the error after putting a breakpoint on the memcpy line, which was not executed.
After a stop and 'debug' again I was surprised to find that I could actually debug the program for the second time. And now, several hours later, this annoying bug here hasn't re-emerged.
So what appears to be going on
So... apparently data from my program is bleeding through into the data or execution space of the debugger, which in turn appears to generate the bug.
I see you thinking: No, this shouldn't happen... you're right; but apparently it does.
So how to fix it? Basically fixing your program (more particular: heap corruption issues) seems to make the VS debugger bug go away. Using appverifier.exe (It's in Debugging tools for Windows) will give you a head start.
Why this works
Since VS2012, VC++ uses a different way to manage the heap. Hans Passant explains it here: Does msvcrt uses a different heap for allocations since (vs2012/2010/2013) .
What basically happens is that heap corruption will break your debugger. The AppVerifier basic settings will ensure that a breakpoint is triggered just before the application does something to corrupt the heap.
So, what happens now is that before the process will break the heap, a breakpoint will trigger instead, which usually means you will terminate the process. The net effect is that the heap will still be in-tact before you terminate your program, which means that your debugger will still function.
"Test"
Before using appverifier -- bug triggered every 2 minutes
While using appverifier -- VS debugger has been stable for 5 days (and counting)
This is an environmental problem of course. Always hard to troubleshoot, SysInternals' utilities like Process Monitor and Process Explorer are your primary weapons of choice. Some non-intuitive ways that a network error can be generated while debugging:
Starting with VS2012, the C runtime library had a pretty drastic modification that can cause very hard to diagnose mis-behavior if your program corrupts the heap. Much like #atlaste describes. Since time memorial, the CRT always created its own heap, underlying call was HeapCreate(). No more, it now uses GetProcessHeap(). This is very convenient, much easier now to deal with DLLs that were built with /MT. But with a pretty sharp edge, you can now easily corrupt the memory owned by Microsoft code. Not strongly indicated if you can't reattach a 64-bit program, you'd have to kill msvsmon.exe to clear up the corruption.
The Microsoft Symbol Server supplies PDBs for Microsoft executables. They normally have their source+line-number info stripped, but not all of them. Notably not for the CRT for example. Those PDBs were built on a build server owned by DevDiv in Redmond that had the source code on the F: drive. A few around that were built from the E: drive, Patterns+Practices uses that (unlikely in a C++ program). Your debugger will go look there to try to find source code. That usually ends well, it gives up quickly, but not if your machine uses those drive letters as well. Diagnose by clearing the symbol cache and disabling the symbol server with Tools + Options, Debugging, Symbols.
The winapi suffers from two nasty viral infections it inherited from another OS that add global state to any process. The PATH environmental variable and the default working directory. Use Control Panel + System + Advanced + Environment to have a look at PATH, copy/paste the content of the intentionally small textboxes into a text editor. Make sure it is squeaky clean, some paralysis at the usual mess is normal btw. Take no prisoners. Having trouble with the default directory is much harder to troubleshoot. Both should pop out when you use Process Monitor.
No slamdunk explanations, it is a tough problem, but dark corners you can look in.
I have the same problem. Thought it was related to 64 bit console apps, where it is very easily triggered with almost any debug session. But, it also happens on 64 bit windows apps too. Now I am seeing it on 32 bit windows apps. I am running Windows 8.1 pro on a single desktop with the latest version of vs 2013 and no remote debugging. My (added) extensions are Visual Assist, Advanced Installer, ClangFormat, Code Alignment, Code Compare, Duplicate Selection, Productivity Power Tools 2013, and Visual SVN.
I discovered that the "Visual Studio 2013\Settings\CurrentSettings.vssettings" file gets corrupted. You can delete this file and recreate it by restarting VS or you can try to edit the XML. I then keep a copy of a good settings file that I use to replace when it gets corrupted again.
In my case, the corrupted line begins with
</ToolsOptionsSubCategory><ToolsOptionsSubCategory name="XAML" RegisteredName="XAML"
... and it is extremely long (I think this is why it is prone to corruption).
I just disabled in the Menu
Tools > Options
Debugging > Edit and Continue
Native-only options > Enable native Edit and Continue
and now it does not give the that stupid error which was preventing the starting of the debuggee application.
I also had the same problem with VS2015. It was so frustrating that a simple Hello World program gave this error when I ran debugger for the second time. Tried uninstall and reinstall and didn't work.
Finally, the solution mentioned in https://social.msdn.microsoft.com/Forums/vstudio/en-US/8dce0952-234f-4c18-a71a-1d614b44f256/visual-studios-2012-cannot-findlaunch-project-exe?forum=vsdebug
worked. Reset all visual studio settings using Tools->Import and Export settings. Now the issue is not occurring.

Generic log for application crash C++/MFC

We have a problem for which I am looking for a direction. We have an old MFC based application, and due to various reasons, the application is crashing sometimes intermittently in some weird scenarios. And even the customers who are using our application and getting these crashes are finding difficulty in identifying the pattern of crash. So, I had a thought that, if we can have a mechanism by which we can generate a log whenever the application crashes. Like for example, the call stack or any other information in that log. I know,, we can use the crash dump in this case, but then I feel like having a log is a better option. So any help or information in this regard would be really helpful.
Thank you.
You can find a good implementation of crash reporter in the link here.
When you compile your release build, make sure that both DEBUG and /MAP are enabled. Store your binaries together with your .map files and let your customer run this version until a crash is produced. In the Event Viewer you will then find a crash log with a crash offset. Then debug step into your code (F10) and use the crash offset together with some nifty tricks and tricks to jump (set the EIP register to... well, you have to google this a bit) to the location where the crash occurred. You should now be able to find the error!

ChtmlView MFC memory leaks on javascript

I have an MFC application which needs to display a webpage. I've added a CHtmlView through CSingleDocTemplate which spawns a window and displays the page fine but it leaks memory when running javascript.
The page I'm looking at is genereated by Madcap flare and so it very heavy with javascript. I'm losing about 4K a second just sitting watching the page.
I've tried to reduce the problem by letting the user close the document but then I run into a problem with not knowing if the CFrameWnd was closed or not in the main application so not knowing if I need to create a new one or just reuse it.
I'm running this on windows 7 with IE9 installed so if I'm right I should be well clear of the old IE javascript circular references bug.
Does it happen in both Release and Debug build? I've seen similar (somewhat deterministic) errors when freeing dangling pointers or blowing the stack. With a bit of bad luck, the undefined behavior from faulty code could produce memory leaks.
Try enabling all possible runtime checks in your build and see if the error goes away (or is somehow detected).
Try commenting out large code blocks and see if the error goes away.
I'm just guessing here :)

C++ DX11 application only runs in Visual Studio IDE

Alright, I presented this question on the MSDN forums but have yet to receive any kind of response so I figured I'd give StackOverflow a try.
I'm currently developing a DirectX application using VS2008 on Win7. I recently experienced a nasty memory corruption bug with a memory allocation class that grabbed byte aligned memory. During this bug I could still run the debug and release executables however it would crash due the instructions getting corrupted or whatever, but it would still execute for a bit until the crash.
I then stripped out the entire memory allocation class. The application runs perfectly in the IDE (release and debug builds) but I can't run any of the executables at all. They immediately crash with a non-responding/stop working error. And I don't think it is my environment because I get the same issue on another computer that wasn't having problems before either.
Dependency walker gives a "Warning: At least one delay-load dependency module was not found. Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module." error and indicates that GPSVC.dll and IESHIMS.DLL can't be found. I've read that this can be misleading and just indicates a potential problem somewhere. And Dependency walker wasn't giving me this error the day before.
I haven't tinkered with any of the configuration or project settings or added new code. Any idea of what could be causing this behavior?
Also another note, I installed the Windows 7.1 sdk the same day. Think this could be some kind of compiler related bug?
Just in case some useful information pops up on the MSDN post, here is the link
http://social.msdn.microsoft.com/Forums/en-IE/vsdebug/thread/f692b394-8af2-4453-991c-aa6a443a9019
Thanks!
Edit -
Here is the last couple lines of Dependency Walker's profiling output
GetProcAddress(0x76CD0000 [c:\windows\syswow64\KERNEL32.DLL], "DecodePointer") called from "c:\windows\syswow64\NVWGF2UM.DLL" at address 0x6D8BAE4F and returned 0x77B59D65.
GetProcAddress(0x76CD0000 [c:\windows\syswow64\KERNEL32.DLL], "DecodePointer") called from "c:\windows\syswow64\NVWGF2UM.DLL" at address 0x6D8BAE4F and returned 0x77B59D65.
GetProcAddress(0x76CD0000 [c:\windows\syswow64\KERNEL32.DLL], "EncodePointer") called from "c:\windows\syswow64\NVWGF2UM.DLL" at address 0x6D8BAF60 and returned 0x77B60FDB.
GetProcAddress(0x76CD0000 [c:\windows\syswow64\KERNEL32.DLL], "DecodePointer") called from "c:\windows\syswow64\NVWGF2UM.DLL" at address 0x6D8BAF70 and returned 0x77B59D65.
Second chance exception 0xC0000005 (Access Violation) occurred in "c:\users\joel\desktop\DXAPP.EXE" at address 0x0110152E.
Exited "c:\users\joel\desktop\DXAPP.EXE" (process 0x27D8) with code 255 (0xFF).
Is this referring to a DLL grabbing a null pointer or to my actual instructions? Going to read up on how to use WinDbg real quick and I'll post it's output if this doesn't shed any immediate light on the issue.
Edit 2 -
Simply running the application and hitting debug to bring up Visual Studio consistently brought me to where I'm compiling my shaders. I'm assuming at the moment that the root of the problem lies around this. However, I still don't understand the change of behavior during execution between using the IDE and not.
Solution! -
I was so thrown off by the previous memory corruption bug that I didn't realize my shaders weren't in a local directory to the executables. This in turn was generating a null pointer that wasn't handled properly after calling D3DX11CompileFromFile().
Shoot, sorry I meant to post this as a comment...
I can only suggest more diagnostic attempts.
One would be to profile the app from within Depends, this will also show dynamic DLL loads and might show something new. Also it captures the debug output. It may behave differently than launching in the debugger itself and provide a clue. You don't mention actually profiling so I thought I'd suggest it in case you hadn't. Also, pay very close attention to the paths for the DLL's loaded - you might be surprised at a DLL loading from a location other than you intended.
Another suggestion is to try at attach to the stopped app after the crash (before dismissing the error dialog). See if you can get a stack trace or anything out of it.
Finally try attaching (or even launching from) WindDbg rather than the IDE. Like the Depends profile, the difference in debugger behavior and how it hooks the app may allow the crash to happen, while providing the clues you need.
Good Luck!

Direct3D strange crash

I have Direct3D rendering library compiled with VS2008. The another application (built with VS2008) uses my library and everything works fine.
Recently, parent application was moved to VS2010 but my library is still being built under VS2008. And still everything works fine BUT one call on only ONE sprite.
D3DXSprite->Draw method crashes in D3DX9_43.dll in D3DXCore::CSprite::Draw() method. And it occurs only when I'm trying to draw a specific element from texture.
I've also tried to rebuild my library under VS2010, but no success. Crash still occurs.
Any ideas?
Thanks!
This may not be want you want to hear, but all I can suggest for debugging something like this is the liberal use of break points and special debugging if-statements.
Place a try-catch statement around the render function that is failing and place a breakpoint in the catch block.
You may need to add some counters and debugging variables so that you can monitor the size/cont of your data structures vs. what your rendering code actually processed.
If you still don't have any hints, it's time to temporarily fork your code (copy it) and simplify. Start ripping out chunks of code to see if it still fails. Eventually you'll narrow it down.
Good luck.