Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting machine instructions using gdb

Tags:

x86

trace

gdb

I need to estimate the exact starting location of some hotspot in a program, in terms of x86 machine instruction count (so that it can later be run in some emulator/simulator). Is there a way to use gdb to count the number of machine instructions being executed up to a breakpoint?

There are other alternatives of course, I could use a emulation / binary instrumentation tool (like Pin), and track the run while counting instructions, but that would require installing this tool on every platform I work on - not always possible. I need some tool that's available on pretty much any linux machine.

With gdb, I guess it's also possible to run stepi X over large strides as some sort of coarse grained search until we hit the breakpoint, then repeat with reduced the resolution, but that would be excruciatingly slow. Is there another way to do this?

like image 584
Leeor Avatar asked Feb 07 '14 12:02

Leeor


2 Answers

Try this:

set pagination off
set $count = 0
while $pc != 0xyourstoppingaddress
  stepi
  set $count++
end
print $count

Then go get a cup of coffee. Or a long lunch.

like image 63
Mark Plotnick Avatar answered Oct 07 '22 17:10

Mark Plotnick


This is actually only a slight improvement of the usability of Mark's solution.

We can define a function do_count:

define do_count
set $count=0
while ($pc != $arg0)
stepi
set $count=$count+1
end
print $count
end

and then this function can be reused for counting the number of steps over and over again:

set pagination off
do_count 0xaddress1
do_count 0xaddress2

One can even put this definition into .gdbinit (on Linux, on Windows it should be called gdb.ini) in the home-folder, so it becomes available automatically after the start of the gdb (use show user to see, whether the function was loaded).

like image 45
ead Avatar answered Oct 07 '22 19:10

ead