Effective WinDbg breakpoints using hit counts

I learned this debugging trick from a colleague a few days ago when we are debugging a bug together and I can’t wait to share it. Conceptually it is really a simple idea but it is very helpful.

Let’s say you are debugging a crash. You know the bug is probably in function A but you have no idea how to stop at the last time A is called before the crash (or whatever debugging events that is interesting). WinDbg actually provides a way to stop at a function when it is called N times, and then the problem becomes how do you know what N is. Here is how:

1. Start your app under debugger

2. Set a breakpoint with a big hit count: for example, bp SomeDll!A 1000

3. Run your scenario until the crash (or whatever debugging events that are interesting to you)

4. See the breakpoint hit count using ‘bl’ command. It should show you the hit count left (say 900).

5. Restart debugging. This time, set a breakpoint with hit count = 1000 – 900 (note that the numbers are typically in hex – time to bring out calc.exe)

6. Run – Now you’ve stopped at the last time function A is called.

Note that in 3 you could hit the breakpoint set in step #2 before the debugging event and in this case you just reset the breakpoint with a larger hit count and keep going. Just keep in mind that you’ve already hit that function for X number of times (X being the hit count you set in step #2) and you need to count that in the final calculation. You could repeat this multiple times but you get the idea. Of course, you can just set a very large number in the beginning to avoid all this trouble.

Like all the other debugging tips/tricks, this method has its own limitations – it doesn’t work if the repro doesn’t always execute code in the exact same way every time it runs. But in most cases, this is a simple but effective trick.