DEV Community

mahesh_attarde
mahesh_attarde

Posted on

1

[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!!!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay