Archive

Archive for the ‘Debugging’ Category

Visual Studio 2010 – Conditional breakpoints using String Comparison Functions (C/C++)

November 3rd, 2009 Sarath Comments

All we’re fond of conditional break points if we need to execute the program until some specific condition exists. We usually give numerical expressions to give conditional break points. If you don’t know about conditional break points, just have a look at MSDN documentation. or this one.

Now the C/C++ programmers are blessed with break with string conditions.

Just put a breakpoint in your source code and right click on that choose “Condition” to see the following window appear. You can give string comparison routines to set the break point.

image

Once you start debugging, you can see the break point hit on the condition you’ve given

image

Visual Studio Beta 2 currently supports the following functions (Taken from Habib Heydarian’s blog)

strlen, wcslen, _tcslen, strnlen, wcsnlen, _tcsnlen, strcmp, wcscmp, _tcscmp, stricmp, wcsicmp, _tcsicmp, strncmp, wcsncmp, _tcsncmp,strnicmp, wcsnicmp,_tcsnicmp,_stricmp, _wcsicmp, _strnicmp, _wcsnicmp

This may be changed or updated in the final release. Anyway enjoy your breakpoints!

Visual Studio 2010 – Pin the watch box in source window

October 27th, 2009 Sarath Comments

To know the content of a particular variable during debugging, what we usually do is add it to the watch window or just hover the mouse over it and see the values as tool tip like window.

image

With Visual Studio 2010 You can pin this watch window in the source file like a notes. Whenever the data is changed, you can watch it instantly in the source file itself. Cool eh? See it here.

Start your Debugging

As you’re seeing above, hover the mouse on the required variable. Click on the pin button on the right end.

 

image

You can see close button to close the watch unpin button and expand button. You can also add the comments as you’re seeing above.

Once you step through debugging process, you can see this changing as below. if the data is updated, it will be displayed in red color.

image

 

It’s really cool when you’re watching the arrays.

image

You can selectively pin the array items and if necessary you can see the entire array as usual.

This can be moved from the current line of display. The blue color pin on the left side of the source window will move along and on hovering, it will display to which line this watch is attached with.

The interesting thing is that Visual Studio can remember your pins and can restore when you start over the debugging.

What the drawback I found in this, we can’t specify symbols for watch variables in this window. If it’s there, we do simple memory analysis and other handy display options easily.

This is a simple use case of this feature. It will be very handy in many critical debugging situations. For e.g. while working with multiple threads etc…

Visual Studio – Using wildcard characters in the symbol pattern for a breakpoint

October 26th, 2009 Sarath Comments

If you even came across WinDBG, you might have experienced using “bm” command for setting one more breakpoints based on the pattern we’re specifying.

For e.g if we put break point like bm Create*, the debugger will put the break points in the function with starts with Create.

The similar feature is available in Visual Studio as well. As an example, consider the following class ‘CPerson’

image

and suppose if we want to set the break points on all set function, we can do as do as follows.

Take New Break Point from Debug Menu

image

Give your wild characters to break at desired function

11

Once you start debugging you can see that break-points appears as specified…

image

Cool isn’t it?

How to enable DML support in WinDBG? (interactive debugger output with hyperlinks)

October 23rd, 2009 Sarath Comments

As everyone knows WinDBG is the most powerful debugger in Windows. But few people find it’s difficult because it’s not friendly like Visual Studio. Only raw text output in the debugger console. (of course thread,process,local watch windows etc. are available) but still its interesting if you can access few quick relevant information with a single click? WinDBG supports embedding hyperlinks in the command output with DML(Debugger Markup language).

As an example, if you faced some crash issues with some wrong version of DLL, probably you might be needed to check the version of the DLL loaded into process’s address space.

lm is the command used to display list the loaded modules. Ok just try with lmD

image

You can see that on clicking the hyperlink shdocvw windbg send the command hidden in that link (lmDvmshdocvw – lm (list modules) D(DML) m(pattern)module name) and displays details of the corresponding DLL. The behavior changes according to the context and implementation of commands. For e.g if kb displays the call stack and the frame numbers will be enabled with DML links.On clicking the frame numbers, it jumps to corresponding stack frame in the current call stack. You can see what’s the command going to be executed at status bar by hovering the mouse over the link.

Not all commands are implemented DML support. You can turn on/off DML support globally according to your convenience. Once the DML support enabled globally, WinDBG will automatically calls the DML version of the commands if available.

You can turn on DML support by – .prefer_dml 1

You can turn this feature off by – .prefer_dml 0

Once after you enable DML mode, if you give lm command, you will get the same output of lmD. Try it with other commands as well. Happy debugging!

Categories: Debugging, Tips Tags: , , , ,

How to Debug Child Process Using WinDBG/Visual Studio?

September 20th, 2009 Sarath Comments

Have you ever came across a situation where you need to debug a child process created by your application or external application?

Usually when we need to debug an application (process) usually we’ll be attaching the particular process to debugger by executing in debug mode from the debugger itself or use “Attach process” option provided by debugger.

image 

You can debug the processes where you’ve the right debug privileges. But suppose if you’re working in a system where your application is launched by someone else and you’re facing some catastrophic errors in some critical point of execution where you’ve no chance to attach it to debugger. (e.g during startup)

In this situation usually developers modify the source code if the want to debug and put some delay, or call “DebugBreak” API to debug the program. But in some situations this is also not practical. So what we’ve to do?

We’ve two debuggers that developers use in very common. Visual Studio Debugger is one of the most popular debugger in Windows. Okay before talking about Visual Studio I’d show how we could achieve this with WinDBG, the most powerful debugger under Windows. But it’s not that flexible like Visual Studio. It’s a beast! with all power to rule the process :)

WinDBG Way

I’ve created a small program which will be crashing in the startup itself. I am not going to write a launcher to create the process, I will do that from the command line. The steps to debug the child process are

1. Launch the parent application which is going to create the desired process.

2. Attach the parent process to WinDBG (Hope you’re all set with your symbol server and source file paths for better debugging)

3. Enable Child Process debugging by giving command “.childdebg 1”  (pass 0 if you want to disable it. See the documentation)

4. Resume the process by hitting “Go” and let the parent process to create the child process.

5. You can see that WinDBG will “Break In” when the new process is created.

6. Now you can start debugging by setting Break points, watch, etc…

Visual Studio Ways

The previous method was not at all painful no? But Visual Studio doesn’t  natively support debugging multiple process. According John Robbins, it requires a serious architectural change in Visual Studio. There’s no straight way to do this. There two known method to do this.

Using Image File Execution Option with Visual Studio

Setup:

   1. Run regedit.exe
   2. Goto HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
   3. Create a new key for your exe (example: foo.exe)
   4. Create a new string value under your exe. The name of the string value is ‘Debugger’, and the value is ‘vsjitdebugger.exe’

Here is a sample registry script to do this: (save as .reg file after changing sample.exe to your application’s name)

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sample.exe]
"Debugger"="vsjitdebugger.exe"

The above method is exploiting one of native debugging feature provided by Windows. Ensure that the modification at registry is reverted back once you finish with debugging. Otherwise whenever the application is started, it will automatically starts with Visual Studio Debugger. See this blog entry for more details

Google Chrome Debug Macros

The people at Google (or those who contributed) are so smart and they’ve created few Visual Studio Macros to enable you to debug the child process. They found in some situations the Image File Execution Option doesn’t work well. And they’ve written some efficient macros to debug the child processes using Visual Studio.

You can see the macros and how to debug article in Chrome website.

Happy Debugging!

Rubber Ducking

May 14th, 2009 Sarath Comments

Hello fellow Programmer, have you ever experienced resolving your debugging problems while you explain it to someone else? If yes, we call this process as “Rubber Ducking”

It’s a very simple but practically useful technique for finding the cause of a problem by simply  explain to someone else. Why it works? By explaining the problem to someone else may help you to gain new insights to the problem.

The act of Rubber Ducking is explained in the book, “The Pragmatic Programmer”

The other person should look over your shoulder at screen and nod his head or her head constantly (like a rubber duck bobbing up and down in a bathtub). They Don’t need to say any word; the simple act of explaining step by step, what the code is supposed to do often causes the problem to leap off the screen and announce itself.

Categories: Debugging, Tips Tags: , , ,

A Critical Section is not 100% user mode synchronization object

April 24th, 2009 Sarath Comments

Recently when I was debugging a dead locked program using WinDBG, I accidently met with following stack trace where I expected to see some API calls related to Critical section. Instead it had shown like ‘WaitForSingleObject’ which is solely a kernel mode API. The thread was supposed to be wait state while other thread is owning the critical section shared among threads.

[sourcecode language='cpp']
001bf994 77de9254 76fac244 00000080 00000000 ntdll!KiFastSystemCallRet
001bf998 76fac244 00000080 00000000 00000000 ntdll!ZwWaitForSingleObject+0xc
001bfa08 76fac1b2 00000080 ffffffff 00000000 kernel32!WaitForSingleObjectEx+0xbe
001bfa1c 009015ab 00000080 ffffffff 00000000 kernel32!WaitForSingleObject+0×12
001bfb04 00901e28 00000001 008679d8 00868b80 DeadLock!wmain+0×6b [c:\users\sarath\documents\visual studio 2008\projects\deadlock\deadlock.cpp @ 21]
001bfb54 00901c6f 001bfb68 76fa4911 7ffd3000 DeadLock!__tmainCRTStartup+0×1a8 [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 579]
001bfb5c 76fa4911 7ffd3000 001bfba8 77dce4b6 DeadLock!wmainCRTStartup+0xf [f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c @ 399]
001bfb68 77dce4b6 7ffd3000 7736d75f 00000000 kernel32!BaseThreadInitThunk+0xe
001bfba8 77dce489 00901096 7ffd3000 00000000 ntdll!__RtlUserThreadStart+0×23
001bfbc0 00000000 00901096 7ffd3000 00000000 ntdll!_RtlUserThreadStart+0×1b
[/sourcecode]

Why we can see a kernel mode call here? Of course critical sections are faster than kernel mode synchronization objects, as it can avoid user mode to kernel mode transition. But the only condition is that, it shouldn’t any conflicts in acquiring the resource. Critical sections are not purely user-mode synchronization objects. If a thread tries to acquire a critical section and if the object is owned by another thread, then it’s necessary to put the thread in wait mode. To make a thread into wait state, it’s necessary to have a transition from user mode to kernel mode. Of course the critical sections are fast, if there are no contentions. If a contention occurred, then it will be using kernel mode objects to make the corresponding thread in wait state.

Here’s a short note on user mode and kernel mode

1. Kernel Mode

In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC. Various drivers and operating system services are under kernel mode.

2. User Mode

In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. The, crashes in user mode are always recoverable as most of the system calls are executed via safe APIs. Most of the code running on your computer will execute in user mode.

How to write your own trace function?

March 11th, 2009 Sarath Comments

Most of us are using TRACE, ATLTRACE macros, OuputDebugString API for  debugging purpose during our development. [Go to end and check the function if you don't want to hear more about the basics of debug strings] Debug strings are used for debugging purpose and it’s displayed by debugger during debugging. You can see it in the output window of most of the debuggers (especially in Visual Studio) and also some smart utilities like DbgView captures the system wide debugging string and it displays in it’s own window without debugging any of the process.

Mainly OutputDebugString function provided by Kernel32 DLL is used for “outputing” debug strings. There are other altenatives available like TRACE, ATLTRACE2 macros, afxDump function etc. and most of these are actually wrapping OutputDebugString API and provides flavored functionalities like formatting like printf string, dumping MFC objects etc. The most widely used are TRACE macros. There are some more alternatives for TRACE macros like TRACE0, TRACE1, TRACE2 (deprecated now). It’s nothing but impossing restrictions on the number of parameters.

Trace macros are supposed to work with debug build of the applciation and in release mode, the traces will not be available. If we approach OutputDebugString API, we will have to first format string using sprintf or CString::Format function and then pass to API. But this adds the burden of declaring temporary buffer/CString objects every time we call this function as follows

[sourcecode language='cpp']
CString csMessage;
csMessage.Format(_T(”My Data:%d”), nData );
OutputDebugString(csMessage).
[/sourcecode]

You will always have to repeat the above code wherever you need a debug trace. Ofcourse TRACE macro can be used as printf like function, but only in debug mode. So it’s better to write our own trace functions. 

The following function is  variadic function which can be used as printf function with format specifierss

[sourcecode language='cpp']
void M4DTrace( LPCTSTR lpctFormat, … )
{
static TCHAR szBuffer[1000];
va_list ArgList;
va_start( ArgList, lpctFormat );
_vstprintf_s( szBuffer, lpctFormat, ArgList );
va_end( ArgList );
OutputDebugString( szBuffer );
}
[/sourcecode]

Instead of _vsntprintf_s, you can use another formating function called wvsprintf
but I found it has some problems formatting float variables in the list. The above function can runs under both UNICODE and MBCS environment.
If you need to know under the hood of OutputDebugString, please check this article
Updated[2009-Apr-17) – updated formatting with _vstprintf_s instead of _vsntprintf_s

How to Programmatically Set Thread Name in Debugger Window(native) ?

March 9th, 2009 Sarath Comments

Most of windows Debuggers supports thread names. This is really helpful to identify the purpose of threads especially when you’re having multiple threads in your application. In Visual Studio  you can see the details of threads including it’s name in the “Threads” window. [updated types 9.15 AM 11-03-2008 IST]

image

There are no direction functions to set the thread names for a thread. But it’s possible to implement by exploiting exception handling mechanism of a debugger. The debugger will get the first chance to handle the exception when an application is being debugged. Using this concept we will be explicitly raising an exception with parameters which specifies the thread name and other information. The particular exception will be specially handled by debugger and thus it will update the name of corresponding thread.

When application running without debugger, raising exceptions lead to application crash. So we’ve to enclose the RaiseException code inside a try-except block.

Here’s the sample snippet. This has been specified in MSDN directly.

[sourcecode language='cpp']
#define MS_VC_EXCEPTION 0×406D1388

#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0×1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)

void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0×1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;

__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// printf(”Not under debugger. Swallowing exception”);
}
}
[/sourcecode]

The function can be used either by specifying the thread ID of the particular thread to be named or passing -1 as thread ID will set the name for the current thread which is calling the function. The demonstration of inside and external calling is demonstrated below. If same thread function is used to create multiple threads, then setting name from external thread or by getting current thread ID is better than passing -1 as thread ID.

[sourcecode language='cpp']
DWORD WINAPI Thread2(LPVOID)
{
// Setting for current thread
SetThreadName( -1, “DisplayThread” );
return 0;
}

DWORD WINAPI Thread1(LPVOID)
{
SetThreadName( -1, “Worker” );
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwID;
CreateThread( 0,0,Thread1, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External1″);
CreateThread( 0,0,Thread2, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External2″);
// Creating new thread using Thread2 function again
HANDLE h = CreateThread( 0,0,Thread2, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External3″);

WaitForSingleObject( h, INFINITE );
return 0;
}
[/sourcecode]

MSDN has also specified how to set thread name in Managed code

Categories: .NET, C++, Debugging, Tips, Visual Studio Tags:

Using Trace Points in Visual Studio for Debugging

February 12th, 2009 Sarath Comments

Trace points are the new debugging aid in Visual Studio. Break points are the general feature in almost all debuggers but not trace points. It’s much popular in GDB community even it’s a bit late, Microsoft introduced trace points with Visual Studio 2005

Why we would use Trace points?
Sometimes during debugging it’s not possible to interrupt the program execution. The correctness of the program may affected by the delay introduced by the debugger. In such cases we can use trace points. As the name resembles break points breaks the execution of the program while trace points doesn’t (or optional). Trace points provide additional options to know the debugging information on Trace point location.

Take the following example. The function Display is being called from two different threads. To know from where the call been made, you can get the help of trace points. This scenario is common in a multi thread program

[sourcecode language='cpp']
#include

void DisplayFxn( int i )
{
printf( “\n%d”,i);
}

void ProcessValue(int i, const int nThreadID )
{
DisplayFxn(i);
}

DWORD WINAPI Thread1(LPVOID)
{
for(int i = 0; i< 100; i++ )
{
ProcessValue( i,GetCurrentThreadId());
Sleep(600);
}
return 0;
}

DWORD WINAPI Thread2(LPVOID)
{
for(int i = 0; i< 100; i++ )
{
ProcessValue( i,GetCurrentThreadId() );
Sleep(300);
}
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
HANDLE h[2];
h[0] = CreateThread( 0,0, Thread1,0,0,0);
h[1] = CreateThread( 0,0, Thread2,0,0,0);

WaitForMultipleObjects(2,h,TRUE,INFINITE);
return 0;
}
[/sourcecode]

First of all you’ve to create a trace point. You can create trace points from the scratch or convert an existing break point to trace point.

image

Now it’s time to specify the configuration of your trace point.

image

As you’re seeing in the configuration box, you can simply print the values of your variable by just giving the variable name inside curly braces.

You can also apply the appropriate predefined keywords to get enough information on the execution context. The basic list of the keywords are shown in the configuration box itself. Beside this, you can also use $TICK get current CPU tick and $FILEPOSE to insert the current file position. You can see a sample construct above. It may give following result where it contains all the specified data in output

[sourcecode language='cpp']
IN: 20Fxn: DisplayFxn(int),Thread: 0×140C Thread2 CPU Tick:0×4EC5FE Call Stack: TracePointSample.exe!DisplayFxn()
TracePointSample.exe!ProcessValue()
TracePointSample.exe!Thread2()
kernel32.dll!76ea36d6()
[Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]
ntdll.dll!77a5883c()
ntdll.dll!77a5880f()

IN: 11Fxn: DisplayFxn(int),Thread: 0xF74 Thread1 CPU Tick:0×4EC6C9 Call Stack: TracePointSample.exe!DisplayFxn()
TracePointSample.exe!ProcessValue()
TracePointSample.exe!Thread1()
kernel32.dll!76ea36d6()
[Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]
ntdll.dll!77a5883c()
ntdll.dll!77a5880f()
[/sourcecode]

Ok it’s time for your own try. Remember once more, this can be used effectively in time-out debugging situation(server client where server has a put some time out but delay from client because of debugging), debugging paint operations etc…. Check the documentation as well for more information