Skip to content

Instantly share code, notes, and snippets.

@jones-drew
Created October 26, 2022 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jones-drew/487791c956ceca8c18adc2847eec9c60 to your computer and use it in GitHub Desktop.
Save jones-drew/487791c956ceca8c18adc2847eec9c60 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -u -e
PREFIX="INSN_CNT"
BIN="test"
PARAMS=""
SRC="sut.S"
FN="func"
MAX_BP_JUMPS_KNOWN=$(grep -c -nP '^\s+j\s' "$SRC")
MAX_BP_JUMPS_UNKNOWN=$((MAX_BP_JUMPS_KNOWN + $(grep -c -nP '^\s+j\w*r\s' "$SRC")))
branches()
{
# Order matters, first known target jumps, then jumps, then branches
while read -r line; do
echo " gdb.Breakpoint(\"$SRC: $line\")"
done < <(grep -nP '^\s+j\s' "$SRC" | cut -d: -f1)
while read -r line; do
echo " gdb.Breakpoint(\"$SRC: $line\")"
done < <(grep -nP '^\s+j\w*r\s' "$SRC" | cut -d: -f1)
while read -r line; do
echo " gdb.Breakpoint(\"$SRC: $line\")"
done < <(grep -nP '^\s+b' "$SRC" | cut -d: -f1)
}
cat <<EOF > insn-count.py
fn = "$FN"
count = 0
branch_count = 0
jump_known_count = 0
jump_unknown_count = 0
cmd = "r $PARAMS"
not_done = True
def stop_handler(event):
global branch_count
global jump_known_count
global jump_unknown_count
global count
global cmd
global not_done
if isinstance(event, gdb.BreakpointEvent) and event.breakpoint.location == fn:
gdb.FinishBreakpoint()
cmd = "si"
elif isinstance(event, gdb.BreakpointEvent) and event.breakpoint.location.startswith("$SRC"):
count += 1
if event.breakpoint.number <= $MAX_BP_JUMPS_KNOWN:
jump_known_count += 1
elif event.breakpoint.number <= $MAX_BP_JUMPS_UNKNOWN:
jump_unknown_count += 1
else:
branch_count += 1
cmd = "si"
elif isinstance(event, gdb.BreakpointEvent):
gdb.write("$PREFIX: insn-count: {}\n".format(count))
gdb.write("$PREFIX: branch-count: {}\n".format(branch_count))
gdb.write("$PREFIX: jump-known-count: {}\n".format(jump_known_count))
gdb.write("$PREFIX: jump-unknown-count: {}\n".format(jump_unknown_count))
not_done = False
cmd = "c"
elif isinstance(event, gdb.StopEvent):
count += 1
cmd = "si"
else:
raise gdb.GdbError("Unexpected event: {}".format(event))
def insn_count():
gdb.execute("set pagination off")
gdb.execute("set confirm off")
$(branches)
gdb.Breakpoint(fn)
gdb.events.stop.connect(stop_handler)
while not_done:
gdb.execute(cmd)
gdb.execute("q")
insn_count()
EOF
echo "source insn-count.py" > insn-count.gdb
cmd="gdb -x insn-count.gdb $BIN | grep $PREFIX"
echo "$cmd"
"$cmd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment