DEV Community

mahesh_attarde
mahesh_attarde

Posted on

[DopeTales] GDB Hit Counter Script for nth time break on function

Some useful hack around gdb. While debugging we often want to wait until certain function hits nth time. Following script does that, in easy python way.

Code Explanation

We have HitMe class which inherits from gdb.BreakPoint which is classes defined in gdb python extension. It provides two methods init will define breakpoint on function and handler on hitting breakpoint. Return value of Stop function tells gdb halt or not.
hitCount is just counter to keep track of number of function hits.
In code BREAK_FUNCTION hits 40 times before breakpoint halts gdb.

# script.py
import traceback
import gdb
import subprocess
import re
import math
import json

hitCount  = 0
class HitMe(gdb.Breakpoint):
    def __init__(self):
        gdb.Breakpoint.__init__(self, "BREAK_FUNCTION")

    def stop(self):
        global hitCount
        hitCount = hitCount + 1
        print(hitCount)
        if hitCount > 40:
          return True;
        return False

print("Ran Counter For Function!")
hit = HitMe()
Enter fullscreen mode Exit fullscreen mode

Running This script

gdb -xargs binary.o arg1
...
gdb> source script.py 
gdb> run
Enter fullscreen mode Exit fullscreen mode

This will be quickest way to get there! Happy Hacking!!!

Top comments (0)