Search This Blog

Thursday 18 September 2014

WinDbg : .for Command For Looping

WinDbg : .for Command For Looping 


Many a times we need to perform the same operation over multiple times in the debugger. The .for command will help ease the task. It helps us define loops, much like we do in the C-style for loop.

The .for token behaves like the for keyword in C, except that multiple increment commands must be separated by semicolons, not by commas.

The syntax is: 
.for (InitialCommand ; Condition ; IncrementCommands) { Commands }

We usually use pseudo-registers or registers to create the initialCommand and the condition of the loop. As an example lets revisit the topic of heaps. In this post we said that to display all the members of the ProcessHeaps array we need a loop. Taking the relevant portion of text from that post for the benefit of the reader, we see that the ProcessHeaps can be displayed with the following command.

kd> .for (r $t0 = 0; @$t0 < 0x4; r $t0 = @$t0 + 1){dt _HEAP poi(0x77c77500 + ((@$t0)*4)) - y SegmentSignature}
ntdll!_HEAP
   +0x008 SegmentSignature : 0xffeeffee
ntdll!_HEAP
   +0x008 SegmentSignature : 0xffeeffee
ntdll!_HEAP
   +0x008 SegmentSignature : 0xffeeffee
ntdll!_HEAP
   +0x008 SegmentSignature : 0xffeeffee

So what is happening here. We are using the pseudo-register $t0 and setting it to initial value 0 with the command r $t0 = 0. Remember the rule about *NOT* having to use the at (@) sign with the left hand operand of the r command. The rule is described in the post here. Next we create the condition of the loop by setting it to execute till it is less than 0x4. This is done by the statement @$t0 < 0x4. Then comes the increment to the value, which is done with the statement r $t0 = @$t0 + 1. Once again we see that the left hand operand for r doesn't need the at (@) sign, however, the same one in the right hand side needs it.

After this, inside the curly braces is the command to execute, which in this case is being used to print the SegmentSignature member of the _HEAP structure. Also note, that the pointer is incremented by 4 bytes (the size of pointers on an x86 machine. Since the register $t0 is a counter this will be used to calculate the indices of the array.

No comments:

Post a Comment