Search code examples
clinuxdebugginggdb

Watch a memory range in gdb?


I am debugging a program in gdb and I want the program to stop when the memory region 0x08049000 to 0x0804a000 is accessed. When I try to set memory breakpoints manually, gdb does not seem to support more than two locations at a time.

(gdb) awatch *0x08049000
Hardware access (read/write) watchpoint 1: *0x08049000
(gdb) awatch *0x08049001
Hardware access (read/write) watchpoint 2: *0x08049001
(gdb) awatch *0x08049002
Hardware access (read/write) watchpoint 3: *0x08049002
(gdb) run
Starting program: /home/iblue/git/some-code/some-executable
Warning:
Could not insert hardware watchpoint 3.
Could not insert hardware breakpoints:
You may have requested too many hardware breakpoints/watchpoints.

There is already a question where this has been asked and the answer was, that it may be possible to do this with valgrind. Unfortunately the answer does not contain any examples or reference to the valgrind manual, so it was not very enlightning: How can gdb be used to watch for any changes in an entire region of memory?

So: How can I watch the whole memory region?


Solution

  • I have verified that recent gdb itself does support watching a range of addresses now, then Valgrind is not a must as other answers suggested, test env:

    • GNU gdb (Ubuntu 12.1-0ubuntu1~22.04) 12.1
    • 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz

    With the command:

    watch *(char [100]*)&gbuf
    

    Then we start to watch the address range [gbuf, gbuf + 100)