Using The Python API event.frame.read_register in Gdb - StevenLwcz/gdb-python GitHub Wiki

Just say you wanted to run some GDB commands each time you used (gdb) set $reg = value. You can create an event like this in a Python script.

 gdb.events.register_changed_connect(reg_changed)
 

Where reg_changed is a Python function.

  def reg_changed(event):
      print(event.regnum)

You can display the register number. But if you want the value, there is a problem. The frame.read_register() function takes a name: x0, s2, d0, etc.

      print("%s" % event.frame.read_register(name))

How do you go from the number to the name? I used:

 (gdb) maint print registers reg.txt

to dump gdb's internal view of registers to a file, then used the awk script reg.awk to turn this into a Python list. Now we can do:

 regs = ["x0", "x1", "x2", "x3", "x4", ...]
 def reg_changed(event):
    name = regs[event.regnum]
    print("%s" % event.frame.read_register(name))     # print register value
 gdb.events.register_changed.connect(reg_changed)

On its own this event is not that useful. But this is a building block for being able to do other things in Python with groups of registers and is used in the info general|single|double commands.

 # Turns the file dump from maint print registers reg.txt to a python dictionary called regs
 #
 # In gdb
 # (gdb) maint print registers reg.txt
 # From the shell command line
 # in vim, delete the header line and any wierd messages at the end of the list
 # $ awk -f reg.awk reg.txt > reg.py
 # reg.py was read into aarch64pp.py
 
 BEGIN { 
     printf("reg_dict = {"); 
 }
 
 { 
   if (NR == 1)
       printf "%d:\"%s\"", $2, $1; 
   else
       printf ", %d:\"%s\"", $2, $1; 
 END { 
     print("}"); 
 }
⚠️ **GitHub.com Fallback** ⚠️