Categories
Programming

Hardware read/write breakpoints

Intel processors have four hardware breakpoints, which means you can drop down into the debugger when someone writes *or reads* from a memory address. This is pretty handy when you’re working with crufty languages like C++ and you have to track down memory corruption. Of course, you could use Purify/Boundschecker but here’s a cheaper and often faster solution.

Include the header hwbreak.h in your project, and create a HWBreak object either on the stack or heap (depending on how long you want it to live for). There’s a quick example in the comments. Now when the memory at that address is modified or read, you’ll drop down into the debugger.

(After I wrote this, I found another webpage which describes a similar approach, whose URL I’ve now lost. The difference is that I jump through hoops to ensure that I only change the thread context on a suspended thread, since the API docs warn against doing it on a running thread).

Now, DevStudio already gives you access to break-on-write breakpoints via the “data breakpoints” pane – you enter WO(0x12345678) to break if the WOrd at that address is modified. But there’s no way to get break-on-read breakpoints from within DevStudio. Well, in a vanilla DevStudio. But if you’re stubborn you can hack the binary to use read-write breakpoints instead of write-only ones. Details to follow …