HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Can I set a breakpoint on 'memory access' in GDB?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
gdbaccesssetcanbreakpointmemory

Problem

I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.

Solution

watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.

You can set read watchpoints on memory locations:

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface


but one limitation applies to the rwatch and awatch commands; you can't use gdb variables
in expressions:

gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.


So you have to expand them yourself:

gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()


Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.

gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

Code Snippets

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.
gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()
gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

Context

Stack Overflow Q#58851, score: 338

Revisions (0)

No revisions yet.