Search code examples
cgdbbreakpointswatchpoint

Difference software and hardware watchpoint


While reading this documentation,

I did not spot the difference between a software and a hardware watchpoint. I read that a software breakpoint (not watchpoint) replaces an instruction by an incorrect instruction to trigger an interrupt (and then stop the program), and that hardware breakpoint put the address of the instruction to stop at in a register and compares it to each executed instruction.

However, I am reading in the documentation of watchpoints that "GDB does software watchpoint in by single-stepping your program and testing the variable's value each time", which is basically the definition of a hardware watchpoint to my understanding.

Does someone have a better understanding of the difference between software and hardware watchpoint ?


Solution

  • A software watchpoint is implemented by single-stepping the program and checking the variable's value every time control returns to the debugger. This is extremely slow, since it involves multiple context switches for every instruction executed in the program under test.

    A hardware watchpoint puts the address of a memory word to watch in a special debug register. The CPU checks every memory write to see if it's targeting the address in the register, and if it is, it interrupts the program under test and returns control to the debugger. The program under test doesn't have to be single-stepped, so this is much faster, but there are usually only a few of these special debug registers, so you can only have one or two hardware watchpoints at a time.

    You might be confused about this because "single-stepping the program and checking [something] every time control returns to the debugger" sounds similar to the description you have heard for hardware breakpoints, where the CPU checks on every instruction fetch whether it has reached the breakpoint address. But with a hardware breakpoint it's the CPU doing the checking, not the debugger, which is orders of magnitude faster. And so also with a hardware watchpoint.