Mar 152011
 

Introduction

This blog entry deals with user mode dumps only. Kernel mode dump files is not dealt with here but should be quite similar.

Define dump file

It is the memory snapshot of a process. The dump file saves all information pertaining to a process. The information include, loaded modules/dlls, handles, executing threads and other stuffs. Optionally we can include heap information.

How to open a dump file?

Dump files can be opened in a debugger as you would normally open a process or attach to a process. All debuggers provide options for opening a dump file. Here is the menu option in WinDbg which opens a dump file…

Open dump file option in windbg

Open dump file option in windbg

A similar but, kinda hidden, version of open dump file option in Visual Studio, its not so visible unless you dig a bit. See below screenshot…

How to create a dump file?

A quick option which is quite is limited is to use the task manager “Create Dump File” option. Which looks like…

Task manager create dump file option
Task manager create dump file option

With windbg use the .dump /ma D:\DumpFile.dmp command. With visual studio you can attach to a process and use Debug->Save dump as or while you are debugging use Debug->Save dump as.

Another tool that comes along with “Debugging tools for windows” is ADPlus, a VBScript based tool, which automates the process of creating a dump file. This tool works by using cdb.exe (console debugger) command line options. Very powerful. I’ll blog about the tool in another post.

Limitations of dump files

You cannot execute the dump file, just like you would normally do with a process, or set breakpoints; a dump is a ‘snapshot’ of a process at a particular point of time. So all stuff in memory up till that particular point of time will be available but not after that particular point of time. Also if you have a wrong dump file then you could end up wasting time, so in order to prevent such cases we have tools like ADPlus which when setup properly automates the process of capturing dumps.

Different kinds of dumps

  • Crash dump – automatically taken during a crash
  • Hang dump – automatically taken (using tools like ADPlus)
  • High CPU dump – automatically taken (using tools like ADPlus)

Dump file tips in windbg

  1. I normally execute the following command in WinDbg: !analyze -v. This command gives a summary of the stuff in dump file. So it shows you the stack of the thread in which the exception occurred.
  2. Also when you open a dump file in WinDbg you’ll get a brief summary of the exception that occurred and also a view of the registers.
  3. If you have a hang dump or a high CPU dump you will love the following command: !analyze -hang. This shows us the name of the function which is eating up most of CPU time.
  4. You will love the command !runaway which shows the excecution time for each thread, so this way you can identify the thread that’s taking most of CPU time.
  5. To know the type of dump file you are working on enter “||” into WinDbg. This command will tell you whether you are dealing with a full dump or a mini dump. A sample output on a dump of MsPaint.exe looks like…
    0 Full memory user mini dump: D:\MsPaint.dmp
  6. To know the name and id of the process for which this dump was made use the single pipe command “|”. Sample output looks like…
    0 id: 11e4 examine name: C:\Windows\System32\mspaint.exe
  7. .ecxr gives you exception record along with registers display.
  8. .lastevent shows you the last exception that occurred.
  9. You can create a mini dump out of a full dump by executing a .dump filename command on the existing dump.
  10. To view last error status of all threads use !gle -all
  11. Its very important to have the correct pdb files. Public symbol path and downstream store path should be set in WinDbg or by using _NT_SYMBOL_PATH environment variable. This is how mine looks -> SRV*C:\DebugSymbols*http://msdl.microsoft.com/download/symbols
  12. Don’t forget you are doing “post mortem” debugging. The dead doesn’t walk and talk. 🙂
  13. ~* kpn shows stack of all threads
  14. !locks displays locks held by threads
  15. !lmvm ModuleName display information about a module. !lmvm User32 display information about user32.dll.
    • lm sm display all modules loaded/unloaded in sorted order, ‘when’ the dump was taken.
    • lm or lmvi display all modules loaded/unloaded in their load/unload order
  16. dt command displays type information of a type passed in.
  17. dv command displays all local variables
  18. x to examine a symbol. For e.g. to see all symbols in kernel32 starting LoadLibrary use following command: x kernel32!LoadLibrary*. The output looks like…
    00000000`77906640 kernel32!LoadLibraryExWStub =
    00000000`778fe3b0 kernel32!LoadLibraryExAStub =
    00000000`77907058 kernel32!LoadLibraryExA =
    00000000`77906f80 kernel32!LoadLibraryW =
    00000000`77907070 kernel32!LoadLibraryA =
    00000000`77906634 kernel32!LoadLibraryExW = 

Conclusion

Have fun debugging dump files and help others too. Spread word about this article. If you’ve got comments let me know. 🙂

Nov 152008
 

It’s always irritating to debug paint messages and sometimes expensive too. I’ve tried different methods to try debug painting issues, always ended up disappointed.

Why is it such a pain to debug WM_PAINT messages?

Main reason is, we are not in control. Paint messages comes via a window framework. Painting is done whenever a window gains focus or is activated this means our application will never get focus if we set a breakpoint in an OnPaint function because as soon as our application comes to focus it again sends a repaint request which again breaks into the OnPaint function.

It’s can be expensive too because we’ll need some kind of a dual monitor setup. So that our application runs on one monitor and the debugger on the other. For professional game/UI developers it’s ok because that’s their job and they will always need such a setup. But guys like me cannot affort such a setup.

Any workaround?

Yes, that’s the good news. Windows explorer has a cute feature called “Tile Horizontally” and “Tile Vertically”. It also has another feature to select taskbar items using control key.

So this is how a standar taskbar looks, as you already know that at a time, in windows, only one window can be active.

taskbar_oneapp_selected

The tab having a dark shade is the one that’s active, and if you right click on this tab you’ll get a context menu which will correspond to the active application’s system menu.

Now here is the interesting part use ‘Ctrl’ key to select multiple tabs. Press ‘Ctrl’ and then use your mouse to click on tabs you wanna select and then right click on any of these selected tabs and see what you get! Here is a screenshot of what I get…

taskbar_multipleapp_selected

These menu items are interesting, most windows users are unaware of this option, it’s a quick way to arrange your windows. You can try them one by one. Note that there is an option to close a group too. 🙂

So returning back to our original discussion, we now apply this trick to our application. We are going to select visual studio and an application that’s being debugged. I’ve set a break point in the OnPaint function.

So we select both applications in the taskbar using ‘Ctrl’ key and mouse and then right click and select ‘Tile vertically’ or ‘Tile Horizontally’. I would select ‘Tile vertically’ as it would give me enough vertical space but you can decide what’s best for you. Eventually what I get is a screen like this with two windows that doesn’t overlap each other. One of them is visual studio and the other one is my application that’s being debugged, also note that I’ve set a breakpoint in OnPaint function. Both applications behave independently without interfering with each other.

vertical_tile

Now my desktop acts like a dual monitor setup. 😉 It’s kinda cool for debugging purpose and yeah I agree this is not the ultimate solution but it’s quite useful. Hope this helps you. 🙂

Aug 132008
 

mm so what the heck is this DEBUG_NEW? Does this harm my application? Why is DEBUG_NEW provided? These are some of the questions that people have always asked when they see the following statements in a .cpp file of an MFC application…

#ifdef _DEBUG
  #define new DEBUG_NEW
  #undef THIS_FILE
  static char THIS_FILE[] = __FILE__;
#endif

So after all what is this DEBUG_NEW?

Well in short it’s an overloaded version of the new operator. So when you write new in your code the preprocessor expands it to DEBUG_NEW.

It’s proper definition looks likewise…

void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine)
{
    return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);
}

The call get’s redirected to another overloaded new operator which in turn does some additional housekeeping for tracking memory leaks. This is the reason why this new operator takes the file name and line number so that when a leak occurs the user can be taken to that particular location where the leak occurred. But out of ignorance people just delete above code which although doesn’t disable tracking of leaks but disables the feature whereby the user can double the click in the output window to be taken to that exact location where the leak occurred.

So suppose I write a piece of code which is purposely left undeleted, then this is what I get! So if I click on the red line I am taken to the exact location where the leak occurred.

Detected memory leaks!
Dumping objects ->
E:\SingleDocTest\SingleDocTestView.cpp(43) : {84} normal block at 0x00035628, 100 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

This is a big help to me atleast. I’ve seen colleagues out of ignorance deleting DEBUG_NEW. So how did this help me? Here is an example…

void SomeFrequentlyCalledFunction()
{
    m_pSomeObjPtr = new CSomeObj;
}

So ideally I should be deleting m_pSomeObjPtr before reallocating it again, and this is where DEBUG_NEW comes handy. Well if you have other advanced applications for tracking memory leaks then it’s fine, but this is a big help to know immediately where the leak is happening.

Is there some performance penalty involved?

Yes only in debug builds which is expected too, since we never ship debug builds!

Does this track resource leaks?

Of course not!

Is there anything wrong if we delete it?

Yes it’s wrong but its not an error, leave it, it’s harmless!

May 042008
 

VC debuggger has a nice feature to display array values. It works with any contiguous data, for e.g. vector, CArray, native type arrays etc.

Follow these steps…

  1. IntVector is an array of integers
  2. Start quick watch by pressing Shift + F9 with IntVector object selected
  3. Select _First(encircled in red) and press Add watch(encircled in red)
  4. You should see _First in the watch window
  5. So now put a comma after _First and add number of elements to view

Here is a screen shot of how I get to see a vector’s array values in the debugger.

Watch demo

See above result in watch window, easy isn’t it? Works in the same way for other array types too!

So have a great time debugging arrays 😉

Apr 102008
 

Ever felt the need to dump an MFC array content to a debugger, it’s just so easy! Use AfxDump or afxDump!

Here is an e.g.

CArray IntArray;
AfxDump( &IntArray ); // Or

#ifdef _DEBUG
afxDump << IntArray; #endif[/sourcecode]

Apr 082008
 

I had heavy resource leaks in my resource digger application with my resource leak detector showing ever increasing amount of bitmap handles!

As a hint to me this was happening in my icon display function, but looking up the code I found nothing causing a leak. Analyzing closely I found that bitmap count was increasing by two, ah immediately it struck me, it’s GetIconInfo! It creates two bitmap and I was not deleting them, my fault I should’ve have read MSDN properly!. 🙁

So as a summary don’t forget to delete bitmaps in an ICONINFO structure filled out by GetIconInfo because this is what the documentation says…

MSDN:

GetIconInfo creates bitmaps for the hbmMask and hbmColor members of ICONINFO. The calling application must manage these bitmaps and delete them when they are no longer necessary. 🙁

For those of you who didn’t know about GetIconInfo, it’s just a function which returns mask bitmap and real bitmap for an icon. You see transparent icons because they have a mask bitmap associated with them. This function also tells us whether given icon handle represents an icon or a cursor along with hotspot co-ords for a cursor.

Feb 112008
 

Ever felt the need for a simple thing like, you print something to developer studio output window and when you double click on that line it takes us to the place from where this was output.

For eg: You have an unknown exception and you put a trace statement which prints the file name and line number to developer studio output window, so when you double click on that line in developer studio it takes us to the place where this exception was traced out. Much like the error statements in output window of developer studio. You press F4/F8 and our cursor is on the line which caused the error.

Here is a macro that does this…

#if ! defined UNKNOWN_EXCEPTION
#   ifdef _DEBUG
#       define UNKNOWN_EXCEPTION AfxTrace(_T("\n%s(%i): Unknown Exception occurred!!"), _T(__FILE__),__LINE__)
#   else
#       define UNKNOWN_EXCEPTION 0
#   endif
#endif

Now just use this from somewhere you want to do a trace for eg:

void SomeFunkyStuff()
{
     try
     {
           char *Blah = 0;
           *Blah = 0; // Hope this throws an exception
     }
     catch( ... )
     {
          UNKNOWN_EXCEPTION;
     }// End try
}// End SomeFunkyStuff

So now when exception is thrown, a trace statment will be printed to developer studio output window, double click on the line your cursor should be on the line which traced out this line to developer studio output window. Well if it doesn’t then 😛

This is not my idea, shamelessly stolen from MSDN, which was originally given by someone.

Jan 312008
 

Hope you’ve heard of conditional compilation. Conditional compilation simply means what it says, i.e. compile only when a certain condition is true and it’s only meant for the compiler hence it should only take place during compilation.

We do conditional compilation with help of preprocessor commands. For eg:

void WhoIsNibu()
{
    // ;)
    #ifdef NIBU_IS_A_VERY_GOOD_MVP
         printf( "Nibu is an MVP, Mwhahahaha, Nibu loves Jesus" );
    #else
         printf( "Nibu is still an MVP hehe ;), He loves Jesus" );
    #endif
}

Well now the first printf will only be “compiled” if you define NIBU_IS_A_VERY_GOOD_MVP else the second one will be “compiled”.

Well this was something about conditional compilation, now about including a resource based on a condition. This is mainly for those who are using VC resource editor to include a resource for others you can simply follow normal conditional compilation to decide whether to include or not to include a resource…

In VC resource editor right click on a resource for eg: a menu resource and select properties, now you will find a text field called “Condition”

Condition

See the controls encircled in red.

I’ve entered _DEBUG here, so this menu will only be compiled into the exe when _DEBUG is defined else it won’t be.

Very easy isn’t it. Recently someone asked this in a forum hence thought of posting it here. This is in VC6 but I am sure there is a similar (and better) option in later versions of visual studio too.