<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>technochakra.com</title>
	
	<link>http://www.technochakra.com</link>
	<description>Wheels Of Technology</description>
	<lastBuildDate>Fri, 17 Jul 2009 15:27:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/technochakra" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Assembly And The Art Of Debugging</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/Vu8xLp0PPlk/</link>
		<comments>http://www.technochakra.com/assembly-and-the-art-of-debugging/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 12:56:29 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[assembly]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=287</guid>
		<description><![CDATA[Debugging in assembly is not an optional skill to have.   Every developer encounters a situation where there is no other alternative other than cracking open the assembly code.  Here are a few reasons why a developer should get their hands dirty with this skill -]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><script type="text/javascript"><!--
google_ad_client = "pub-2898169159040774";
/* 468x60, created 7/1/09 */
google_ad_slot = "5882807646";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p><div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">This article is an introduction to understanding Intel&#8217;s assembly language while debugging a computer program.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Debugging in assembly can be a daunting task and not every developer likes to make sense of the mnemonics that appear on the screen.  While debugging, one is normally used to viewing local variables, parameters  and syntax highlighted code in the most user friendly manner and that is the primary reason why many developers dislike debugging in assembly initially.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Why Debug In Assembly?</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">1.  You have a binary and its corresponding code but the build environment is not functional.  This could be because of missing tools, unavailable compilers and the lack of understanding of complex scripts and steps needed to recreate the binary.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">2.  You are dealing with a release build only bug and the debug symbols are unavailable or you are dealing with a third party library and don&#8217;t have access to the source code.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">3.  You like to have fun.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">What You Need?</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">1.  A debugger that can display assembly language (Visual Studio, WinDbg, gdb, XCode are capable debuggers).</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">2.  A ready reference to the Intel instruction set.  Google works just fine.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">3.  Patience and maybe a link to this article.  :-)</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The key to understanding debugging in assembly is to understand how functions are called, parameters are passed, local variables accessed.  The rest can be understood by referring the Intel Instruction set while debugging the assembly code.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The diagram below is roughly how a stack should look like once a function call has been made.  When one encounters assembly, mapping the code to this diagram should simply the debugging experience.  Note that the stack grows downwards.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Passing Parameters To A Function</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Parameters are the first to be pushed onto the stack.  The caller of the function pushes them from right to left.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Cleanup Of Parameters</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Parameter cleanup may happen in the function that was called (e.g. stdcall calling convention) or by the caller of the function (e.g. cdecl).  Various kinds of calling conventions of the x86 architecture are explained in detailed in this wiki article. http://en.wikipedia.org/wiki/X86_calling_conventions  Looking right after the function call gives a good idea of what convention was being used when compiling the code.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Take note that if cleanup happens in the function being called, variable number of arguments cannot be passed to it.  Whereas it becomes possible to do this if the parameter cleanup happens outside the function.  This essentially is the main difference between stdcall and cdelc calling conventions on a x86 architecture.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The Function Call</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Before control is passed to the function, the return address where the program is supposed to resume once the function has finished execution is pushed to the stack.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">To recap, parameters are pushed first, followed by the return address.  Later depending on the calling convention of the function, you may see cleanup hhappening right after the function call or within the function itself.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">In the diagram above, as the stack grows downwards, the parameters are at the top followed by the return address.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Example</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Take a look at the snippet and the equivalent assembly below :</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The Function</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The function usually starts with a prolog and ends with an epilog</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The prolog is either a simple ENTER instruction or more commonly, it saves the ebp register and copies the stack pointer value in it so as to use it as frame pointer.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">push        ebp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">mov         ebp,esp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The epilog just reverses what the prolog had done.  It is implented by a LEAVE instruction or is implemented as follows</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">mov         esp,ebp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">pop         ebp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The ret instruction returns from the function to the return address stored in the stack.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">A compiler switch allows one to omit the frame pointer (fpo &#8211; frame pointer omission) which effectively removes the prolog and epilog and uses the ebp register for other optimizations.  It is easy to demarcate function boundaries where the frame pointer is not omitted but one should be aware of the absense of these entry and exit points.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Allocation Of Local Variables</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Local variables are allocated on the stack.  The total size of the local variables is computed at compile time and at runtime those many bytes are reserved on the stack.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">004113A0  push        ebp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">004113A1  mov         ebp,esp</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">004113A3  sub         esp,0E8h</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Note that in the example above, 232 (0xE8) bytes are being reserved for local variables.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The above code will also help in understanding why local variable allocation is much faster than requesting memory from heap.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">Local Variables And Parameters In Assembly</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The most important part in assembly is to be able to identify access to locals and parameters.  The frame pointer that is set in the prolog, acts as the reference pointer using which all variables can be accessed.  If you add to the frame pointer (Remember : P for Plus and P for Parameters), you will access parameters.  If you subtract from the frame pointer, you will be able to access local variables.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">mov         byte ptr [ebp-20h],3</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">mov         byte ptr [ebp+20h],5</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">The first line above access a local variable whereas the second accesses a parameter.</div>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">In the case of frame pointer omission, everything is calculated with respect to the stack pointer.  Therefore [esp + 20h] might refer to a local or a parameter depending on where the stack pointer currently points to.  And if say a register is pushed on the stack, the same variable will now be referred using [esp + 24h].  Debugging functions that have optimized out the frame pointer is not that easy as the changes made to the stack pointer need to be constantly tracked.</div>
<p>This article is an introduction to understanding Intel&#8217;s assembly language while debugging a computer program.</p>
<p>Debugging in assembly can be a daunting task and not every developer likes to make sense of the mnemonics that appear on the screen.</p>
<p>While debugging, one is normally used to viewing local variables, parameters  and syntax highlighted code in the most user friendly manner.  This is the primary reason why many developers dislike debugging in assembly initially.</p>
<h3>Why Debug In Assembly?</h3>
<p><span style="font-weight: normal; font-size: 13px;">Debugging in assembly is not an optional skill to have.   Every developer encounters a situation where there is no other alternative other than cracking open the assembly code.  Here are a few reasons why a developer should get their hands dirty with this skill -</span></p>
<ol>
<li> You have a binary and its corresponding code but the build environment is not functional.  This could be because of missing tools, unavailable compilers or the lack of understanding of complex scripts and steps needed to recreate the binary.</li>
<li> You are dealing with a release build only bug and the debug symbols are unavailable or you are dealing with a third party library and don&#8217;t have access to its source code.</li>
<li> You like to have fun <img src='http://www.technochakra.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
</ol>
<h3><strong>What You Need?</strong></h3>
<ol>
<li>A debugger that can display assembly language (Visual Studio, WinDbg, gdb, XCode are capable debuggers).</li>
<li>A ready reference to the Intel instruction set.  Google works just fine.</li>
<li>Patience and maybe a link to this article.  :-)</li>
</ol>
<p>The key to debugging in assembly is to understand how functions are called, parameters are passed, local variables accessed.  The code flow and logic can be understood by looking up the Intel instruction set .</p>
<p>The diagram below (click for larger image)  is roughly how a stack should look like when a function is called.  Mapping the assembly code to this diagram should simplify the debugging experience.  Note that the stack grows from top to bottom.</p>
<p><a style="text-decoration: none;" href="http://www.technochakra.com/wp-content/uploads/assembly_stack.jpg"><img class="alignnone size-medium wp-image-317" title="assembly_stack" src="http://www.technochakra.com/wp-content/uploads/assembly_stack-300x170.jpg" alt="assembly_stack" width="300" height="170" /></a></p>
<h3>Passing Parameters To A Function</h3>
<p>Parameters are the first to be pushed onto the stack.  The caller of the function pushes them from right to left.</p>
<h3>Cleanup Of Parameters</h3>
<p>Parameter cleanup may happen in the function that was called (e.g. stdcall calling convention) or by the caller of the function (e.g. cdecl).  Various kinds of calling conventions of the x86 architecture are explained in detail in<a href="http://en.wikipedia.org/wiki/X86_calling_conventions" target="_blank"> this wiki article</a>.   Stack cleanup code right after the function call gives a good idea of  the calling convention being used.</p>
<p>Take note that if cleanup happens in the function being called, variable number of arguments cannot be passed to it.  In contrast, variable number of arguments can be implemented if the parameter cleanup happens outside the function.  This essentially is the main difference between stdcall and cdelc calling conventions on a x86 architecture.</p>
<h3>The Function Call</h3>
<p>Before control is passed to the function, the return address (where the caller is supposed to resume after the function completes execution) is pushed on the stack.</p>
<p>To recap, parameters are pushed first, followed by the return address.  Later depending on the calling convention of the function, you may see cleanup happening right after the function call or within the function itself.</p>
<p>In the stack diagram above, as the stack grows downwards, the parameters are at the top followed by the return address.</p>
<h3>Example</h3>
<p>Take a look at the snippet and the equivalent assembly below :</p>
<blockquote><p>[1]<span style="white-space:pre"> </span><strong>int a = 4;</strong><br />
[2]<span style="white-space:pre"> </span>mov         dword ptr [a],4<br />
[3]<span style="white-space:pre"> </span><br />
[4]<span style="white-space:pre"> </span><strong>char c = 0;</strong><br />
[5]<span style="white-space:pre"> </span>mov         byte ptr [c],0<br />
[6]<br />
[7]<span style="white-space:pre"> </span><strong>c = f(a, 22);</strong><br />
[8]<span style="white-space:pre"> </span>push        16h<br />
[9]  <span style="white-space:pre"> </span>mov         eax,dword ptr [a]<br />
[10]  push        eax<br />
[11]<span style="white-space:pre"> </span>call        f (4111D1h)<br />
[12]<span style="white-space:pre"> </span>add         esp,8 <span style="white-space:pre"> </span><br />
[13]<span style="white-space:pre"> </span>mov         byte ptr [c],al</p></blockquote>
<ul>
<li>In line [8], the constant value 22 (16 hex) is being pushed on the stack.</li>
<li>In line [9-10] the variable &#8216;a&#8217; is pushed.</li>
<li>Line [11] is the function call to f() which implicitly pushes the return address.</li>
<li>The return value of the function is passed in a register and copied in variable &#8216;c&#8217; (line[13]).</li>
<li>In line [12] one can see that 8 bytes are being discarded from the stack as f() uses the cdecl calling convention and cleanup needs to happen in the caller function.</li>
</ul>
<h3>The Function</h3>
<p>The function usually starts with a prolog and ends with an epilog.</p>
<p>The prolog is either a simple ENTER instruction or more commonly, it saves the ebp register and copies the stack pointer value in it so as to use it as frame pointer.</p>
<blockquote><p>push        ebp<br />
mov         ebp,esp</p></blockquote>
<p>The epilog just reverses what the prolog had done.  It is implented by a LEAVE instruction or is implemented as follows</p>
<blockquote><p>mov         esp,ebp<br />
pop         ebp</p></blockquote>
<p>The ret instruction passes control from the function to the return address stored in the stack.</p>
<p>Compilers provide a switch that allows one to omit the frame pointer (fpo or frame pointer omission) which effectively removes the prolog and epilog and uses the ebp register for other optimizations.  It is easy to demarcate function boundaries where the frame pointer is present but one should be aware that the entry and exit points may be absent.</p>
<h3>Allocation Of Local Variables</h3>
<p>Local variables are allocated on the stack.  The total size of the local variables is computed at compile time and at runtime those many bytes are reserved on the stack.</p>
<blockquote><p>004113A0  push        ebp<br />
004113A1  mov         ebp,esp<br />
004113A3 <strong> sub          esp,0E8h</strong></p></blockquote>
<p>Note that in the example above, 232 (0xE8) bytes are being reserved for local variables.</p>
<p>The above code will also help in understanding why local variable allocation is much faster than requesting memory from heap.   Allocating local variables requires moving the stack pointer whereas memory heap management is much more complex.</p>
<p>As the return address and local variable area are very close to each other, buffer overflows can be caused if data is written past the the local variable area which can then overwrite the the return address.   When this return address if forced to point to shell code (or to some other code placed intentionally by a hacker), such a buffer overflow is termed as an exploit.</p>
<h3>Local Variables And Parameters In Assembly</h3>
<p>The most important part in assembly is to be able to identify access to locals and parameters.  The frame pointer that is set in the prolog, acts as the reference pointer using which all variables can be accessed.  If you add to the frame pointer (Remember : P for Plus and P for Parameters), you will be able to access parameters.  If you subtract from the frame pointer, you will be able to access local variables.</p>
<blockquote><p>mov         byte ptr [ebp-20h],3<br />
mov         byte ptr [ebp+20h],5</p></blockquote>
<p>The first line above accesses a local variable whereas the second accesses a parameter.</p>
<p>In the case of frame pointer omission, everything is calculated with respect to the stack pointer.  Therefore [esp + 20h] might refer to a local or a parameter depending on where the stack pointer currently points to.  And if say a register is pushed on the stack, the same variable will now be referred using [esp + 24h].  Debugging functions that have optimized out the frame pointer is not that easy as the changes made to the stack pointer need to be constantly tracked.</p>
<h3>Conclusion</h3>
<p>Debugging in assembly is not only fun but a useful tool to debug difficult problems.  Different debuggers provide different interfaces to interact with the assembly code but under the hood, all programs work alike.   Understanding this is the key to debugging in assembly with ease.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=Vu8xLp0PPlk:zawv2vhxApU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/Vu8xLp0PPlk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/assembly-and-the-art-of-debugging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/assembly-and-the-art-of-debugging/</feedburner:origLink></item>
		<item>
		<title>Cross-platform Debugging Cheat Sheet</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/6IJSP85XWTo/</link>
		<comments>http://www.technochakra.com/cross-platform-debugging-cheat-sheet/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 06:06:36 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[visualstudio]]></category>
		<category><![CDATA[windbg]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=231</guid>
		<description><![CDATA[If you work on multiple platforms and use different debuggers, you are expected to know the debugger&#8217;s user interfaces well enough.  At times this gets confusing especially if you have one primary  platform and you work on other platforms rather infrequently.  
I have compiled a list of my favorite features in a debugger and how [...]]]></description>
			<content:encoded><![CDATA[<p>If you work on multiple platforms and use different debuggers, you are expected to know the debugger&#8217;s user interfaces well enough.  At times this gets confusing especially if you have one primary  platform and you work on other platforms rather infrequently.  </p>
<p>I have compiled a list of my favorite features in a debugger and how to invoke them on different debuggers (Visual Studio, XCode, gdb and Windbg). </p>
<p>This is not a substitute for the debugger&#8217;s documentation but helpful for quickly switching to an unfamiliar debugging environment.  Click the image below for viewing the table or download the PDF version as a ready reference.</p>
<p><a rel="attachment wp-att-249" href="http://www.technochakra.com/cross-platform-debugging-cheat-sheet/debuggersv01/"><img class="alignnone size-medium wp-image-249" title="Debugger Cheatsheet" src="http://www.technochakra.com/wp-content/uploads/debuggersV01-300x212.jpg" alt="Debugger Cheatsheet" width="300" height="212" /></a></p>
<p><a href="http://www.technochakra.com/wp-content/uploads/debuggersV01.pdf" target="_blank">Debugger Cheat Sheet (Download PDF)</a></p>
<p>Please note :</p>
<ul>
<li>The commands (especially for gdb) are not necessarily complete and the debugger&#8217;s help should be consulted for detailed usage.</li>
<li>The list is not comprehensive and I have only put in my favorite commands that I use while debugging.  </li>
<li>A square bracket [ ] denotes a keyboard shortcut.</li>
</ul>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=6IJSP85XWTo:fTZ5icDJys4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/6IJSP85XWTo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/cross-platform-debugging-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/cross-platform-debugging-cheat-sheet/</feedburner:origLink></item>
		<item>
		<title>Debugging – Types Of Data Breakpoints In GDB</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/rLZpQFYY9gY/</link>
		<comments>http://www.technochakra.com/debugging-types-of-data-breakpoints-in-gdb/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 17:33:46 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[breakpoints]]></category>
		<category><![CDATA[gdb]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=216</guid>
		<description><![CDATA[Data breakpoints are now becoming a part of common breakpoint vocabulary.  They help in detecting heap corruption, inadvertent data overwrites and writing past buffer boundaries.

Most programmer&#8217;s restrict the definition of data breakpoints to breakpoints that help halting the execution of code in the debugger when memory is written to.  This is the kind [...]]]></description>
			<content:encoded><![CDATA[<p>Data breakpoints are now becoming a part of common breakpoint vocabulary.  They help in detecting heap corruption, inadvertent data overwrites and writing past buffer boundaries.
<p>
Most programmer&#8217;s restrict the definition of data breakpoints to breakpoints that help halting the execution of code in the debugger when memory is written to.  This is the kind of breakpoint that helps in catching most of the corruption bugs.  </p>
<p>GDB provides data breakpoints (at least on Intel platforms) that do slightly more than that.  As data breakpoints are implemented through hardware assistance, it is the hardware platform that provides the different kinds of data breakpoints and the debuggers provide the required interface.  </p>
<p><h3>watch</h3>
<p>watch is gdb&#8217;s way of setting data breakpoints which will halt the execution of a program if memory changes at the specified location.</p>
<p>watch breakpoints can either be set on the variable name or any address location.</p>
<blockquote><p>
watch my_variable<br />
watch *0&#215;12345678<br />
where 0&#215;12345678 is a valid address.
</p></blockquote>
<p>Usually a crash because of heap corruption or invalid outcome due to buffer overruns shows up in the debugger when it is too late to figure out what went wrong.  The watch or write data breakpoints can be used to find when a memory location has changed.  The debugger at that very instant shows the reason for the inadvertent change.  </p>
<p>
The cause usually is double deletion of memory, writing to deleted memory, writing past the buffer boundary, etc.  In order to fix such issues, it is more important to know when the corruption happens than to know what happens when the corruption has taken place.  </p>
<p>
Another interesting use of write data breakpoints is to find out the cause of memory leaks in reference counted objects by monitoring the increase and decrease in the reference count of the objects.  </p>
<p><h3>rwatch</h3>
<p>rwatch (read-watch) breakpoints break the execution of code when the program tries to read from a variable or memory location.   </p>
<blockquote><p>
rwatch iWasAccessed<br />
rwatch *0&#215;12345678<br />
where 0&#215;12345678 is a valid address.
</p></blockquote>
<p>For example, say you are new to your project and would like to figure out where exactly are your encryption routines in code.  As a start, you can first search your codebase but you may hit a few false positives.  If you know the memory location of your password and you set your rwatch breakpoints correctly, it would not be long before the debugger breaks execution right in your encryption algorithms which have to read the password in order to perform their function.  Getting evil ideas already?  </p>
<p>
Another use of read data breakpoints is finding out the code that is reading from memory that has already been deleted and is using this corrupt information later.  </p>
<p><h3>awatch</h3>
<p>awatch or access watches break execution of the program if a variable or memory location is written to or read from.  In summary, awatches are watches and rwatches all in one.  It is a handy way of creating one breakpoint than two separate ones.</p>
<blockquote><p>
awatch *0&#215;12345678<br />
where 0&#215;12345678 is a valid address.
</p></blockquote>
<p>
The problem with data breakpoints like any other breakpoint is that they can be triggered far too many times and the programmer may lose track of the problem being debugged.  To ensure the breakpoints are hit the least number of times, the <a href="http://www.technochakra.com/debugging-divide-and-conquer-the-input-data">data being worked upon should be minimal</a> and the breakpoint should be set as late as possible.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=rLZpQFYY9gY:6N7N47XVpNU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/rLZpQFYY9gY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/debugging-types-of-data-breakpoints-in-gdb/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/debugging-types-of-data-breakpoints-in-gdb/</feedburner:origLink></item>
		<item>
		<title>Software Breakpoints</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/QeWA8I7KoJI/</link>
		<comments>http://www.technochakra.com/software-breakpoints/#comments</comments>
		<pubDate>Wed, 13 May 2009 19:05:53 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[breakpoints]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[visualstudio]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=192</guid>
		<description><![CDATA[It is very useful to be able to break execution of code at a line number of your choice.  Breakpoints are provided in debuggers to do exactly that.  It is fun getting to the root of the problem by setting breakpoints in a debug session.  It is even more fun to know how do breakpoints work in the first place. ]]></description>
			<content:encoded><![CDATA[<p><em>Line breakpoints can be implemented either in hardware or software.  This article discusses the latter in detail. </em></p>
<p>It is very useful to be able to break execution of code at a line number of your choice.  Breakpoints are provided in debuggers to do exactly that.  It is fun getting to the root of the problem by setting breakpoints in a debug session.  It is even more fun to know how do breakpoints work in the first place.</p>
<p>Software breakpoints work by  inserting a special instruction in the program being debugged.  This special instruction on the Intel platform is &#8220;int 3&#8243;.  When executed it calls the debugger&#8217;s exception handler.</p>
<h3>Example</h3>
<p>Let us look at a very simple example that inserts a breakpoint in a program at compile time and not through a debugger.  The code uses the Intel instruction &#8220;int 3&#8243; and you may need to figure out the equivalent instruction for a non-Intel platform.<br />
<code><br />
// The code below works well with Visual Studio.<br />
int main()<br />
{<br />
__asm int 3;<br />
printf("Hello World\n");<br />
return 0;<br />
}</code><br />
<code><br />
// The code below works well with gcc + gdb<br />
int main()<br />
{<br />
asm("int $3");<br />
printf("Hello World\n");<br />
return 0;<br />
}</code></p>
<p>If you run this program in Visual Studio, you get a dialog saying &#8220;<em><strong>helloworld</strong><strong>.exe has triggered a breakpoint</strong></em>&#8220;.</p>
<p>In gdb you get the message &#8220;<strong><em>Program received signal SIGTRAP, Trace/breakpoint trap.</em></strong>&#8221;</p>
<p>In the example above, a call to &#8220;int 3&#8243; invokes the debugger&#8217;s exception handler.</p>
<p>It is also interesting to note the assembly instructions generated for the program above.</p>
<p>In Visual Studio, right click on the code and click on &#8220;Show Disassembly&#8221;. Also ensure that &#8220;Show Code Bytes&#8221; is on in the same context menu.</p>
<div class="mceTemp">
<dl id="attachment_198" class="wp-caption alignnone" style="width: 455px;">
<dt class="wp-caption-dt"><img class="size-full wp-image-198" title="vs2008_disassembly" src="http://www.technochakra.com/wp-content/uploads/vs2008_disassembly.jpg" alt="Visual Studio 2008 Disassembly" width="445" height="49" /></dt>
</dl>
</div>
<p>In gdb type disassemble at the gdb command.</p>
<blockquote><p>0&#215;0040107a &lt;main+42&gt;:   int3</p></blockquote>
<p>Now obtain the opcode of the int3 instruction using the x (examine memory) command</p>
<blockquote><p>(gdb) x/x main+42</p>
<p>0&#215;40107a &lt;main+42&gt;:     0xcc</p></blockquote>
<p>As seen above, the breakpoint opcode we inserted during compilation is 0xCC .</p>
<h3>How Do Debuggers Insert Breakpoints?</h3>
<p>For practical reasons, it is unwise to ask for a recompilation whenever a breakpoint is added or deleted.  Debuggers change the loaded image of the executable in memory and insert the &#8220;int 3&#8243; instruction at runtime.  The common steps a debugger performs to provide the functionality of a line breakpoint to a user are as follows -</p>
<ol>
<li> When a user inserts a breakpoint in a line of code, the debugger saves the opcode at that given location and replaces it with 0xCC (int 3).</li>
<li>When the program is run and it executes the &#8220;int 3&#8243; instruction, control is passed to the debugger&#8217;s exception handler.</li>
<li>The debugger notifies the user that a breakpoint has been hit.  Say that the user instructs the debugger to resume execution of the program.</li>
<li>The debugger replaces the opcode 0xCC with the one it had saved earlier.  This is done to restore the instructions to their original state.</li>
<li>The debugger then single steps the program.</li>
<li>It then resaves the original instruction and re-inserts the opcode 0xCC.  If this step were not done, the breakpoint would have been lost.  <a href="http://www.technochakra.com/temporary-breakpoint-now-you-see-it-now-you-dont/">Temporary breakpoints</a> on the other hand skip this step.</li>
<li>The debugger then resumes execution of the program.</li>
</ol>
<p>Hardware breakpoints are limited in number but debuggers are able to provide unlimited breakpoints by implementing them through software.</p>
<p>Knowing what goes behind the scenes makes debugging a bit easier.  A debugger may defer setting a breakpoint if the module is not loaded in memory yet.  It needs to replace some opcode with 0xCC and that can happen only when the module is in memory.  Likewise, a mismatch between a binary, its sources and its debug symbols (or the lack of it) may cause breakpoints to be hit at unexpected locations because the debugger is not able to correctly map the source line to the opcode that it needs to replace with 0xCC.  At times debuggers complain about the mismatch and refuse to set the breakpoints.</p>
<p>Many of the setup issues with breakpoints become obvious once we know how they work internally.  And when all else fails and release build breakpoints  adamantly refuse to work, you always have the option of compiling an &#8220;int 3&#8243; breakpoint right into your code.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=QeWA8I7KoJI:XS183Lpkt_U:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/QeWA8I7KoJI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/software-breakpoints/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/software-breakpoints/</feedburner:origLink></item>
		<item>
		<title>Profiling with procexp (process explorer)</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/xqLxiSPdHjc/</link>
		<comments>http://www.technochakra.com/profiling-with-procexp-process-explorer/#comments</comments>
		<pubDate>Fri, 05 Dec 2008 17:06:39 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[procexp]]></category>
		<category><![CDATA[profiling]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=180</guid>
		<description><![CDATA[While running your program in memory intensive workflows, you may often run into a situation where the low memory condition starts to thrash the system.  Such a program usually exhibits a performance problem as it has consumed most of its available virtual memory.  Developers often use their favorite profilers to figure out the performance bottlenecks [...]]]></description>
			<content:encoded><![CDATA[<p>While running your program in memory intensive workflows, you may often run into a situation where the low memory condition starts to thrash the system.  Such a program usually exhibits a performance problem as it has consumed most of its available virtual memory.  Developers often use their favorite profilers to figure out the performance bottlenecks though profilng such programs is difficult and sometimes impractical.  A lot of good profilers crash when collecting data in such situations.  They need additional memory and resources to collect and consolidate the data which makes the situation even worse.</p>
<p>The good thing about a program that is thrashing a system is that it tends to be in the slow portion of the code for a long period of time.  So when it is bringing down the system, it is mostly executing the code that is responsible for the situation and all we want is to take a peek at the call stack at that very moment.  An obvious choice is to use a debugger or a profiler but given the low memory condition of the system, one may get little help from such tools.  When debugging or profiling become painfully slow, people may get evil ideas of reformatting their system or may start comparing their state of the art machines with ones they had five years back <img src='http://www.technochakra.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .  This article describes a light weight profiling trick where one can get the call stack of the unresponsive program without really loading the system further.</p>
<p>Procexp (Process Explorer) is a tool from sysinternals (now Microsoft) and both the download and documentation is available at the link <a title="Download Procexp from Microsoft's site " href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" target="_blank">here</a> (Microsoft&#8217;s site).</p>
<p>The tool allows one to view the call stack of any running program on the system.  Below are the steps needed to display a call stack of any running program.</p>
<ol>
<li>Launch procexp.</li>
<li>In the process tree, find your process that is thrashing the system.</li>
<li>Right click on &#8220;Properties&#8221; and select the &#8220;Threads&#8221; tab.    
<p><div id="attachment_182" class="wp-caption alignnone" style="width: 457px"><a href="http://www.technochakra.com/wp-content/uploads/procexp_threads.jpg"><img class="size-full wp-image-182" title="procexp threads tab" src="http://www.technochakra.com/wp-content/uploads/procexp_threads.jpg" alt="procexp threads tab" width="447" height="517" /></a>    </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p><p class="wp-caption-text">procexp threads tab</p></div></li>
<li>Sort the &#8220;Cycles Delta&#8221; (on Vista) or &#8220;CSwitch Data&#8221; (on Windows XP) column in descending order and select the topmost thread.  For some programs there might be just one thread.</li>
<li>For the selected thread click on the stack button to see the current call stack of the program.  Do note that this is a snapshot of the call stack and does not change dynamically.      
<p><div id="attachment_183" class="wp-caption alignnone" style="width: 474px"><a href="http://www.technochakra.com/wp-content/uploads/procexp_call_stack.jpg"><img class="size-full wp-image-183" title="procexp call stack" src="http://www.technochakra.com/wp-content/uploads/procexp_call_stack.jpg" alt="procexp call stack" width="464" height="339" /></a>    </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p><p class="wp-caption-text">procexp call stack</p></div></li>
</ol>
<p>This call stack can provide a good insight of the area of the code that is causing the system to stall.  In the example above functiondothis() is where the thread is spending the most time.  Take more than one sample to reconfirm the findings.  This is a very unintrusive and light weight method of getting a call stack of a running program.  The same trick can be used to debug a hang but there a debugger works equally well. </p>
<p>Sometimes you don&#8217;t need heavy debugging tools and sometimes you just can&#8217;t use them.  Procexp is a nifty debugging utility (in addition to being a process explorer) that a developer should download and keep handy for times when nothing else works.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=xqLxiSPdHjc:HOQwIiLr8Ck:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/xqLxiSPdHjc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/profiling-with-procexp-process-explorer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/profiling-with-procexp-process-explorer/</feedburner:origLink></item>
		<item>
		<title>strace Those Crashes On Linux</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/vSfWl8qde_8/</link>
		<comments>http://www.technochakra.com/strace-those-crashes-on-linux/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 04:21:07 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[debugging linux]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=155</guid>
		<description><![CDATA[strace is a great tool on Linux that every developer should be aware of.  It helps trace system APIs &#8211; the APIs used, parameters passed and the error value returned.   It does not require root permissions to run.  You can generate a system call trace on a command that is executed or you can trace [...]]]></description>
			<content:encoded><![CDATA[<p>strace is a great tool on Linux that every developer should be aware of.  It helps trace system APIs &#8211; the APIs used, parameters passed and the error value returned.   It does not require root permissions to run.  You can generate a system call trace on a command that is executed or you can trace an already running process.</p>
<h3>Sample Usage</h3>
<blockquote><p>strace ./my_crashing_binary</p>
<p>strace ./my_crashing_binary 2&gt;out.txt</p>
<p>strace -p 12345 2&gt;out.txt</p></blockquote>
<h2>The strace Output</h2>
<p>A sample output of strace is given below -</p>
<blockquote><p><code><span style="color: #800000;">&lt;snip&gt;</span><br />
<span style="color: #800000;">old_mmap</span>(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000<br />
<span style="color: #800000;">mprotect</span>(0x645000, 4096, PROT_READ)     = 0<br />
<span style="color: #800000;">mprotect</span>(0x51a000, 4096, PROT_READ)     = 0<br />
<span style="color: #800000;">set_thread_area</span>({entry_number:-1 -&gt; 6, base_addr:0xb7fe16c0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0<br />
<span style="color: #800000;">munmap</span>(0xb7fe3000, 115297)              = 0<br />
<span style="color: #800000;">fstat64</span>(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 5), ...}) = 0<br />
<span style="color: #800000;">mmap2</span>(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fff000<br />
<span style="color: #800000;">write</span>(1, "Hello World\n", 12)           = 12<br />
<span style="color: #800000;">brk</span>(0)                                  = 0x940e000<br />
<span style="color: #800000;">brk</span>(0x942f000)                          = 0x942f000<br />
<span style="color: #993366;">open</span>("/myfile", O_RDONLY)               = -1 ENOENT (No such file or directory)<br />
<span style="color: #993366;">--- SIGSEGV (Segmentation fault) @ 0 (0) ---<br />
+++ killed by SIGSEGV (core dumped) +++</span><br />
</code></p></blockquote>
<p>In the above example each line of the strace output has the system call, the parameters passed to it and the return value.</p>
<p>Take note that just before the above program crashed, it tried to access <em>/myfile</em>. With experience it is not hard to guess that the file is being accessed even though it was not found.  Either this file is absolutely necessary for the program to run or the required error checks are missing that could have averted the crash.</p>
<h2>When Is strace Useful?</h2>
<p>strace is very useful while debugging crashes.  Some scenarios where strace can be helpful are -</p>
<ol>
<li>Debugging why an installation crashes on a machine.</li>
<li>Detecting file contention issues such as a file name clash while creating temporary files.</li>
<li>Debugging random crashes that are most probably due to the program running out of memory or due to it requesting an arbitrarily large chunk of memory.</li>
<li>Finding out how the program interacts with the file system.</li>
<li>Debugging crashes reproducibly only on one machine.</li>
<li>Debugging crashes in unfamilar code or in cases when sources are unavailable.</li>
</ol>
<h2>More Information</h2>
<p>This article is meant as a pointer to the strace utility but it is not a substitute for the man page.  Go to the man page to explore all options strace provides.</p>
<blockquote><p>man strace</p></blockquote>
<p>strace is not a substitute for a debugger but a lightweight tool which can be used to generate logs, diagnose common problems and study the usage of system calls in a program.  Like any other program in a programmer&#8217;s toolset, it can save a lot of debugging time if used at the right time.</p>
<p>
<iframe src="http://rcm.amazon.com/e/cm?t=technochakra-20&#038;o=1&#038;p=13&#038;l=st1&#038;mode=books&#038;search=linux%20debugging&#038;fc1=000000&#038;lt1=&#038;lc1=3366FF&#038;bg1=FFFFFF&#038;f=ifr" marginwidth="0" marginheight="0" width="468" height="60" border="0" frameborder="0" style="border:none;" scrolling="no"></iframe></p>
<p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=vSfWl8qde_8:wFW2Xu5wNEE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/vSfWl8qde_8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/strace-those-crashes-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/strace-those-crashes-on-linux/</feedburner:origLink></item>
		<item>
		<title>Temporary Breakpoint – Now You See It, Now You Don’t</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/7-kNwPGJXRg/</link>
		<comments>http://www.technochakra.com/temporary-breakpoint-now-you-see-it-now-you-dont/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 18:00:02 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[breakpoints]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[windbg]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=126</guid>
		<description><![CDATA[Have you faced the problem of breakpoint clutter where breakpoints keep piling up only to hinder the debugging session?  It is then that one realizes that there are some breakpoints that can be deleted and others disabled. 
A useful feature in a debugger is a temporary breakpoint that automagically gets deleted when hit thereby reducing the clutter of unnecessary breakpoints.  These breakpoints are [...]]]></description>
			<content:encoded><![CDATA[<p>Have you faced the problem of breakpoint clutter where breakpoints keep piling up only to hinder the debugging session?  It is then that one realizes that there are some breakpoints that can be deleted and others disabled. </p>
<p>A useful feature in a debugger is a temporary breakpoint that automagically gets deleted when hit thereby reducing the clutter of unnecessary breakpoints.  These breakpoints are useful when you wish to stop at a code location only once and do not require the execution to stop at that location ever again. </p>
<p>For example, say you are trying to determine whether a particular test scenario invokes a specific line of code or not, in that case a temporary breakpoint can be used as the breakpoint is not useful once it has been hit alteast once.</p>
<p>Below are steps on how to set temporary breakpoints in various debuggers.</p>
<h2>gdb</h2>
<p>Use the<em> <strong>tb</strong></em> command to set a temporary breakpoint in gdb.  It is similar to the <em><strong>break </strong></em>command but the breakpoint will automatically be deleted when hit.</p>
<blockquote><p><strong><span style="text-decoration: underline;">(gdb)</span></strong>help tb<br />
Set a temporary breakpoint.<br />
Like &#8220;break&#8221; except the breakpoint is only temporary,<br />
so it will be deleted when hit.  Equivalent to &#8220;break&#8221; followed<br />
by using &#8220;enable delete&#8221; on the breakpoint number.<br />
    </p></blockquote>
<h2>Windbg</h2>
<p>In Windbg, breakpoints set in the Command window using the <strong><em>bl /1</em></strong> command can be used to create temporary breakpoints.  The <strong><em>/1 </em></strong>tells Windbg that the breakpoint should be deleted when hit.</p>
<p>In Windbg temporary breakpoints are also known as &#8220;one shot breakpoints&#8221;.</p>
<h2>Visual Studio</h2>
<p>I found it a bit painful to create temporary breakpoints in Visual Studio.  The only way I could create one was by setting a breakpoint and then setting the hit count for the breakpoint to be equal to 1.   The  article <a href="http://www.technochakra.com/debugging-using-breakpoint-hit-count-for-fun-and-profit#vs_hitcount">here</a> explains how to set a hit count in Visual Studio.</p>
<p>The amount of work involved to do this sometimes doesn&#8217;t make temporary breakpoints worthwhile to set.  Moreover the breakpoint lingers on and doesn&#8217;t actually get deleted when hit.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=7-kNwPGJXRg:xLGMsDGC-_E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/7-kNwPGJXRg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/temporary-breakpoint-now-you-see-it-now-you-dont/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/temporary-breakpoint-now-you-see-it-now-you-dont/</feedburner:origLink></item>
		<item>
		<title>GDB – Debugging In Assembly</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/Ea-JBorlZZU/</link>
		<comments>http://www.technochakra.com/gdb-debugging-in-assembly/#comments</comments>
		<pubDate>Tue, 05 Aug 2008 17:55:13 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[gdb]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=112</guid>
		<description><![CDATA[If you haven&#8217;t debugged in assembly yet, you haven&#8217;t debugged enough    Debugging assembly in gdb can be tricky at times.
A normal debugging session involving assembly language consists of the following steps -

Launch the program in gdb and set the required breakpoint(s).
When the breakpoint is hit, use the disassemble command to view the assembly [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t debugged in assembly yet, you haven&#8217;t debugged enough <img src='http://www.technochakra.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   Debugging assembly in gdb can be tricky at times.</p>
<p>A normal debugging session involving assembly language consists of the following steps -</p>
<ol>
<li>Launch the program in gdb and set the required breakpoint(s).</li>
<li>When the breakpoint is hit, use the <em>disassemble</em> command to view the assembly language of the current frame.</li>
<li>Use the <em>frame</em> command and figure out the program counter and thus your location in the assembly that gdb produced in the last step.</li>
<li>Use the <em>si</em> and <em>ni</em> commands to step in and step over the instructions in assembly language.</li>
</ol>
<p>The problem is that this may require a bit of scrolling to do if the disassembled function is very long.  The display command can be used to solve this problem.</p>
<p>The display command in gdb allows a user to configure the variables that should show up each time the program is suspended.</p>
<blockquote><p><span style="text-decoration: underline;">(gdb)</span> <strong>help display</strong><br />
Print value of expression EXP each time the program stops.<br />
/FMT may be used before EXP as in the &#8220;print&#8221; command.<br />
/FMT &#8220;i&#8221; or &#8220;s&#8221; or including a size-letter is allowed,<br />
as in the &#8220;x&#8221; command, and then EXP is used to get the address to examine<br />
and examining is done as in the &#8220;x&#8221; command.</p>
<p>With no argument, display all currently requested auto-display expressions.<br />
Use &#8220;undisplay&#8221; to cancel display requests previously made.</p></blockquote>
<p>One can use the display command to view the next instruction that is about to be executed.  The pointer to the instruction yet to be executed is stored in the computer&#8217;s program counter (also known as the instruction pointer).   The following command will show the next 3 instructions that are pointed to by the program counter.</p>
<blockquote><p>display /3i $pc</p></blockquote>
<p>The /3i above causes three instructions to be printed and $pc references the program counter register.  A sample output is shown below.</p>
<blockquote><p>1: x/3i $pc<br />
0&#215;401175 &lt;main+37&gt;:     call   0&#215;4103f0 &lt;__main&gt;<br />
0&#215;40117a &lt;main+42&gt;:     lea    0xffffffe8(%ebp),%eax<br />
0&#215;40117d &lt;main+45&gt;:     mov    %eax,(%esp)<br />
<span style="text-decoration: underline;">(gdb)</span></p></blockquote>
<p>
<DIV ALIGN=CENTER><br />
<iframe src="http://rcm.amazon.com/e/cm?t=technochakra-20&#038;o=1&#038;p=6&#038;l=st1&#038;mode=books&#038;search=gdb%20debugging&#038;fc1=000000&#038;lt1=&#038;lc1=3366FF&#038;bg1=FFFFFF&#038;f=ifr" marginwidth="0" marginheight="0" width="120" height="150" border="0" frameborder="0" style="border:none;" scrolling="no"></iframe><br />
</DIV></p>
<p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=Ea-JBorlZZU:ul_li_ZwGwI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/Ea-JBorlZZU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/gdb-debugging-in-assembly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/gdb-debugging-in-assembly/</feedburner:origLink></item>
		<item>
		<title>Aliases In Visual Studio’s Command Window</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/bUL1bF7WrF8/</link>
		<comments>http://www.technochakra.com/aliases-in-visual-studios-command-window/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 06:13:01 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[debugging visualstudio]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=74</guid>
		<description><![CDATA[One trick I picked up from fellow developers was to open a file real quick in Visual Studio.  The trick was to go to the Command Window and type open &#60;filename&#62;.  This is a great productivity tip as you don&#8217;t have to search the file through the Solution Explorer.  And if you miss the command prompt after having worked with debuggers such [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.technochakra.com/wp-content/uploads/command_window_vs1.jpg"></a>One trick I picked up from fellow developers was to open a file real quick in Visual Studio.  The trick was to go to the Command Window and type <strong><em>open</em> &lt;<em>filename&gt;</em></strong>.  This is a great productivity tip as you don&#8217;t have to search the file through the Solution Explorer.  And if you miss the command prompt after having worked with debuggers such as gdb, this is a must try feature.  Try this in a huge code base and you will come to appreciate it as well.</p>
<p>I then explored the Command Window in more depth and found out that it has some real nice commands which save you a lot of mouse clicks and time.</p>
<p>The Command Window is available through the shortcut <strong>CTRL + A</strong> or through the Menu ( View -&gt; Other Windows -&gt; Command Window). </p>
<div id="attachment_98" class="wp-caption aligncenter" style="width: 418px"><a href="http://www.technochakra.com/wp-content/uploads/command_window_vs.jpg"><img class="size-full wp-image-98" title="command_window_vs" src="http://www.technochakra.com/wp-content/uploads/command_window_vs.jpg" alt="Visual Studio 2005 Command Window" width="408" height="226" /></a><p class="wp-caption-text">Visual Studio 2005 Command Window</p></div>
<p style="text-align: left;">Instead of the open command you could also have used the File.OpenFile command (analogous to Menu-&gt;File-&gt;Open File).  However the Command Window is not just an alternate way of accessing the menu. </p>
<p style="text-align: left;">The Command Window provides the ability to use aliases and to create new ones.  This is what makes it very powerful and useful.  open in the above example is an alias for File.OpenFile.  It is easy to remember and type in. </p>
<p style="text-align: left;">Visual Studio has a lot of predefined aliases and below are some that I found very useful.</p>
<p style="text-align: left;"> </p>
<p><code>alias     : lists all existing alias or creates a new alias.<br />
cls       : clears the text from the Command Window.<br />
disasm    : switches to disassembly view.<br />
code      : switches to the code view.<br />
bp        : toggle an existing breakpoint.<br />
? &lt;var&gt;   : prints the value of the variable.<br />
?? &lt;var&gt;  : displays the variable in the quickwatch window.<br />
open file : opens the file and supports auto-complete.<br />
nf        : new file.<br />
closeall  : close all open windows.<br />
|         : list processes.<br />
~         : list threads.<br />
r         : list registers.<br />
g         : run program.<br />
q         : stop debugging.</code></p>
<p> </p>
<p>New aliases can be set by using the alias command and the auto-complete facilitates this.  They continue to persist even after you have exited Visual Studio.  For example, the following command will create an alias <strong><em>only</em></strong>  that will close all files except for the active one.</p>
<p><code>alias only File.CloseAllButThis</code></p>
<p style="text-align: left;"> </p>
<p style="text-align: left;">Many aliases in the Command Window do the task that can also be performed with keyboard shortcuts.  Aliases are not meant to replace keyboard shortcuts or menu items but provides an alternative way of debugging in Visual Studio which is intuitive to those who have worked on command line interfaces.  Some commands such as <em><strong>only</strong>  </em>(created above) are more easily used through the Command Window whereas others might be more accessible through keyboard shortcuts. </p>
<p>
<iframe src="http://rcm.amazon.com/e/cm?t=technochakra-20&#038;o=1&#038;p=13&#038;l=st1&#038;mode=books&#038;search=%22microsoft%20visual%20studio%22%20&#038;fc1=000000&#038;lt1=&#038;lc1=3366FF&#038;bg1=FFFFFF&#038;f=ifr" marginwidth="0" marginheight="0" width="468" height="60" border="0" frameborder="0" style="border:none;" scrolling="no"></iframe></p>
<p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=bUL1bF7WrF8:oq4FTMjfm8Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/bUL1bF7WrF8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/aliases-in-visual-studios-command-window/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/aliases-in-visual-studios-command-window/</feedburner:origLink></item>
		<item>
		<title>Debugging – Divide And Conquer The Input Data</title>
		<link>http://feedproxy.google.com/~r/technochakra/~3/OKkGGelO384/</link>
		<comments>http://www.technochakra.com/debugging-divide-and-conquer-the-input-data/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 17:47:20 +0000</pubDate>
		<dc:creator>tc</dc:creator>
				<category><![CDATA[debugging]]></category>

		<guid isPermaLink="false">http://www.technochakra.com/?p=76</guid>
		<description><![CDATA[The rule of debugging is very simple  -

"Every developer should strive to reproduce the bug by hitting the required set of breakpoints the least number of times. This allows faster and efficient debugging sessions."]]></description>
			<content:encoded><![CDATA[<p>As a developer, the first step for solving any bug is to reproduce it. This is an important step before the investigation actually begins. Once the issue is reproduced, the developer starts investigating the bug with the knowledge, tools and debugging skills at hand.  The source of the problem is then determined, a fix is proposed and later checked in after completing the unit testing and other required processes followed by the team.   This may sound very simple but there are obstacles at every step unless the bug is very trivial.    This is routine work for any seasoned software developer.</p>
<p>One mistake developers often make is to jumpstart the debugging process sooner than needed.  They fire up their favorite debugger, set the breakpoints and then start debugging when actually they should have first reduced the data set required for reproducing the bug.</p>
<p>The rule of debugging is very simple  -</p>
<p><em><strong>&#8220;Every developer should strive to reproduce the bug by hitting the required set of breakpoints the least number of times. This allows faster and efficient debugging sessions.&#8221; </strong></em></p>
<p>So if you are hitting a breakpoint hundred times more than you should have, then you are either not using the debugger efficiently or you have not worked enough to reduce the data required to reproduce the bug.</p>
<p>The latter problem is more common as sometimes developers put in little effort to reduce the input data and start debugging prematurely.   This leads to longer debugging cycles where a lot of time is wasted on investigating code that is not even relevant to the problem being solved.</p>
<p>For example, if a there is 1MB text file that is processed by your program and crashes it, then one should first try minimizing the text file such that if it is reduced any further, the crash goes away.  The text file obtained in such a manner is the smallest input data set required to reproduce the crash.  Once this goal is achieved, the program will now be processing lesser data and effectively less code will be executed which results in important breakpoints being hit fewer times.</p>
<p>Well how does the developer go about reducing the input data set?  There is no single method but the one that commonly works is to run a <a href="http://en.wikipedia.org/wiki/Binary_search">binary search</a> on the input data.  For example in the above case, the text file should be split into two.  Two text files of half MB each would be obtained and one should test to see if the crash reproduces with either one of the files.   If you still see the crash, you have halved the data set.  Then the smaller file should be again split into  two and the process should be repeated till a very small text file is obtained that still causes the crash to occur.  Depending on what your program does, you can even reduce the 1 MB text file to a single character file.  Debugging your program with a single character file is much simpler than using the initial 1MB file.</p>
<div class="mceTemp" style="text-align: center;">
<dl id="attachment_80" class="wp-caption alignnone" style="width: 330px;">
<dt class="wp-caption-dt"><a href="http://www.technochakra.com/wp-content/uploads/reduce-data-set.jpg"><img class="size-full wp-image-80" title="reduce-data-set" src="http://www.technochakra.com/wp-content/uploads/reduce-data-set.jpg" alt="reducing data set" width="320" height="320" /></a></dt>
<dd class="wp-caption-dd">Reducing The Data Set</dd>
</dl>
</div>
<p><h3>The Caveat</h3>
<p>Sometimes a large data set may have multiple issues.  By reducing it as described above, one may solve a partial problem but other problems may go unnoticed in the reduced set.  Therefore once a bug has been solved on a reduced input data set, it should be tested against the one provided with the original bug.  This ensures that no other issue that should have been fixed got ignored in a bid to made debugging more efficient.</p>
<p><h3>Final Note</h3>
<p>Reducing the input data is essential before starting the debugging process and a great productivity aid too.  If possible, this should be a part of the bug reporting process for quality engineers or customers who often log the issue.    Reducing the data may not always be possible but it is certainly worth an attempt.</p>
<p>
<iframe src="http://rcm.amazon.com/e/cm?t=technochakra-20&#038;o=1&#038;p=13&#038;l=st1&#038;mode=books&#038;search=debugging%20testing&#038;fc1=000000&#038;lt1=&#038;lc1=3366FF&#038;bg1=FFFFFF&#038;f=ifr" marginwidth="0" marginheight="0" width="468" height="60" border="0" frameborder="0" style="border:none;" scrolling="no"></iframe></p>
<p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/technochakra?a=OKkGGelO384:HwgDuvM7S9Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/technochakra?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/technochakra/~4/OKkGGelO384" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.technochakra.com/debugging-divide-and-conquer-the-input-data/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.technochakra.com/debugging-divide-and-conquer-the-input-data/</feedburner:origLink></item>
	</channel>
</rss>
